File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1198: download - view: text, annotated - select for diffs
Sun Nov 11 17:33:26 2012 UTC (11 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Code to obtain unique unix timestamp-based identifier for new group board
  moved to lonnet.pm -- &get_timebased_id() -- to facilitate re-use.
- perldoc added for get_timebased_id().

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1198 2012/11/11 17:33:26 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     return $handle;
  638: }
  639: 
  640: sub timed_flock {
  641:     my ($file,$lock_type) = @_;
  642:     my $failed=0;
  643:     eval {
  644: 	local $SIG{__DIE__}='DEFAULT';
  645: 	local $SIG{ALRM}=sub {
  646: 	    $failed=1;
  647: 	    die("failed lock");
  648: 	};
  649: 	alarm(13);
  650: 	flock($file,$lock_type);
  651: 	alarm(0);
  652:     };
  653:     if ($failed) {
  654: 	return undef;
  655:     } else {
  656: 	return 1;
  657:     }
  658: }
  659: 
  660: # ---------------------------------------------------------- Append Environment
  661: 
  662: sub appenv {
  663:     my ($newenv,$roles) = @_;
  664:     if (ref($newenv) eq 'HASH') {
  665:         foreach my $key (keys(%{$newenv})) {
  666:             my $refused = 0;
  667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  668:                 $refused = 1;
  669:                 if (ref($roles) eq 'ARRAY') {
  670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  672:                         $refused = 0;
  673:                     }
  674:                 }
  675:             }
  676:             if ($refused) {
  677:                 &logthis("<font color=\"blue\">WARNING: ".
  678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  679:                          .'</font>');
  680: 	        delete($newenv->{$key});
  681:             } else {
  682:                 $env{$key}=$newenv->{$key};
  683:             }
  684:         }
  685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  686:         if ($opened
  687: 	    && &timed_flock($env_file,LOCK_EX)
  688: 	    &&
  689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  691: 	    while (my ($key,$value) = each(%{$newenv})) {
  692: 	        $disk_env{$key} = $value;
  693: 	    }
  694: 	    untie(%disk_env);
  695:         }
  696:     }
  697:     return 'ok';
  698: }
  699: # ----------------------------------------------------- Delete from Environment
  700: 
  701: sub delenv {
  702:     my ($delthis,$regexp,$roles) = @_;
  703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  704:         my $refused = 1;
  705:         if (ref($roles) eq 'ARRAY') {
  706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  707:             if (grep(/^\Q$role\E$/,@{$roles})) {
  708:                 $refused = 0;
  709:             }
  710:         }
  711:         if ($refused) {
  712:             &logthis("<font color=\"blue\">WARNING: ".
  713:                      "Attempt to delete from environment ".$delthis);
  714:             return 'error';
  715:         }
  716:     }
  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  718:     if ($opened
  719: 	&& &timed_flock($env_file,LOCK_EX)
  720: 	&&
  721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  723: 	foreach my $key (keys(%disk_env)) {
  724: 	    if ($regexp) {
  725:                 if ($key=~/^$delthis/) {
  726:                     delete($env{$key});
  727:                     delete($disk_env{$key});
  728:                 } 
  729:             } else {
  730:                 if ($key=~/^\Q$delthis\E/) {
  731: 		    delete($env{$key});
  732: 		    delete($disk_env{$key});
  733: 	        }
  734:             }
  735: 	}
  736: 	untie(%disk_env);
  737:     }
  738:     return 'ok';
  739: }
  740: 
  741: sub get_env_multiple {
  742:     my ($name) = @_;
  743:     my @values;
  744:     if (defined($env{$name})) {
  745:         # exists is it an array
  746:         if (ref($env{$name})) {
  747:             @values=@{ $env{$name} };
  748:         } else {
  749:             $values[0]=$env{$name};
  750:         }
  751:     }
  752:     return(@values);
  753: }
  754: 
  755: # ------------------------------------------------------------------- Locking
  756: 
  757: sub set_lock {
  758:     my ($text)=@_;
  759:     $locknum++;
  760:     my $id=$$.'-'.$locknum;
  761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  762:              'session.lock.'.$id => $text});
  763:     return $id;
  764: }
  765: 
  766: sub get_locks {
  767:     my $num=0;
  768:     my %texts=();
  769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  770:        if ($lock=~/\w/) {
  771:           $num++;
  772:           $texts{$lock}=$env{'session.lock.'.$lock};
  773:        }
  774:    }
  775:    return ($num,%texts);
  776: }
  777: 
  778: sub remove_lock {
  779:     my ($id)=@_;
  780:     my $newlocks='';
  781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  782:        if (($lock=~/\w/) && ($lock ne $id)) {
  783:           $newlocks.=','.$lock;
  784:        }
  785:     }
  786:     &appenv({'session.locks' => $newlocks});
  787:     &delenv('session.lock.'.$id);
  788: }
  789: 
  790: sub remove_all_locks {
  791:     my $activelocks=$env{'session.locks'};
  792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  793:        if ($lock=~/\w/) {
  794:           &remove_lock($lock);
  795:        }
  796:     }
  797: }
  798: 
  799: 
  800: # ------------------------------------------ Find out current server userload
  801: sub userload {
  802:     my $numusers=0;
  803:     {
  804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  805: 	my $filename;
  806: 	my $curtime=time;
  807: 	while ($filename=readdir(LONIDS)) {
  808: 	    next if ($filename eq '.' || $filename eq '..');
  809: 	    next if ($filename =~ /publicuser_\d+\.id/);
  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  812: 	}
  813: 	closedir(LONIDS);
  814:     }
  815:     my $userloadpercent=0;
  816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  817:     if ($maxuserload) {
  818: 	$userloadpercent=100*$numusers/$maxuserload;
  819:     }
  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  821:     return $userloadpercent;
  822: }
  823: 
  824: # ------------------------------ Find server with least workload from spare.tab
  825: 
  826: sub spareserver {
  827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  828:     my $spare_server;
  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  831:                                                      :  $userloadpercent;
  832:     my ($uint_dom,$remotesessions);
  833:     if (($udom ne '') && (&domain($udom) ne '')) {
  834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  837:         $remotesessions = $udomdefaults{'remotesessions'};
  838:     }
  839:     my $spareshash = &this_host_spares($udom);
  840:     if (ref($spareshash) eq 'HASH') {
  841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  843:                 if ($uint_dom) {
  844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  845:                                                  $try_server));
  846:                 }
  847: 	        ($spare_server, $lowest_load) =
  848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  849:             }
  850:         }
  851: 
  852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  853: 
  854:         if (!$found_server) {
  855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  857:                     if ($uint_dom) {
  858:                         next unless (&spare_can_host($udom,$uint_dom,
  859:                                                      $remotesessions,$try_server));
  860:                     }
  861: 	            ($spare_server, $lowest_load) =
  862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  863:                 }
  864: 	    }
  865:         }
  866:     }
  867: 
  868:     if (!$want_server_name) {
  869:         my $protocol = 'http';
  870:         if ($protocol{$spare_server} eq 'https') {
  871:             $protocol = $protocol{$spare_server};
  872:         }
  873:         if (defined($spare_server)) {
  874:             my $hostname = &hostname($spare_server);
  875:             if (defined($hostname)) {
  876: 	        $spare_server = $protocol.'://'.$hostname;
  877:             }
  878:         }
  879:     }
  880:     return $spare_server;
  881: }
  882: 
  883: sub compare_server_load {
  884:     my ($try_server, $spare_server, $lowest_load) = @_;
  885: 
  886:     my $loadans     = &reply('load',    $try_server);
  887:     my $userloadans = &reply('userload',$try_server);
  888: 
  889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  891:     }
  892: 
  893:     my $load;
  894:     if ($loadans =~ /\d/) {
  895: 	if ($userloadans =~ /\d/) {
  896: 	    #both are numbers, pick the bigger one
  897: 	    $load = ($loadans > $userloadans) ? $loadans 
  898: 		                              : $userloadans;
  899: 	} else {
  900: 	    $load = $loadans;
  901: 	}
  902:     } else {
  903: 	$load = $userloadans;
  904:     }
  905: 
  906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  907: 	$spare_server = $try_server;
  908: 	$lowest_load  = $load;
  909:     }
  910:     return ($spare_server,$lowest_load);
  911: }
  912: 
  913: # --------------------------- ask offload servers if user already has a session
  914: sub find_existing_session {
  915:     my ($udom,$uname) = @_;
  916:     my $spareshash = &this_host_spares($udom);
  917:     if (ref($spareshash) eq 'HASH') {
  918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  921:             }
  922:         }
  923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  926:             }
  927:         }
  928:     }
  929:     return;
  930: }
  931: 
  932: # -------------------------------- ask if server already has a session for user
  933: sub has_user_session {
  934:     my ($lonid,$udom,$uname) = @_;
  935:     my $result = &reply(join(':','userhassession',
  936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  937:     return 1 if ($result eq 'ok');
  938: 
  939:     return 0;
  940: }
  941: 
  942: # --------- determine least loaded server in a user's domain which allows login
  943: 
  944: sub choose_server {
  945:     my ($udom,$checkloginvia) = @_;
  946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  947:     my %servers = &get_servers($udom);
  948:     my $lowest_load = 30000;
  949:     my ($login_host,$hostname,$portal_path,$isredirect);
  950:     foreach my $lonhost (keys(%servers)) {
  951:         my $loginvia;
  952:         if ($checkloginvia) {
  953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  954:             if ($loginvia) {
  955:                 my ($server,$path) = split(/:/,$loginvia);
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($server, $login_host, $lowest_load);
  958:                 if ($login_host eq $server) {
  959:                     $portal_path = $path;
  960:                     $isredirect = 1;
  961:                 }
  962:             } else {
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  965:                 if ($login_host eq $lonhost) {
  966:                     $portal_path = '';
  967:                     $isredirect = ''; 
  968:                 }
  969:             }
  970:         } else {
  971:             ($login_host, $lowest_load) =
  972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  973:         }
  974:     }
  975:     if ($login_host ne '') {
  976:         $hostname = &hostname($login_host);
  977:     }
  978:     return ($login_host,$hostname,$portal_path,$isredirect);
  979: }
  980: 
  981: # --------------------------------------------- Try to change a user's password
  982: 
  983: sub changepass {
  984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  985:     $currentpass = &escape($currentpass);
  986:     $newpass     = &escape($newpass);
  987:     my $lonhost = $perlvar{'lonHostID'};
  988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  989: 		       $server);
  990:     if (! $answer) {
  991: 	&logthis("No reply on password change request to $server ".
  992: 		 "by $uname in domain $udom.");
  993:     } elsif ($answer =~ "^ok") {
  994:         &logthis("$uname in $udom successfully changed their password ".
  995: 		 "on $server.");
  996:     } elsif ($answer =~ "^pwchange_failure") {
  997: 	&logthis("$uname in $udom was unable to change their password ".
  998: 		 "on $server.  The action was blocked by either lcpasswd ".
  999: 		 "or pwchange");
 1000:     } elsif ($answer =~ "^non_authorized") {
 1001:         &logthis("$uname in $udom did not get their password correct when ".
 1002: 		 "attempting to change it on $server.");
 1003:     } elsif ($answer =~ "^auth_mode_error") {
 1004:         &logthis("$uname in $udom attempted to change their password despite ".
 1005: 		 "not being locally or internally authenticated on $server.");
 1006:     } elsif ($answer =~ "^unknown_user") {
 1007:         &logthis("$uname in $udom attempted to change their password ".
 1008: 		 "on $server but were unable to because $server is not ".
 1009: 		 "their home server.");
 1010:     } elsif ($answer =~ "^refused") {
 1011: 	&logthis("$server refused to change $uname in $udom password because ".
 1012: 		 "it was sent an unencrypted request to change the password.");
 1013:     } elsif ($answer =~ "invalid_client") {
 1014:         &logthis("$server refused to change $uname in $udom password because ".
 1015:                  "it was a reset by e-mail originating from an invalid server.");
 1016:     }
 1017:     return $answer;
 1018: }
 1019: 
 1020: # ----------------------- Try to determine user's current authentication scheme
 1021: 
 1022: sub queryauthenticate {
 1023:     my ($uname,$udom)=@_;
 1024:     my $uhome=&homeserver($uname,$udom);
 1025:     if (!$uhome) {
 1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1027: 	return 'no_host';
 1028:     }
 1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1032:     }
 1033:     return $answer;
 1034: }
 1035: 
 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
 1037: 
 1038: sub authenticate {
 1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1040:     $upass=&escape($upass);
 1041:     $uname= &LONCAPA::clean_username($uname);
 1042:     my $uhome=&homeserver($uname,$udom,1);
 1043:     my $newhome;
 1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1045: # Maybe the machine was offline and only re-appeared again recently?
 1046:         &reconlonc();
 1047: # One more
 1048: 	$uhome=&homeserver($uname,$udom,1);
 1049:         if (($uhome eq 'no_host') && $checkdefauth) {
 1050:             if (defined(&domain($udom,'primary'))) {
 1051:                 $newhome=&domain($udom,'primary');
 1052:             }
 1053:             if ($newhome ne '') {
 1054:                 $uhome = $newhome;
 1055:             }
 1056:         }
 1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1059: 	    return 'no_host';
 1060:         }
 1061:     }
 1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1063:     if ($answer eq 'authorized') {
 1064:         if ($newhome) {
 1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1066:             return 'no_account_on_host'; 
 1067:         } else {
 1068:             &logthis("User $uname at $udom authorized by $uhome");
 1069:             return $uhome;
 1070:         }
 1071:     }
 1072:     if ($answer eq 'non_authorized') {
 1073: 	&logthis("User $uname at $udom rejected by $uhome");
 1074: 	return 'no_host'; 
 1075:     }
 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1077:     return 'no_host';
 1078: }
 1079: 
 1080: sub can_host_session {
 1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1082:     my $canhost = 1;
 1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1084:     if (ref($remotesessions) eq 'HASH') {
 1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1087:                 $canhost = 0;
 1088:             } else {
 1089:                 $canhost = 1;
 1090:             }
 1091:         }
 1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1094:                 $canhost = 1;
 1095:             } else {
 1096:                 $canhost = 0;
 1097:             }
 1098:         }
 1099:         if ($canhost) {
 1100:             if ($remotesessions->{'version'} ne '') {
 1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1102:                 if ($reqmajor ne '' && $reqminor ne '') {
 1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1104:                         my $major = $1;
 1105:                         my $minor = $2;
 1106:                         if (($major < $reqmajor ) ||
 1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1108:                             $canhost = 0;
 1109:                         }
 1110:                     } else {
 1111:                         $canhost = 0;
 1112:                     }
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     if ($canhost) {
 1118:         if (ref($hostedsessions) eq 'HASH') {
 1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1122:                 if (($uint_dom ne '') && 
 1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1124:                     $canhost = 0;
 1125:                 } else {
 1126:                     $canhost = 1;
 1127:                 }
 1128:             }
 1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1130:                 if (($uint_dom ne '') && 
 1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1132:                     $canhost = 1;
 1133:                 } else {
 1134:                     $canhost = 0;
 1135:                 }
 1136:             }
 1137:         }
 1138:     }
 1139:     return $canhost;
 1140: }
 1141: 
 1142: sub spare_can_host {
 1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1144:     my $canhost=1;
 1145:     my @intdoms;
 1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1147:     if (ref($internet_names) eq 'ARRAY') {
 1148:         @intdoms = @{$internet_names};
 1149:     }
 1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1156:                                      $remotesessions,
 1157:                                      $defdomdefaults{'hostedsessions'});
 1158:     }
 1159:     return $canhost;
 1160: }
 1161: 
 1162: sub this_host_spares {
 1163:     my ($dom) = @_;
 1164:     my ($dom_in_use,$lonhost_in_use,$result);
 1165:     my @hosts = &current_machine_ids();
 1166:     foreach my $lonhost (@hosts) {
 1167:         if (&host_domain($lonhost) eq $dom) {
 1168:             $dom_in_use = $dom;
 1169:             $lonhost_in_use = $lonhost;
 1170:             last;
 1171:         }
 1172:     }
 1173:     if ($dom_in_use ne '') {
 1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1175:     }
 1176:     if (ref($result) ne 'HASH') {
 1177:         $lonhost_in_use = $perlvar{'lonHostID'};
 1178:         $dom_in_use = &host_domain($lonhost_in_use);
 1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1180:         if (ref($result) ne 'HASH') {
 1181:             $result = \%spareid;
 1182:         }
 1183:     }
 1184:     return $result;
 1185: }
 1186: 
 1187: sub spares_for_offload  {
 1188:     my ($dom_in_use,$lonhost_in_use) = @_;
 1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1190:     if (defined($cached)) {
 1191:         return $result;
 1192:     } else {
 1193:         my $cachetime = 60*60*24;
 1194:         my %domconfig =
 1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1200:                 }
 1201:             }
 1202:         }
 1203:     }
 1204:     return;
 1205: }
 1206: 
 1207: sub get_lonbalancer_config {
 1208:     my ($servers) = @_;
 1209:     my ($currbalancer,$currtargets);
 1210:     if (ref($servers) eq 'HASH') {
 1211:         foreach my $server (keys(%{$servers})) {
 1212:             my %what = (
 1213:                          spareid => 1,
 1214:                          perlvar => 1,
 1215:                        );
 1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1217:             if ($result eq 'ok') {
 1218:                 if (ref($returnhash) eq 'HASH') {
 1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1221:                             $currbalancer = $server;
 1222:                             $currtargets = {};
 1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1226:                                 }
 1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1229:                                 }
 1230:                             }
 1231:                             last;
 1232:                         }
 1233:                     }
 1234:                 }
 1235:             }
 1236:         }
 1237:     }
 1238:     return ($currbalancer,$currtargets);
 1239: }
 1240: 
 1241: sub check_loadbalancing {
 1242:     my ($uname,$udom) = @_;
 1243:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1244:         $rule_in_effect,$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:         ($is_balancer,$currtargets,$currrules) = 
 1270:             &check_balancer_result($result,@hosts);
 1271:         if ($is_balancer) {
 1272:             if (ref($currrules) eq 'HASH') {
 1273:                 if ($homeintdom) {
 1274:                     if ($uname ne '') {
 1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1281:                             }
 1282:                         }
 1283:                         if ($rule_in_effect eq '') {
 1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1285:                             if ($userenv{'inststatus'} ne '') {
 1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1287:                                 my ($othertitle,$usertypes,$types) =
 1288:                                     &Apache::loncommon::sorted_inst_types($udom);
 1289:                                 if (ref($types) eq 'ARRAY') {
 1290:                                     foreach my $type (@{$types}) {
 1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1292:                                             if (exists($currrules->{$type})) {
 1293:                                                 $rule_in_effect = $currrules->{$type};
 1294:                                             }
 1295:                                         }
 1296:                                     }
 1297:                                 }
 1298:                             } else {
 1299:                                 if (exists($currrules->{'default'})) {
 1300:                                     $rule_in_effect = $currrules->{'default'};
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     } else {
 1305:                         if (exists($currrules->{'default'})) {
 1306:                             $rule_in_effect = $currrules->{'default'};
 1307:                         }
 1308:                     }
 1309:                 } else {
 1310:                     if ($currrules->{'_LC_external'} ne '') {
 1311:                         $rule_in_effect = $currrules->{'_LC_external'};
 1312:                     }
 1313:                 }
 1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1315:                                                        $uname,$udom);
 1316:             }
 1317:         }
 1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1320:         unless (defined($cached)) {
 1321:             my %domconfig =
 1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1325:             }
 1326:         }
 1327:         if (ref($result) eq 'HASH') {
 1328:             ($is_balancer,$currtargets,$currrules) = 
 1329:                 &check_balancer_result($result,@hosts);
 1330:             if ($is_balancer) {
 1331:                 if (ref($currrules) eq 'HASH') {
 1332:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1333:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1334:                     }
 1335:                 }
 1336:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1337:                                                        $uname,$udom);
 1338:             }
 1339:         } else {
 1340:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1341:                 $is_balancer = 1;
 1342:                 $offloadto = &this_host_spares($dom_in_use);
 1343:             }
 1344:         }
 1345:     } else {
 1346:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1347:             $is_balancer = 1;
 1348:             $offloadto = &this_host_spares($dom_in_use);
 1349:         }
 1350:     }
 1351:     if ($is_balancer) {
 1352:         my $lowest_load = 30000;
 1353:         if (ref($offloadto) eq 'HASH') {
 1354:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1355:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1356:                     ($otherserver,$lowest_load) =
 1357:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1358:                 }
 1359:             }
 1360:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1361: 
 1362:             if (!$found_server) {
 1363:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1364:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1365:                         ($otherserver,$lowest_load) =
 1366:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                     }
 1368:                 }
 1369:             }
 1370:         } elsif (ref($offloadto) eq 'ARRAY') {
 1371:             if (@{$offloadto} == 1) {
 1372:                 $otherserver = $offloadto->[0];
 1373:             } elsif (@{$offloadto} > 1) {
 1374:                 foreach my $try_server (@{$offloadto}) {
 1375:                     ($otherserver,$lowest_load) =
 1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                 }
 1378:             }
 1379:         }
 1380:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1381:             $is_balancer = 0;
 1382:             if ($uname ne '' && $udom ne '') {
 1383:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1384:                     
 1385:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1386:                              'user.loadbalcheck.time' => time});
 1387:                 }
 1388:             }
 1389:         }
 1390:     }
 1391:     return ($is_balancer,$otherserver);
 1392: }
 1393: 
 1394: sub check_balancer_result {
 1395:     my ($result,@hosts) = @_;
 1396:     my ($is_balancer,$currtargets,$currrules);
 1397:     if (ref($result) eq 'HASH') {
 1398:         if ($result->{'lonhost'} ne '') {
 1399:             my $currbalancer = $result->{'lonhost'};
 1400:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1401:                 $is_balancer = 1;
 1402:                 $currtargets = $result->{'targets'};
 1403:                 $currrules = $result->{'rules'};
 1404:             }
 1405:         } else {
 1406:             foreach my $key (keys(%{$result})) {
 1407:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1408:                     (ref($result->{$key}) eq 'HASH')) {
 1409:                     $is_balancer = 1;
 1410:                     $currrules = $result->{$key}{'rules'};
 1411:                     $currtargets = $result->{$key}{'targets'};
 1412:                     last;
 1413:                 }
 1414:             }
 1415:         }
 1416:     }
 1417:     return ($is_balancer,$currtargets,$currrules);
 1418: }
 1419: 
 1420: sub get_loadbalancer_targets {
 1421:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1422:     my $offloadto;
 1423:     if ($rule_in_effect eq 'none') {
 1424:         return [$perlvar{'lonHostID'}];
 1425:     } elsif ($rule_in_effect eq '') {
 1426:         $offloadto = $currtargets;
 1427:     } else {
 1428:         if ($rule_in_effect eq 'homeserver') {
 1429:             my $homeserver = &homeserver($uname,$udom);
 1430:             if ($homeserver ne 'no_host') {
 1431:                 $offloadto = [$homeserver];
 1432:             }
 1433:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1434:             my %domconfig =
 1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1437:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1438:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1439:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1440:                     }
 1441:                 }
 1442:             } else {
 1443:                 my %servers = &internet_dom_servers($udom);
 1444:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1445:                 if (&hostname($remotebalancer) ne '') {
 1446:                     $offloadto = [$remotebalancer];
 1447:                 }
 1448:             }
 1449:         } elsif (&hostname($rule_in_effect) ne '') {
 1450:             $offloadto = [$rule_in_effect];
 1451:         }
 1452:     }
 1453:     return $offloadto;
 1454: }
 1455: 
 1456: sub internet_dom_servers {
 1457:     my ($dom) = @_;
 1458:     my (%uniqservers,%servers);
 1459:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1460:     my @machinedoms = &machine_domains($primaryserver);
 1461:     foreach my $mdom (@machinedoms) {
 1462:         my %currservers = %servers;
 1463:         my %server = &get_servers($mdom);
 1464:         %servers = (%currservers,%server);
 1465:     }
 1466:     my %by_hostname;
 1467:     foreach my $id (keys(%servers)) {
 1468:         push(@{$by_hostname{$servers{$id}}},$id);
 1469:     }
 1470:     foreach my $hostname (sort(keys(%by_hostname))) {
 1471:         if (@{$by_hostname{$hostname}} > 1) {
 1472:             my $match = 0;
 1473:             foreach my $id (@{$by_hostname{$hostname}}) {
 1474:                 if (&host_domain($id) eq $dom) {
 1475:                     $uniqservers{$id} = $hostname;
 1476:                     $match = 1;
 1477:                 }
 1478:             }
 1479:             unless ($match) {
 1480:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1481:             }
 1482:         } else {
 1483:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1484:         }
 1485:     }
 1486:     return %uniqservers;
 1487: }
 1488: 
 1489: # ---------------------- Find the homebase for a user from domain's lib servers
 1490: 
 1491: my %homecache;
 1492: sub homeserver {
 1493:     my ($uname,$udom,$ignoreBadCache)=@_;
 1494:     my $index="$uname:$udom";
 1495: 
 1496:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1497: 
 1498:     my %servers = &get_servers($udom,'library');
 1499:     foreach my $tryserver (keys(%servers)) {
 1500:         next if ($ignoreBadCache ne 'true' && 
 1501: 		 exists($badServerCache{$tryserver}));
 1502: 
 1503: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1504: 	if ($answer eq 'found') {
 1505: 	    delete($badServerCache{$tryserver}); 
 1506: 	    return $homecache{$index}=$tryserver;
 1507: 	} elsif ($answer eq 'no_host') {
 1508: 	    $badServerCache{$tryserver}=1;
 1509: 	}
 1510:     }    
 1511:     return 'no_host';
 1512: }
 1513: 
 1514: # ------------------------------------- Find the usernames behind a list of IDs
 1515: 
 1516: sub idget {
 1517:     my ($udom,@ids)=@_;
 1518:     my %returnhash=();
 1519:     
 1520:     my %servers = &get_servers($udom,'library');
 1521:     foreach my $tryserver (keys(%servers)) {
 1522: 	my $idlist=join('&',@ids);
 1523: 	$idlist=~tr/A-Z/a-z/; 
 1524: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1525: 	my @answer=();
 1526: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1527: 	    @answer=split(/\&/,$reply);
 1528: 	}                    ;
 1529: 	my $i;
 1530: 	for ($i=0;$i<=$#ids;$i++) {
 1531: 	    if ($answer[$i]) {
 1532: 		$returnhash{$ids[$i]}=$answer[$i];
 1533: 	    } 
 1534: 	}
 1535:     } 
 1536:     return %returnhash;
 1537: }
 1538: 
 1539: # ------------------------------------- Find the IDs behind a list of usernames
 1540: 
 1541: sub idrget {
 1542:     my ($udom,@unames)=@_;
 1543:     my %returnhash=();
 1544:     foreach my $uname (@unames) {
 1545:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1546:     }
 1547:     return %returnhash;
 1548: }
 1549: 
 1550: # ------------------------------- Store away a list of names and associated IDs
 1551: 
 1552: sub idput {
 1553:     my ($udom,%ids)=@_;
 1554:     my %servers=();
 1555:     foreach my $uname (keys(%ids)) {
 1556: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1557:         my $uhom=&homeserver($uname,$udom);
 1558:         if ($uhom ne 'no_host') {
 1559:             my $id=&escape($ids{$uname});
 1560:             $id=~tr/A-Z/a-z/;
 1561:             my $esc_unam=&escape($uname);
 1562: 	    if ($servers{$uhom}) {
 1563: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1564:             } else {
 1565:                 $servers{$uhom}=$id.'='.$esc_unam;
 1566:             }
 1567:         }
 1568:     }
 1569:     foreach my $server (keys(%servers)) {
 1570:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1571:     }
 1572: }
 1573: 
 1574: # ------------------------------dump from db file owned by domainconfig user
 1575: sub dump_dom {
 1576:     my ($namespace, $udom, $regexp) = @_;
 1577: 
 1578:     $udom ||= $env{'user.domain'};
 1579: 
 1580:     return () unless $udom;
 1581: 
 1582:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1583: }
 1584: 
 1585: # ------------------------------------------ get items from domain db files   
 1586: 
 1587: sub get_dom {
 1588:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1589:     my $items='';
 1590:     foreach my $item (@$storearr) {
 1591:         $items.=&escape($item).'&';
 1592:     }
 1593:     $items=~s/\&$//;
 1594:     if (!$udom) {
 1595:         $udom=$env{'user.domain'};
 1596:         if (defined(&domain($udom,'primary'))) {
 1597:             $uhome=&domain($udom,'primary');
 1598:         } else {
 1599:             undef($uhome);
 1600:         }
 1601:     } else {
 1602:         if (!$uhome) {
 1603:             if (defined(&domain($udom,'primary'))) {
 1604:                 $uhome=&domain($udom,'primary');
 1605:             }
 1606:         }
 1607:     }
 1608:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1609:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1610:         my %returnhash;
 1611:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1612:             return %returnhash;
 1613:         }
 1614:         my @pairs=split(/\&/,$rep);
 1615:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1616:             return @pairs;
 1617:         }
 1618:         my $i=0;
 1619:         foreach my $item (@$storearr) {
 1620:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1621:             $i++;
 1622:         }
 1623:         return %returnhash;
 1624:     } else {
 1625:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1626:     }
 1627: }
 1628: 
 1629: # -------------------------------------------- put items in domain db files 
 1630: 
 1631: sub put_dom {
 1632:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     } 
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $items='';
 1649:         foreach my $item (keys(%$storehash)) {
 1650:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1651:         }
 1652:         $items=~s/\&$//;
 1653:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1654:     } else {
 1655:         &logthis("put_dom failed - no homeserver and/or domain");
 1656:     }
 1657: }
 1658: 
 1659: # --------------------- newput for items in db file owned by domainconfig user
 1660: sub newput_dom {
 1661:     my ($namespace,$storehash,$udom) = @_;
 1662:     my $result;
 1663:     if (!$udom) {
 1664:         $udom=$env{'user.domain'};
 1665:     }
 1666:     if ($udom) {
 1667:         my $uname = &get_domainconfiguser($udom);
 1668:         $result = &newput($namespace,$storehash,$udom,$uname);
 1669:     }
 1670:     return $result;
 1671: }
 1672: 
 1673: # --------------------- delete for items in db file owned by domainconfig user
 1674: sub del_dom {
 1675:     my ($namespace,$storearr,$udom)=@_;
 1676:     if (ref($storearr) eq 'ARRAY') {
 1677:         if (!$udom) {
 1678:             $udom=$env{'user.domain'};
 1679:         }
 1680:         if ($udom) {
 1681:             my $uname = &get_domainconfiguser($udom); 
 1682:             return &del($namespace,$storearr,$udom,$uname);
 1683:         }
 1684:     }
 1685: }
 1686: 
 1687: # ----------------------------------construct domainconfig user for a domain 
 1688: sub get_domainconfiguser {
 1689:     my ($udom) = @_;
 1690:     return $udom.'-domainconfig';
 1691: }
 1692: 
 1693: sub retrieve_inst_usertypes {
 1694:     my ($udom) = @_;
 1695:     my (%returnhash,@order);
 1696:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1697:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1698:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1699:         %returnhash = %{$domdefs{'inststatustypes'}};
 1700:         @order = @{$domdefs{'inststatusorder'}};
 1701:     } else {
 1702:         if (defined(&domain($udom,'primary'))) {
 1703:             my $uhome=&domain($udom,'primary');
 1704:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1705:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1706:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1707:                 return (\%returnhash,\@order);
 1708:             }
 1709:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1710:             my @pairs=split(/\&/,$hashitems);
 1711:             foreach my $item (@pairs) {
 1712:                 my ($key,$value)=split(/=/,$item,2);
 1713:                 $key = &unescape($key);
 1714:                 next if ($key =~ /^error: 2 /);
 1715:                 $returnhash{$key}=&thaw_unescape($value);
 1716:             }
 1717:             my @esc_order = split(/\&/,$orderitems);
 1718:             foreach my $item (@esc_order) {
 1719:                 push(@order,&unescape($item));
 1720:             }
 1721:         } else {
 1722:             &logthis("get_dom failed - no primary domain server for $udom");
 1723:         }
 1724:     }
 1725:     return (\%returnhash,\@order);
 1726: }
 1727: 
 1728: sub is_domainimage {
 1729:     my ($url) = @_;
 1730:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1731:         if (&domain($1) ne '') {
 1732:             return '1';
 1733:         }
 1734:     }
 1735:     return;
 1736: }
 1737: 
 1738: sub inst_directory_query {
 1739:     my ($srch) = @_;
 1740:     my $udom = $srch->{'srchdomain'};
 1741:     my %results;
 1742:     my $homeserver = &domain($udom,'primary');
 1743:     my $outcome;
 1744:     if ($homeserver ne '') {
 1745: 	my $queryid=&reply("querysend:instdirsearch:".
 1746: 			   &escape($srch->{'srchby'}).':'.
 1747: 			   &escape($srch->{'srchterm'}).':'.
 1748: 			   &escape($srch->{'srchtype'}),$homeserver);
 1749: 	my $host=&hostname($homeserver);
 1750: 	if ($queryid !~/^\Q$host\E\_/) {
 1751: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1752: 	    return;
 1753: 	}
 1754: 	my $response = &get_query_reply($queryid);
 1755: 	my $maxtries = 5;
 1756: 	my $tries = 1;
 1757: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1758: 	    $response = &get_query_reply($queryid);
 1759: 	    $tries ++;
 1760: 	}
 1761: 
 1762:         if (!&error($response) && $response ne 'refused') {
 1763:             if ($response eq 'unavailable') {
 1764:                 $outcome = $response;
 1765:             } else {
 1766:                 $outcome = 'ok';
 1767:                 my @matches = split(/\n/,$response);
 1768:                 foreach my $match (@matches) {
 1769:                     my ($key,$value) = split(/=/,$match);
 1770:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1771:                 }
 1772:             }
 1773:         }
 1774:     }
 1775:     return ($outcome,%results);
 1776: }
 1777: 
 1778: sub usersearch {
 1779:     my ($srch) = @_;
 1780:     my $dom = $srch->{'srchdomain'};
 1781:     my %results;
 1782:     my %libserv = &all_library();
 1783:     my $query = 'usersearch';
 1784:     foreach my $tryserver (keys(%libserv)) {
 1785:         if (&host_domain($tryserver) eq $dom) {
 1786:             my $host=&hostname($tryserver);
 1787:             my $queryid=
 1788:                 &reply("querysend:".&escape($query).':'.
 1789:                        &escape($srch->{'srchby'}).':'.
 1790:                        &escape($srch->{'srchtype'}).':'.
 1791:                        &escape($srch->{'srchterm'}),$tryserver);
 1792:             if ($queryid !~/^\Q$host\E\_/) {
 1793:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1794:                 next;
 1795:             }
 1796:             my $reply = &get_query_reply($queryid);
 1797:             my $maxtries = 1;
 1798:             my $tries = 1;
 1799:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1800:                 $reply = &get_query_reply($queryid);
 1801:                 $tries ++;
 1802:             }
 1803:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1804:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1805:             } else {
 1806:                 my @matches;
 1807:                 if ($reply =~ /\n/) {
 1808:                     @matches = split(/\n/,$reply);
 1809:                 } else {
 1810:                     @matches = split(/\&/,$reply);
 1811:                 }
 1812:                 foreach my $match (@matches) {
 1813:                     my ($uname,$udom,%userhash);
 1814:                     foreach my $entry (split(/:/,$match)) {
 1815:                         my ($key,$value) =
 1816:                             map {&unescape($_);} split(/=/,$entry);
 1817:                         $userhash{$key} = $value;
 1818:                         if ($key eq 'username') {
 1819:                             $uname = $value;
 1820:                         } elsif ($key eq 'domain') {
 1821:                             $udom = $value;
 1822:                         }
 1823:                     }
 1824:                     $results{$uname.':'.$udom} = \%userhash;
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     return %results;
 1830: }
 1831: 
 1832: sub get_instuser {
 1833:     my ($udom,$uname,$id) = @_;
 1834:     my $homeserver = &domain($udom,'primary');
 1835:     my ($outcome,%results);
 1836:     if ($homeserver ne '') {
 1837:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1838:                            &escape($id).':'.&escape($udom),$homeserver);
 1839:         my $host=&hostname($homeserver);
 1840:         if ($queryid !~/^\Q$host\E\_/) {
 1841:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1842:             return;
 1843:         }
 1844:         my $response = &get_query_reply($queryid);
 1845:         my $maxtries = 5;
 1846:         my $tries = 1;
 1847:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1848:             $response = &get_query_reply($queryid);
 1849:             $tries ++;
 1850:         }
 1851:         if (!&error($response) && $response ne 'refused') {
 1852:             if ($response eq 'unavailable') {
 1853:                 $outcome = $response;
 1854:             } else {
 1855:                 $outcome = 'ok';
 1856:                 my @matches = split(/\n/,$response);
 1857:                 foreach my $match (@matches) {
 1858:                     my ($key,$value) = split(/=/,$match);
 1859:                     $results{&unescape($key)} = &thaw_unescape($value);
 1860:                 }
 1861:             }
 1862:         }
 1863:     }
 1864:     my %userinfo;
 1865:     if (ref($results{$uname}) eq 'HASH') {
 1866:         %userinfo = %{$results{$uname}};
 1867:     } 
 1868:     return ($outcome,%userinfo);
 1869: }
 1870: 
 1871: sub inst_rulecheck {
 1872:     my ($udom,$uname,$id,$item,$rules) = @_;
 1873:     my %returnhash;
 1874:     if ($udom ne '') {
 1875:         if (ref($rules) eq 'ARRAY') {
 1876:             @{$rules} = map {&escape($_);} (@{$rules});
 1877:             my $rulestr = join(':',@{$rules});
 1878:             my $homeserver=&domain($udom,'primary');
 1879:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:                 my $response;
 1881:                 if ($item eq 'username') {                
 1882:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1883:                                               ':'.&escape($uname).':'.$rulestr,
 1884:                                               $homeserver));
 1885:                 } elsif ($item eq 'id') {
 1886:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1887:                                               ':'.&escape($id).':'.$rulestr,
 1888:                                               $homeserver));
 1889:                 } elsif ($item eq 'selfcreate') {
 1890:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1891:                                                &escape($udom).':'.&escape($uname).
 1892:                                               ':'.$rulestr,$homeserver));
 1893:                 }
 1894:                 if ($response ne 'refused') {
 1895:                     my @pairs=split(/\&/,$response);
 1896:                     foreach my $item (@pairs) {
 1897:                         my ($key,$value)=split(/=/,$item,2);
 1898:                         $key = &unescape($key);
 1899:                         next if ($key =~ /^error: 2 /);
 1900:                         $returnhash{$key}=&thaw_unescape($value);
 1901:                     }
 1902:                 }
 1903:             }
 1904:         }
 1905:     }
 1906:     return %returnhash;
 1907: }
 1908: 
 1909: sub inst_userrules {
 1910:     my ($udom,$check) = @_;
 1911:     my (%ruleshash,@ruleorder);
 1912:     if ($udom ne '') {
 1913:         my $homeserver=&domain($udom,'primary');
 1914:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1915:             my $response;
 1916:             if ($check eq 'id') {
 1917:                 $response=&reply('instidrules:'.&escape($udom),
 1918:                                  $homeserver);
 1919:             } elsif ($check eq 'email') {
 1920:                 $response=&reply('instemailrules:'.&escape($udom),
 1921:                                  $homeserver);
 1922:             } else {
 1923:                 $response=&reply('instuserrules:'.&escape($udom),
 1924:                                  $homeserver);
 1925:             }
 1926:             if (($response ne 'refused') && ($response ne 'error') && 
 1927:                 ($response ne 'unknown_cmd') && 
 1928:                 ($response ne 'no_such_host')) {
 1929:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1930:                 my @pairs=split(/\&/,$hashitems);
 1931:                 foreach my $item (@pairs) {
 1932:                     my ($key,$value)=split(/=/,$item,2);
 1933:                     $key = &unescape($key);
 1934:                     next if ($key =~ /^error: 2 /);
 1935:                     $ruleshash{$key}=&thaw_unescape($value);
 1936:                 }
 1937:                 my @esc_order = split(/\&/,$orderitems);
 1938:                 foreach my $item (@esc_order) {
 1939:                     push(@ruleorder,&unescape($item));
 1940:                 }
 1941:             }
 1942:         }
 1943:     }
 1944:     return (\%ruleshash,\@ruleorder);
 1945: }
 1946: 
 1947: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1948: 
 1949: sub get_domain_defaults {
 1950:     my ($domain) = @_;
 1951:     my $cachetime = 60*60*24;
 1952:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1953:     if (defined($cached)) {
 1954:         if (ref($result) eq 'HASH') {
 1955:             return %{$result};
 1956:         }
 1957:     }
 1958:     my %domdefaults;
 1959:     my %domconfig =
 1960:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1961:                                   'requestcourses','inststatus',
 1962:                                   'coursedefaults','usersessions',
 1963:                                   'requestauthor'],$domain);
 1964:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1965:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1966:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1967:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1968:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1969:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1970:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1971:     } else {
 1972:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1973:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1974:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1975:     }
 1976:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1977:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1978:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1979:         } else {
 1980:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1981:         } 
 1982:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1983:         foreach my $item (@usertools) {
 1984:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1985:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1986:             }
 1987:         }
 1988:     }
 1989:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1990:         foreach my $item ('official','unofficial','community') {
 1991:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1992:         }
 1993:     }
 1994:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1995:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 1996:     }
 1997:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1998:         foreach my $item ('inststatustypes','inststatusorder') {
 1999:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2000:         }
 2001:     }
 2002:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2003:         foreach my $item ('canuse_pdfforms') {
 2004:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2005:         }
 2006:     }
 2007:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2008:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2009:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2010:         }
 2011:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2012:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2013:         }
 2014:     }
 2015:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 2016:                                   $cachetime);
 2017:     return %domdefaults;
 2018: }
 2019: 
 2020: # --------------------------------------------------- Assign a key to a student
 2021: 
 2022: sub assign_access_key {
 2023: #
 2024: # a valid key looks like uname:udom#comments
 2025: # comments are being appended
 2026: #
 2027:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2028:     $kdom=
 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2030:     $knum=
 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2032:     $cdom=
 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2034:     $cnum=
 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2036:     $udom=$env{'user.name'} unless (defined($udom));
 2037:     $uname=$env{'user.domain'} unless (defined($uname));
 2038:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2039:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2040:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2041:                                                   # assigned to this person
 2042:                                                   # - this should not happen,
 2043:                                                   # unless something went wrong
 2044:                                                   # the first time around
 2045: # ready to assign
 2046:         $logentry=$1.'; '.$logentry;
 2047:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2048:                                                  $kdom,$knum) eq 'ok') {
 2049: # key now belongs to user
 2050: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2051:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2052:                 &appenv({'environment.'.$envkey => $ckey});
 2053:                 return 'ok';
 2054:             } else {
 2055:                 return 
 2056:   'error: Count not permanently assign key, will need to be re-entered later.';
 2057: 	    }
 2058:         } else {
 2059:             return 'error: Could not assign key, try again later.';
 2060:         }
 2061:     } elsif (!$existing{$ckey}) {
 2062: # the key does not exist
 2063: 	return 'error: The key does not exist';
 2064:     } else {
 2065: # the key is somebody else's
 2066: 	return 'error: The key is already in use';
 2067:     }
 2068: }
 2069: 
 2070: # ------------------------------------------ put an additional comment on a key
 2071: 
 2072: sub comment_access_key {
 2073: #
 2074: # a valid key looks like uname:udom#comments
 2075: # comments are being appended
 2076: #
 2077:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2083:     if ($existing{$ckey}) {
 2084:         $existing{$ckey}.='; '.$logentry;
 2085: # ready to assign
 2086:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2087:                                                  $cdom,$cnum) eq 'ok') {
 2088: 	    return 'ok';
 2089:         } else {
 2090: 	    return 'error: Count not store comment.';
 2091:         }
 2092:     } else {
 2093: # the key does not exist
 2094: 	return 'error: The key does not exist';
 2095:     }
 2096: }
 2097: 
 2098: # ------------------------------------------------------ Generate a set of keys
 2099: 
 2100: sub generate_access_keys {
 2101:     my ($number,$cdom,$cnum,$logentry)=@_;
 2102:     $cdom=
 2103:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2104:     $cnum=
 2105:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2106:     unless (&allowed('mky',$cdom)) { return 0; }
 2107:     unless (($cdom) && ($cnum)) { return 0; }
 2108:     if ($number>10000) { return 0; }
 2109:     sleep(2); # make sure don't get same seed twice
 2110:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2111:     my $total=0;
 2112:     for (my $i=1;$i<=$number;$i++) {
 2113:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2114:                   sprintf("%lx",int(100000*rand)).'-'.
 2115:                   sprintf("%lx",int(100000*rand));
 2116:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2117:        $newkey=~s/0/h/g; # and also 0 and O
 2118:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2119:        if ($existing{$newkey}) {
 2120:            $i--;
 2121:        } else {
 2122: 	  if (&put('accesskeys',
 2123:               { $newkey => '# generated '.localtime().
 2124:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2125:                            '; '.$logentry },
 2126: 		   $cdom,$cnum) eq 'ok') {
 2127:               $total++;
 2128: 	  }
 2129:        }
 2130:     }
 2131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2132:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2133:     return $total;
 2134: }
 2135: 
 2136: # ------------------------------------------------------- Validate an accesskey
 2137: 
 2138: sub validate_access_key {
 2139:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2140:     $cdom=
 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2142:     $cnum=
 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2144:     $udom=$env{'user.domain'} unless (defined($udom));
 2145:     $uname=$env{'user.name'} unless (defined($uname));
 2146:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2147:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2148: }
 2149: 
 2150: # ------------------------------------- Find the section of student in a course
 2151: sub devalidate_getsection_cache {
 2152:     my ($udom,$unam,$courseid)=@_;
 2153:     my $hashid="$udom:$unam:$courseid";
 2154:     &devalidate_cache_new('getsection',$hashid);
 2155: }
 2156: 
 2157: sub courseid_to_courseurl {
 2158:     my ($courseid) = @_;
 2159:     #already url style courseid
 2160:     return $courseid if ($courseid =~ m{^/});
 2161: 
 2162:     if (exists($env{'course.'.$courseid.'.num'})) {
 2163: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2164: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2165: 	return "/$cdom/$cnum";
 2166:     }
 2167: 
 2168:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2169:     if (exists($courseinfo{'num'})) {
 2170: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2171:     }
 2172: 
 2173:     return undef;
 2174: }
 2175: 
 2176: sub getsection {
 2177:     my ($udom,$unam,$courseid)=@_;
 2178:     my $cachetime=1800;
 2179: 
 2180:     my $hashid="$udom:$unam:$courseid";
 2181:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2182:     if (defined($cached)) { return $result; }
 2183: 
 2184:     my %Pending; 
 2185:     my %Expired;
 2186:     #
 2187:     # Each role can either have not started yet (pending), be active, 
 2188:     #    or have expired.
 2189:     #
 2190:     # If there is an active role, we are done.
 2191:     #
 2192:     # If there is more than one role which has not started yet, 
 2193:     #     choose the one which will start sooner
 2194:     # If there is one role which has not started yet, return it.
 2195:     #
 2196:     # If there is more than one expired role, choose the one which ended last.
 2197:     # If there is a role which has expired, return it.
 2198:     #
 2199:     $courseid = &courseid_to_courseurl($courseid);
 2200:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2201:     foreach my $key (keys(%roleshash)) {
 2202:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2203:         my $section=$1;
 2204:         if ($key eq $courseid.'_st') { $section=''; }
 2205:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2206:         my $now=time;
 2207:         if (defined($end) && $end && ($now > $end)) {
 2208:             $Expired{$end}=$section;
 2209:             next;
 2210:         }
 2211:         if (defined($start) && $start && ($now < $start)) {
 2212:             $Pending{$start}=$section;
 2213:             next;
 2214:         }
 2215:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2216:     }
 2217:     #
 2218:     # Presumedly there will be few matching roles from the above
 2219:     # loop and the sorting time will be negligible.
 2220:     if (scalar(keys(%Pending))) {
 2221:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2222:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2223:     } 
 2224:     if (scalar(keys(%Expired))) {
 2225:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2226:         my $time = pop(@sorted);
 2227:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2228:     }
 2229:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2230: }
 2231: 
 2232: sub save_cache {
 2233:     &purge_remembered();
 2234:     #&Apache::loncommon::validate_page();
 2235:     undef(%env);
 2236:     undef($env_loaded);
 2237: }
 2238: 
 2239: my $to_remember=-1;
 2240: my %remembered;
 2241: my %accessed;
 2242: my $kicks=0;
 2243: my $hits=0;
 2244: sub make_key {
 2245:     my ($name,$id) = @_;
 2246:     if (length($id) > 65 
 2247: 	&& length(&escape($id)) > 200) {
 2248: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2249:     }
 2250:     return &escape($name.':'.$id);
 2251: }
 2252: 
 2253: sub devalidate_cache_new {
 2254:     my ($name,$id,$debug) = @_;
 2255:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2256:     $id=&make_key($name,$id);
 2257:     $memcache->delete($id);
 2258:     delete($remembered{$id});
 2259:     delete($accessed{$id});
 2260: }
 2261: 
 2262: sub is_cached_new {
 2263:     my ($name,$id,$debug) = @_;
 2264:     $id=&make_key($name,$id);
 2265:     if (exists($remembered{$id})) {
 2266: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2267: 	$accessed{$id}=[&gettimeofday()];
 2268: 	$hits++;
 2269: 	return ($remembered{$id},1);
 2270:     }
 2271:     my $value = $memcache->get($id);
 2272:     if (!(defined($value))) {
 2273: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2274: 	return (undef,undef);
 2275:     }
 2276:     if ($value eq '__undef__') {
 2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2278: 	$value=undef;
 2279:     }
 2280:     &make_room($id,$value,$debug);
 2281:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2282:     return ($value,1);
 2283: }
 2284: 
 2285: sub do_cache_new {
 2286:     my ($name,$id,$value,$time,$debug) = @_;
 2287:     $id=&make_key($name,$id);
 2288:     my $setvalue=$value;
 2289:     if (!defined($setvalue)) {
 2290: 	$setvalue='__undef__';
 2291:     }
 2292:     if (!defined($time) ) {
 2293: 	$time=600;
 2294:     }
 2295:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2296:     my $result = $memcache->set($id,$setvalue,$time);
 2297:     if (! $result) {
 2298: 	&logthis("caching of id -> $id  failed");
 2299: 	$memcache->disconnect_all();
 2300:     }
 2301:     # need to make a copy of $value
 2302:     &make_room($id,$value,$debug);
 2303:     return $value;
 2304: }
 2305: 
 2306: sub make_room {
 2307:     my ($id,$value,$debug)=@_;
 2308: 
 2309:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2310:                                     : $value;
 2311:     if ($to_remember<0) { return; }
 2312:     $accessed{$id}=[&gettimeofday()];
 2313:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2314:     my $to_kick;
 2315:     my $max_time=0;
 2316:     foreach my $other (keys(%accessed)) {
 2317: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2318: 	    $to_kick=$other;
 2319: 	    $max_time=&tv_interval($accessed{$other});
 2320: 	}
 2321:     }
 2322:     delete($remembered{$to_kick});
 2323:     delete($accessed{$to_kick});
 2324:     $kicks++;
 2325:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2326:     return;
 2327: }
 2328: 
 2329: sub purge_remembered {
 2330:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2331:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2332:     undef(%remembered);
 2333:     undef(%accessed);
 2334: }
 2335: # ------------------------------------- Read an entry from a user's environment
 2336: 
 2337: sub userenvironment {
 2338:     my ($udom,$unam,@what)=@_;
 2339:     my $items;
 2340:     foreach my $item (@what) {
 2341:         $items.=&escape($item).'&';
 2342:     }
 2343:     $items=~s/\&$//;
 2344:     my %returnhash=();
 2345:     my $uhome = &homeserver($unam,$udom);
 2346:     unless ($uhome eq 'no_host') {
 2347:         my @answer=split(/\&/, 
 2348:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2349:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2350:             return %returnhash;
 2351:         }
 2352:         my $i;
 2353:         for ($i=0;$i<=$#what;$i++) {
 2354: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2355:         }
 2356:     }
 2357:     return %returnhash;
 2358: }
 2359: 
 2360: # ---------------------------------------------------------- Get a studentphoto
 2361: sub studentphoto {
 2362:     my ($udom,$unam,$ext) = @_;
 2363:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2364:     if (defined($env{'request.course.id'})) {
 2365:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2366:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2367:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2368:             } else {
 2369:                 my ($result,$perm_reqd)=
 2370: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2371:                 if ($result eq 'ok') {
 2372:                     if (!($perm_reqd eq 'yes')) {
 2373:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2374:                     }
 2375:                 }
 2376:             }
 2377:         }
 2378:     } else {
 2379:         my ($result,$perm_reqd) = 
 2380: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2381:         if ($result eq 'ok') {
 2382:             if (!($perm_reqd eq 'yes')) {
 2383:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2384:             }
 2385:         }
 2386:     }
 2387:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2388: }
 2389: 
 2390: sub retrievestudentphoto {
 2391:     my ($udom,$unam,$ext,$type) = @_;
 2392:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2393:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2394:     if ($ret eq 'ok') {
 2395:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2396:         if ($type eq 'thumbnail') {
 2397:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2398:         }
 2399:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2400:         return $tokenurl;
 2401:     } else {
 2402:         if ($type eq 'thumbnail') {
 2403:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2404:         } else { 
 2405:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2406:         }
 2407:     }
 2408: }
 2409: 
 2410: # -------------------------------------------------------------------- New chat
 2411: 
 2412: sub chatsend {
 2413:     my ($newentry,$anon,$group)=@_;
 2414:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2416:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2417:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2418: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2419: 		   &escape($newentry)).':'.$group,$chome);
 2420: }
 2421: 
 2422: # ------------------------------------------ Find current version of a resource
 2423: 
 2424: sub getversion {
 2425:     my $fname=&clutter(shift);
 2426:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2427:     return &currentversion(&filelocation('',$fname));
 2428: }
 2429: 
 2430: sub currentversion {
 2431:     my $fname=shift;
 2432:     my $author=$fname;
 2433:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2434:     my ($udom,$uname)=split(/\//,$author);
 2435:     my $home=&homeserver($uname,$udom);
 2436:     if ($home eq 'no_host') { 
 2437:         return -1; 
 2438:     }
 2439:     my $answer=&reply("currentversion:$fname",$home);
 2440:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2441: 	return -1;
 2442:     }
 2443:     return $answer;
 2444: }
 2445: 
 2446: #
 2447: # Return special version number of resource if set by override, empty otherwise
 2448: #
 2449: sub usedversion {
 2450:     my $fname=shift;
 2451:     unless ($fname) { $fname=$env{'request.uri'}; }
 2452:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2453:     if ($urlversion) { return $urlversion; }
 2454:     return '';
 2455: }
 2456: 
 2457: # ----------------------------- Subscribe to a resource, return URL if possible
 2458: 
 2459: sub subscribe {
 2460:     my $fname=shift;
 2461:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2462:     $fname=~s/[\n\r]//g;
 2463:     my $author=$fname;
 2464:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2465:     my ($udom,$uname)=split(/\//,$author);
 2466:     my $home=homeserver($uname,$udom);
 2467:     if ($home eq 'no_host') {
 2468:         return 'not_found';
 2469:     }
 2470:     my $answer=reply("sub:$fname",$home);
 2471:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2472: 	$answer.=' by '.$home;
 2473:     }
 2474:     return $answer;
 2475: }
 2476:     
 2477: # -------------------------------------------------------------- Replicate file
 2478: 
 2479: sub repcopy {
 2480:     my $filename=shift;
 2481:     $filename=~s/\/+/\//g;
 2482:     my $londocroot = $perlvar{'lonDocRoot'};
 2483:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2484:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2485:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2486: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2487: 	return &repcopy_userfile($filename);
 2488:     }
 2489:     $filename=~s/[\n\r]//g;
 2490:     my $transname="$filename.in.transfer";
 2491: # FIXME: this should flock
 2492:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2493:     my $remoteurl=subscribe($filename);
 2494:     if ($remoteurl =~ /^con_lost by/) {
 2495: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2496:            return 'unavailable';
 2497:     } elsif ($remoteurl eq 'not_found') {
 2498: 	   #&logthis("Subscribe returned not_found: $filename");
 2499: 	   return 'not_found';
 2500:     } elsif ($remoteurl =~ /^rejected by/) {
 2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2502:            return 'forbidden';
 2503:     } elsif ($remoteurl eq 'directory') {
 2504:            return 'ok';
 2505:     } else {
 2506:         my $author=$filename;
 2507:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2508:         my ($udom,$uname)=split(/\//,$author);
 2509:         my $home=homeserver($uname,$udom);
 2510:         unless ($home eq $perlvar{'lonHostID'}) {
 2511:            my @parts=split(/\//,$filename);
 2512:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2513:            if ($path ne "$londocroot/res") {
 2514:                &logthis("Malconfiguration for replication: $filename");
 2515: 	       return 'bad_request';
 2516:            }
 2517:            my $count;
 2518:            for ($count=5;$count<$#parts;$count++) {
 2519:                $path.="/$parts[$count]";
 2520:                if ((-e $path)!=1) {
 2521: 		   mkdir($path,0777);
 2522:                }
 2523:            }
 2524:            my $ua=new LWP::UserAgent;
 2525:            my $request=new HTTP::Request('GET',"$remoteurl");
 2526:            my $response=$ua->request($request,$transname);
 2527:            if ($response->is_error()) {
 2528: 	       unlink($transname);
 2529:                my $message=$response->status_line;
 2530:                &logthis("<font color=\"blue\">WARNING:"
 2531:                        ." LWP get: $message: $filename</font>");
 2532:                return 'unavailable';
 2533:            } else {
 2534: 	       if ($remoteurl!~/\.meta$/) {
 2535:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2536:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2537:                   if ($mresponse->is_error()) {
 2538: 		      unlink($filename.'.meta');
 2539:                       &logthis(
 2540:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2541:                   }
 2542: 	       }
 2543:                rename($transname,$filename);
 2544:                return 'ok';
 2545:            }
 2546:        }
 2547:     }
 2548: }
 2549: 
 2550: # ------------------------------------------------ Get server side include body
 2551: sub ssi_body {
 2552:     my ($filelink,%form)=@_;
 2553:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2554:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2555:     }
 2556:     my $output='';
 2557:     my $response;
 2558:     if ($filelink=~/^https?\:/) {
 2559:        ($output,$response)=&externalssi($filelink);
 2560:     } else {
 2561:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2562:        $filelink .= 'inhibitmenu=yes';
 2563:        ($output,$response)=&ssi($filelink,%form);
 2564:     }
 2565:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2566:     $output=~s/^.*?\<body[^\>]*\>//si;
 2567:     $output=~s/\<\/body\s*\>.*?$//si;
 2568:     if (wantarray) {
 2569:         return ($output, $response);
 2570:     } else {
 2571:         return $output;
 2572:     }
 2573: }
 2574: 
 2575: # --------------------------------------------------------- Server Side Include
 2576: 
 2577: sub absolute_url {
 2578:     my ($host_name) = @_;
 2579:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2580:     if ($host_name eq '') {
 2581: 	$host_name = $ENV{'SERVER_NAME'};
 2582:     }
 2583:     return $protocol.$host_name;
 2584: }
 2585: 
 2586: #
 2587: #   Server side include.
 2588: # Parameters:
 2589: #  fn     Possibly encrypted resource name/id.
 2590: #  form   Hash that describes how the rendering should be done
 2591: #         and other things.
 2592: # Returns:
 2593: #   Scalar context: The content of the response.
 2594: #   Array context:  2 element list of the content and the full response object.
 2595: #     
 2596: sub ssi {
 2597: 
 2598:     my ($fn,%form)=@_;
 2599:     my $ua=new LWP::UserAgent;
 2600:     my $request;
 2601: 
 2602:     $form{'no_update_last_known'}=1;
 2603:     &Apache::lonenc::check_encrypt(\$fn);
 2604:     if (%form) {
 2605:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2606:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2607:     } else {
 2608:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2609:     }
 2610: 
 2611:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2612:     my $response= $ua->request($request);
 2613:     my $content = $response->content;
 2614: 
 2615: 
 2616:     if (wantarray) {
 2617: 	return ($content, $response);
 2618:     } else {
 2619: 	return $content;
 2620:     }
 2621: }
 2622: 
 2623: sub externalssi {
 2624:     my ($url)=@_;
 2625:     my $ua=new LWP::UserAgent;
 2626:     my $request=new HTTP::Request('GET',$url);
 2627:     my $response=$ua->request($request);
 2628:     if (wantarray) {
 2629:         return ($response->content, $response);
 2630:     } else {
 2631:         return $response->content;
 2632:     }
 2633: }
 2634: 
 2635: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2636: 
 2637: sub allowuploaded {
 2638:     my ($srcurl,$url)=@_;
 2639:     $url=&clutter(&declutter($url));
 2640:     my $dir=$url;
 2641:     $dir=~s/\/[^\/]+$//;
 2642:     my %httpref=();
 2643:     my $httpurl=&hreflocation('',$url);
 2644:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2645:     &Apache::lonnet::appenv(\%httpref);
 2646: }
 2647: 
 2648: #
 2649: # Determine if the current user should be able to edit a particular resource,
 2650: # when viewing in course context.
 2651: # (a) When viewing resource used to determine if "Edit" item is included in 
 2652: #     Functions.
 2653: # (b) When displaying folder contents in course editor, used to determine if
 2654: #     "Edit" link will be displayed alongside resource.
 2655: #
 2656: #  input: six args -- filename (decluttered), course number, course domain,
 2657: #                   url, symb (if registered) and group (if this is a group
 2658: #                   item -- e.g., bulletin board, group page etc.).
 2659: #  output: array of five scalars -- 
 2660: #          $cfile -- url for file editing if editable on current server
 2661: #          $home -- homeserver of resource (i.e., for author if published,
 2662: #                                           or course if uploaded.).
 2663: #          $switchserver --  1 if server switch will be needed.
 2664: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2665: #          $forceview -- 1 if icon/link should be to go to view mode
 2666: #
 2667: 
 2668: sub can_edit_resource {
 2669:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2670:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2671: #
 2672: # For aboutme pages user can only edit his/her own.
 2673: #
 2674:     if ($resurl =~ m{^/adm/($match_domain)/($match_username)/aboutme$}) {
 2675:         my ($sdom,$sname) = ($1,$2);
 2676:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2677:             $home = $env{'user.home'};
 2678:             $cfile = $resurl;
 2679:             if ($env{'form.forceedit'}) {
 2680:                 $forceview = 1;
 2681:             } else {
 2682:                 $forceedit = 1;
 2683:             }
 2684:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2685:         } else {
 2686:             return;
 2687:         }
 2688:     }
 2689: 
 2690:     if ($env{'request.course.id'}) {
 2691:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2692:         if ($group ne '') {
 2693: # if this is a group homepage or group bulletin board, check group privs
 2694:             my $allowed = 0;
 2695:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2696:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2697:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2698:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2699:                     $allowed = 1;
 2700:                 }
 2701:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2702:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2703:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2704:                     $allowed = 1;
 2705:                 }
 2706:             }
 2707:             if ($allowed) {
 2708:                 $home=&homeserver($cnum,$cdom);
 2709:                 if ($env{'form.forceedit'}) {
 2710:                     $forceview = 1;
 2711:                 } else {
 2712:                     $forceedit = 1;
 2713:                 }
 2714:                 $cfile = $resurl;
 2715:             } else {
 2716:                 return;
 2717:             }
 2718:         } else {
 2719: #
 2720: # No edit allowed where CC has switched to student role.
 2721: #
 2722:             unless ($crsedit) {
 2723:                 return;
 2724:             }
 2725:         }
 2726:     }
 2727: 
 2728:     if ($file ne '') {
 2729:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2730:             if (&is_course_upload($file,$cnum,$cdom)) {
 2731:                 $uploaded = 1;
 2732:                 $incourse = 1;
 2733:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2734:                     $cfile = &hreflocation('',$file);
 2735:                     $forceedit = 1;
 2736:                 }
 2737:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2738:                 $incourse = 1;
 2739:                 if ($env{'form.forceedit'}) {
 2740:                     $forceview = 1;
 2741:                 } else {
 2742:                     $forceedit = 1;
 2743:                 }
 2744:                 $cfile = $resurl;
 2745:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2746:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2747:                     $incourse = 1;
 2748:                     if ($env{'form.forceedit'}) {
 2749:                         $forceview = 1;
 2750:                     } else {
 2751:                         $forceedit = 1;
 2752:                     }
 2753:                     $cfile = $resurl;
 2754:                 } elsif (($resurl eq '/res/lib/templates/simpleproblem.problem')) {
 2755:                     $incourse = 1;
 2756:                     $cfile = $resurl.'/smpedit';
 2757:                 } elsif ($resurl =~ /ext/) {
 2758:                     $incourse = 1;
 2759:                     # is external
 2760:                 }
 2761:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2762:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2763:                 if (&is_on_map($template)) { 
 2764:                     $incourse = 1;
 2765:                     $forceview = 1;
 2766:                     $cfile = $template;
 2767:                 }
 2768:             }
 2769:         }
 2770:         if ($uploaded || $incourse) {
 2771:             $home=&homeserver($cnum,$cdom);
 2772:         } else {
 2773:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2774:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2775:             # Check that the user has permission to edit this resource
 2776:             my $setpriv = 1;
 2777:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2778:             if (defined($cfudom)) {
 2779:                 $home=&homeserver($cfuname,$cfudom);
 2780:                 $cfile=$file;
 2781:             }
 2782:         }
 2783:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2784:             (($home ne '') && ($home ne 'no_host'))) {
 2785:             my @ids=&current_machine_ids();
 2786:             unless (grep(/^\Q$home\E$/,@ids)) {
 2787:                 $switchserver=1;
 2788:             }
 2789:         }
 2790:     }
 2791:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2792: }
 2793: 
 2794: sub is_course_upload {
 2795:     my ($file,$cnum,$cdom) = @_;
 2796:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2797:     $uploadpath =~ s{^\/}{};
 2798:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
 2799:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
 2800:         return 1;
 2801:     }
 2802:     return;
 2803: }
 2804: 
 2805: sub in_course {
 2806:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2807:     if ($hideprivileged) {
 2808:         my $skipuser;
 2809:         if (&privileged($uname,$udom)) {
 2810:             $skipuser = 1;
 2811:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2812:             if ($coursehash{'nothideprivileged'}) {
 2813:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2814:                     my $user;
 2815:                     if ($item =~ /:/) {
 2816:                         $user = $item;
 2817:                     } else {
 2818:                         $user = join(':',split(/[\@]/,$item));
 2819:                     }
 2820:                     if ($user eq $uname.':'.$udom) {
 2821:                         undef($skipuser);
 2822:                         last;
 2823:                     }
 2824:                 }
 2825:             }
 2826:             if ($skipuser) {
 2827:                 return 0;
 2828:             }
 2829:         }
 2830:     }
 2831:     $type ||= 'any';
 2832:     if (!defined($cdom) || !defined($cnum)) {
 2833:         my $cid  = $env{'request.course.id'};
 2834:         $cdom = $env{'course.'.$cid.'.domain'};
 2835:         $cnum = $env{'course.'.$cid.'.num'};
 2836:     }
 2837:     my $typesref;
 2838:     if (($type eq 'any') || ($type eq 'all')) {
 2839:         $typesref = ['active','previous','future'];
 2840:     } elsif ($type eq 'previous' || $type eq 'future') {
 2841:         $typesref = [$type];
 2842:     }
 2843:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2844:                               $typesref,undef,[$cdom]);
 2845:     my ($tmp) = keys(%roles);
 2846:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2847:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2848:     if (@course_roles > 0) {
 2849:         return 1;
 2850:     }
 2851:     return 0;
 2852: }
 2853: 
 2854: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2855: # input: action, courseID, current domain, intended
 2856: #        path to file, source of file, instruction to parse file for objects,
 2857: #        ref to hash for embedded objects,
 2858: #        ref to hash for codebase of java objects.
 2859: #        reference to scalar to accommodate mime type determined
 2860: #          from File::MMagic if $parser = parse.
 2861: #
 2862: # output: url to file (if action was uploaddoc), 
 2863: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2864: #
 2865: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2866: # course.
 2867: #
 2868: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2869: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2870: #          course's home server.
 2871: #
 2872: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2873: #          be copied from $source (current location) to 
 2874: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2875: #         and will then be copied to
 2876: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2877: #         course's home server.
 2878: #
 2879: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2880: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2881: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2882: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2883: #         in course's home server.
 2884: #
 2885: 
 2886: sub process_coursefile {
 2887:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2888:         $mimetype)=@_;
 2889:     my $fetchresult;
 2890:     my $home=&homeserver($docuname,$docudom);
 2891:     if ($action eq 'propagate') {
 2892:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2893: 			     $home);
 2894:     } else {
 2895:         my $fpath = '';
 2896:         my $fname = $file;
 2897:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2898:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2899:         my $filepath = &build_filepath($fpath);
 2900:         if ($action eq 'copy') {
 2901:             if ($source eq '') {
 2902:                 $fetchresult = 'no source file';
 2903:                 return $fetchresult;
 2904:             } else {
 2905:                 my $destination = $filepath.'/'.$fname;
 2906:                 rename($source,$destination);
 2907:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2908:                                  $home);
 2909:             }
 2910:         } elsif ($action eq 'uploaddoc') {
 2911:             open(my $fh,'>'.$filepath.'/'.$fname);
 2912:             print $fh $env{'form.'.$source};
 2913:             close($fh);
 2914:             if ($parser eq 'parse') {
 2915:                 my $mm = new File::MMagic;
 2916:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2917:                 if ($type eq 'text/html') {
 2918:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2919:                     unless ($parse_result eq 'ok') {
 2920:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2921:                     }
 2922:                 }
 2923:                 if (ref($mimetype)) {
 2924:                     $$mimetype = $type;
 2925:                 } 
 2926:             }
 2927:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2928:                                  $home);
 2929:             if ($fetchresult eq 'ok') {
 2930:                 return '/uploaded/'.$fpath.'/'.$fname;
 2931:             } else {
 2932:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2933:                         ' to host '.$home.': '.$fetchresult);
 2934:                 return '/adm/notfound.html';
 2935:             }
 2936:         }
 2937:     }
 2938:     unless ( $fetchresult eq 'ok') {
 2939:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2940:              ' to host '.$home.': '.$fetchresult);
 2941:     }
 2942:     return $fetchresult;
 2943: }
 2944: 
 2945: sub build_filepath {
 2946:     my ($fpath) = @_;
 2947:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2948:     unless ($fpath eq '') {
 2949:         my @parts=split('/',$fpath);
 2950:         foreach my $part (@parts) {
 2951:             $filepath.= '/'.$part;
 2952:             if ((-e $filepath)!=1) {
 2953:                 mkdir($filepath,0777);
 2954:             }
 2955:         }
 2956:     }
 2957:     return $filepath;
 2958: }
 2959: 
 2960: sub store_edited_file {
 2961:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2962:     my $file = $primary_url;
 2963:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2964:     my $fpath = '';
 2965:     my $fname = $file;
 2966:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2967:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2968:     my $filepath = &build_filepath($fpath);
 2969:     open(my $fh,'>'.$filepath.'/'.$fname);
 2970:     print $fh $content;
 2971:     close($fh);
 2972:     my $home=&homeserver($docuname,$docudom);
 2973:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2974: 			  $home);
 2975:     if ($$fetchresult eq 'ok') {
 2976:         return '/uploaded/'.$fpath.'/'.$fname;
 2977:     } else {
 2978:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2979: 		 ' to host '.$home.': '.$$fetchresult);
 2980:         return '/adm/notfound.html';
 2981:     }
 2982: }
 2983: 
 2984: sub clean_filename {
 2985:     my ($fname,$args)=@_;
 2986: # Replace Windows backslashes by forward slashes
 2987:     $fname=~s/\\/\//g;
 2988:     if (!$args->{'keep_path'}) {
 2989:         # Get rid of everything but the actual filename
 2990: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2991:     }
 2992: # Replace spaces by underscores
 2993:     $fname=~s/\s+/\_/g;
 2994: # Replace all other weird characters by nothing
 2995:     $fname=~s{[^/\w\.\-]}{}g;
 2996: # Replace all .\d. sequences with _\d. so they no longer look like version
 2997: # numbers
 2998:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2999:     return $fname;
 3000: }
 3001: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3002: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3003: # image with the same aspect ratio as the original, but with dimensions which do 
 3004: # not exceed $resizewidth and $resizeheight.
 3005:  
 3006: sub resizeImage {
 3007:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3008:     my $ima = Image::Magick->new;
 3009:     my $resized;
 3010:     if (-e $img_path) {
 3011:         $ima->Read($img_path);
 3012:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3013:             my $width = $ima->Get('width');
 3014:             my $height = $ima->Get('height');
 3015:             if ($width > $resizewidth) {
 3016: 	        my $factor = $width/$resizewidth;
 3017:                 my $newheight = $height/$factor;
 3018:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3019:                 $resized = 1;
 3020:             }
 3021:         }
 3022:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3023:             my $width = $ima->Get('width');
 3024:             my $height = $ima->Get('height');
 3025:             if ($height > $resizeheight) {
 3026:                 my $factor = $height/$resizeheight;
 3027:                 my $newwidth = $width/$factor;
 3028:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3029:                 $resized = 1;
 3030:             }
 3031:         }
 3032:         if ($resized) {
 3033:             $ima->Write($img_path);
 3034:         }
 3035:     }
 3036:     return;
 3037: }
 3038: 
 3039: # --------------- Take an uploaded file and put it into the userfiles directory
 3040: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3041: #                    the desired filename is in $env{"form.$formname.filename"}
 3042: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3043: #                                    canceloverwrite, or ''. 
 3044: #                   if 'coursedoc': upload to the current course
 3045: #                   if 'existingfile': write file to tmp/overwrites directory 
 3046: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3047: #                   $context is passed as argument to &finishuserfileupload
 3048: #        $subdir - directory in userfile to store the file into
 3049: #        $parser - instruction to parse file for objects ($parser = parse)    
 3050: #        $allfiles - reference to hash for embedded objects
 3051: #        $codebase - reference to hash for codebase of java objects
 3052: #        $desuname - username for permanent storage of uploaded file
 3053: #        $dsetudom - domain for permanaent storage of uploaded file
 3054: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3055: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3056: #        $resizewidth - width (pixels) to which to resize uploaded image
 3057: #        $resizeheight - height (pixels) to which to resize uploaded image
 3058: #        $mimetype - reference to scalar to accommodate mime type determined
 3059: #                    from File::MMagic.
 3060: # 
 3061: # output: url of file in userspace, or error: <message> 
 3062: #             or /adm/notfound.html if failure to upload occurse
 3063: 
 3064: sub userfileupload {
 3065:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3066:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3067:     if (!defined($subdir)) { $subdir='unknown'; }
 3068:     my $fname=$env{'form.'.$formname.'.filename'};
 3069:     $fname=&clean_filename($fname);
 3070:     # See if there is anything left
 3071:     unless ($fname) { return 'error: no uploaded file'; }
 3072:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3073:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3074:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3075:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3076:         my $now = time;
 3077:         my $filepath;
 3078:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3079:              $filepath = 'tmp/helprequests/'.$now;
 3080:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3081:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3082:                          '_'.$env{'user.domain'}.'/pending';
 3083:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3084:             my ($docuname,$docudom);
 3085:             if ($destudom) {
 3086:                 $docudom = $destudom;
 3087:             } else {
 3088:                 $docudom = $env{'user.domain'};
 3089:             }
 3090:             if ($destuname) {
 3091:                 $docuname = $destuname;
 3092:             } else {
 3093:                 $docuname = $env{'user.name'};
 3094:             }
 3095:             if (exists($env{'form.group'})) {
 3096:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3097:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3098:             }
 3099:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3100:             if ($context eq 'canceloverwrite') {
 3101:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3102:                 if (-e  $tempfile) {
 3103:                     my @info = stat($tempfile);
 3104:                     if ($info[9] eq $env{'form.timestamp'}) {
 3105:                         unlink($tempfile);
 3106:                     }
 3107:                 }
 3108:                 return;
 3109:             }
 3110:         }
 3111:         # Create the directory if not present
 3112:         my @parts=split(/\//,$filepath);
 3113:         my $fullpath = $perlvar{'lonDaemons'};
 3114:         for (my $i=0;$i<@parts;$i++) {
 3115:             $fullpath .= '/'.$parts[$i];
 3116:             if ((-e $fullpath)!=1) {
 3117:                 mkdir($fullpath,0777);
 3118:             }
 3119:         }
 3120:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3121:         print $fh $env{'form.'.$formname};
 3122:         close($fh);
 3123:         if ($context eq 'existingfile') {
 3124:             my @info = stat($fullpath.'/'.$fname);
 3125:             return ($fullpath.'/'.$fname,$info[9]);
 3126:         } else {
 3127:             return $fullpath.'/'.$fname;
 3128:         }
 3129:     }
 3130:     if ($subdir eq 'scantron') {
 3131:         $fname = 'scantron_orig_'.$fname;
 3132:     } else {
 3133:         $fname="$subdir/$fname";
 3134:     }
 3135:     if ($context eq 'coursedoc') {
 3136: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3137: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3138:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3139:             return &finishuserfileupload($docuname,$docudom,
 3140: 					 $formname,$fname,$parser,$allfiles,
 3141: 					 $codebase,$thumbwidth,$thumbheight,
 3142:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3143:         } else {
 3144:             $fname=$env{'form.folder'}.'/'.$fname;
 3145:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3146: 				       $fname,$formname,$parser,
 3147: 				       $allfiles,$codebase,$mimetype);
 3148:         }
 3149:     } elsif (defined($destuname)) {
 3150:         my $docuname=$destuname;
 3151:         my $docudom=$destudom;
 3152: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3153: 				     $parser,$allfiles,$codebase,
 3154:                                      $thumbwidth,$thumbheight,
 3155:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3156:     } else {
 3157:         my $docuname=$env{'user.name'};
 3158:         my $docudom=$env{'user.domain'};
 3159:         if (exists($env{'form.group'})) {
 3160:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3161:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3162:         }
 3163: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3164: 				     $parser,$allfiles,$codebase,
 3165:                                      $thumbwidth,$thumbheight,
 3166:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3167:     }
 3168: }
 3169: 
 3170: sub finishuserfileupload {
 3171:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3172:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3173:     my $path=$docudom.'/'.$docuname.'/';
 3174:     my $filepath=$perlvar{'lonDocRoot'};
 3175:   
 3176:     my ($fnamepath,$file,$fetchthumb);
 3177:     $file=$fname;
 3178:     if ($fname=~m|/|) {
 3179:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3180: 	$path.=$fnamepath.'/';
 3181:     }
 3182:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3183:     my $count;
 3184:     for ($count=4;$count<=$#parts;$count++) {
 3185:         $filepath.="/$parts[$count]";
 3186:         if ((-e $filepath)!=1) {
 3187: 	    mkdir($filepath,0777);
 3188:         }
 3189:     }
 3190: 
 3191: # Save the file
 3192:     {
 3193: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3194: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3195: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3196: 	    return '/adm/notfound.html';
 3197: 	}
 3198:         if ($context eq 'overwrite') {
 3199:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3200:             my $target = $filepath.'/'.$file;
 3201:             if (-e $source) {
 3202:                 my @info = stat($source);
 3203:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3204:                     unless (&File::Copy::move($source,$target)) {
 3205:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3206:                         return "Moving from $source failed";
 3207:                     }
 3208:                 } else {
 3209:                     return "Temporary file: $source had unexpected date/time for last modification";
 3210:                 }
 3211:             } else {
 3212:                 return "Temporary file: $source missing";
 3213:             }
 3214:         } elsif (!print FH ($env{'form.'.$formname})) {
 3215: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3216: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3217: 	    return '/adm/notfound.html';
 3218: 	}
 3219: 	close(FH);
 3220:         if ($resizewidth && $resizeheight) {
 3221:             my $mm = new File::MMagic;
 3222:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3223:             if ($mime_type =~ m{^image/}) {
 3224: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3225:             }  
 3226: 	}
 3227:     }
 3228:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3229:         if (ref($mimetype)) {
 3230:             if ($$mimetype eq '') {
 3231:                 my $mm = new File::MMagic;
 3232:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3233:                 $$mimetype = $type;
 3234:             }
 3235:         }
 3236:     }
 3237:     if ($parser eq 'parse') {
 3238:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3239:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3240:                                                        $allfiles,$codebase);
 3241:             unless ($parse_result eq 'ok') {
 3242:                 &logthis('Failed to parse '.$filepath.$file.
 3243: 	   	         ' for embedded media: '.$parse_result); 
 3244:             }
 3245:         }
 3246:     }
 3247:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3248:         my $input = $filepath.'/'.$file;
 3249:         my $output = $filepath.'/'.'tn-'.$file;
 3250:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3251:         system("convert -sample $thumbsize $input $output");
 3252:         if (-e $filepath.'/'.'tn-'.$file) {
 3253:             $fetchthumb  = 1; 
 3254:         }
 3255:     }
 3256:  
 3257: # Notify homeserver to grep it
 3258: #
 3259:     my $docuhome=&homeserver($docuname,$docudom);	
 3260:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3261:     if ($fetchresult eq 'ok') {
 3262:         if ($fetchthumb) {
 3263:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3264:             if ($thumbresult ne 'ok') {
 3265:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3266:                          $docuhome.': '.$thumbresult);
 3267:             }
 3268:         }
 3269: #
 3270: # Return the URL to it
 3271:         return '/uploaded/'.$path.$file;
 3272:     } else {
 3273:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3274: 		 ': '.$fetchresult);
 3275:         return '/adm/notfound.html';
 3276:     }
 3277: }
 3278: 
 3279: sub extract_embedded_items {
 3280:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3281:     my @state = ();
 3282:     my (%lastids,%related,%shockwave,%flashvars);
 3283:     my %javafiles = (
 3284:                       codebase => '',
 3285:                       code => '',
 3286:                       archive => ''
 3287:                     );
 3288:     my %mediafiles = (
 3289:                       src => '',
 3290:                       movie => '',
 3291:                      );
 3292:     my $p;
 3293:     if ($content) {
 3294:         $p = HTML::LCParser->new($content);
 3295:     } else {
 3296:         $p = HTML::LCParser->new($fullpath);
 3297:     }
 3298:     while (my $t=$p->get_token()) {
 3299: 	if ($t->[0] eq 'S') {
 3300: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3301: 	    push(@state, $tagname);
 3302:             if (lc($tagname) eq 'allow') {
 3303:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3304:             }
 3305: 	    if (lc($tagname) eq 'img') {
 3306: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3307: 	    }
 3308: 	    if (lc($tagname) eq 'a') {
 3309: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3310: 	    }
 3311:             if (lc($tagname) eq 'script') {
 3312:                 my $src;
 3313:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3314:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3315:                 } else {
 3316:                     if ($attr->{'src'} ne '') {
 3317:                         $src = $attr->{'src'};
 3318:                         &add_filetype($allfiles,$src,'src');
 3319:                     }
 3320:                 }
 3321:                 my $text = $p->get_trimmed_text();
 3322:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3323:                     my @swfargs = split(/,/,$1);
 3324:                     foreach my $item (@swfargs) {
 3325:                         $item =~ s/["']//g;
 3326:                         $item =~ s/^\s+//;
 3327:                         $item =~ s/\s+$//;
 3328:                     }
 3329:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3330:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3331:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3332:                         } else {
 3333:                             $related{$swfargs[0]} = [$swfargs[2]];
 3334:                         }
 3335:                     }
 3336:                 }
 3337:             }
 3338:             if (lc($tagname) eq 'link') {
 3339:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3340:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3341:                 }
 3342:             }
 3343: 	    if (lc($tagname) eq 'object' ||
 3344: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3345: 		foreach my $item (keys(%javafiles)) {
 3346: 		    $javafiles{$item} = '';
 3347: 		}
 3348:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3349:                     $lastids{lc($tagname)} = $attr->{'id'};
 3350:                 }
 3351: 	    }
 3352: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3353: 		my $name = lc($attr->{'name'});
 3354: 		foreach my $item (keys(%javafiles)) {
 3355: 		    if ($name eq $item) {
 3356: 			$javafiles{$item} = $attr->{'value'};
 3357: 			last;
 3358: 		    }
 3359: 		}
 3360:                 my $pathfrom;
 3361: 		foreach my $item (keys(%mediafiles)) {
 3362: 		    if ($name eq $item) {
 3363:                         $pathfrom = $attr->{'value'};
 3364:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3365: 			&add_filetype($allfiles,$pathfrom,$name);
 3366: 			last;
 3367: 		    }
 3368: 		}
 3369:                 if ($name eq 'flashvars') {
 3370:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3371:                 }
 3372:                 if ($pathfrom ne '') {
 3373:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3374:                                          $pathfrom);
 3375:                 }
 3376: 	    }
 3377: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3378: 		foreach my $item (keys(%javafiles)) {
 3379: 		    if ($attr->{$item}) {
 3380: 			$javafiles{$item} = $attr->{$item};
 3381: 			last;
 3382: 		    }
 3383: 		}
 3384: 		foreach my $item (keys(%mediafiles)) {
 3385: 		    if ($attr->{$item}) {
 3386: 			&add_filetype($allfiles,$attr->{$item},$item);
 3387: 			last;
 3388: 		    }
 3389: 		}
 3390:                 if (lc($tagname) eq 'embed') {
 3391:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3392:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3393:                                              $attr->{'src'});
 3394:                     }
 3395:                 }
 3396: 	    }
 3397:             if ($t->[4] =~ m{/>$}) {
 3398:                 pop(@state);  
 3399:             }
 3400: 	} elsif ($t->[0] eq 'E') {
 3401: 	    my ($tagname) = ($t->[1]);
 3402: 	    if ($javafiles{'codebase'} ne '') {
 3403: 		$javafiles{'codebase'} .= '/';
 3404: 	    }  
 3405: 	    if (lc($tagname) eq 'applet' ||
 3406: 		lc($tagname) eq 'object' ||
 3407: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3408: 		) {
 3409: 		foreach my $item (keys(%javafiles)) {
 3410: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3411: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3412: 			&add_filetype($allfiles,$file,$item);
 3413: 		    }
 3414: 		}
 3415: 	    } 
 3416: 	    pop @state;
 3417: 	}
 3418:     }
 3419:     foreach my $id (sort(keys(%flashvars))) {
 3420:         if ($shockwave{$id} ne '') {
 3421:             my @pairs = split(/\&/,$flashvars{$id});
 3422:             foreach my $pair (@pairs) {
 3423:                 my ($key,$value) = split(/\=/,$pair);
 3424:                 if ($key eq 'thumb') {
 3425:                     &add_filetype($allfiles,$value,$key);
 3426:                 } elsif ($key eq 'content') {
 3427:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3428:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3429:                     if ($ext ne '') {
 3430:                         &add_filetype($allfiles,$path.$value,$ext);
 3431:                     }
 3432:                 }
 3433:             }
 3434:         }
 3435:     }
 3436:     return 'ok';
 3437: }
 3438: 
 3439: sub add_filetype {
 3440:     my ($allfiles,$file,$type)=@_;
 3441:     if (exists($allfiles->{$file})) {
 3442: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3443: 	    push(@{$allfiles->{$file}}, &escape($type));
 3444: 	}
 3445:     } else {
 3446: 	@{$allfiles->{$file}} = (&escape($type));
 3447:     }
 3448: }
 3449: 
 3450: sub embedded_dependency {
 3451:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3452:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3453:         if (($identifier ne '') &&
 3454:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3455:             ($pathfrom ne '')) {
 3456:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3457:             foreach my $dep (@{$related->{$identifier}}) {
 3458:                 &add_filetype($allfiles,$path.$dep,'object');
 3459:             }
 3460:         }
 3461:     }
 3462:     return;
 3463: }
 3464: 
 3465: sub removeuploadedurl {
 3466:     my ($url)=@_;	
 3467:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3468:     return &removeuserfile($uname,$udom,$fname);
 3469: }
 3470: 
 3471: sub removeuserfile {
 3472:     my ($docuname,$docudom,$fname)=@_;
 3473:     my $home=&homeserver($docuname,$docudom);    
 3474:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3475:     if ($result eq 'ok') {	
 3476:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3477:             my $metafile = $fname.'.meta';
 3478:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3479: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3480:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3481:             my $sqlresult = 
 3482:                 &update_portfolio_table($docuname,$docudom,$file,
 3483:                                         'portfolio_metadata',$group,
 3484:                                         'delete');
 3485:         }
 3486:     }
 3487:     return $result;
 3488: }
 3489: 
 3490: sub mkdiruserfile {
 3491:     my ($docuname,$docudom,$dir)=@_;
 3492:     my $home=&homeserver($docuname,$docudom);
 3493:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3494: }
 3495: 
 3496: sub renameuserfile {
 3497:     my ($docuname,$docudom,$old,$new)=@_;
 3498:     my $home=&homeserver($docuname,$docudom);
 3499:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3500:                         &escape("$old").':'.&escape("$new"),$home);
 3501:     if ($result eq 'ok') {
 3502:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3503:             my $oldmeta = $old.'.meta';
 3504:             my $newmeta = $new.'.meta';
 3505:             my $metaresult = 
 3506:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3507: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3509:             my $sqlresult = 
 3510:                 &update_portfolio_table($docuname,$docudom,$file,
 3511:                                         'portfolio_metadata',$group,
 3512:                                         'delete');
 3513:         }
 3514:     }
 3515:     return $result;
 3516: }
 3517: 
 3518: # ------------------------------------------------------------------------- Log
 3519: 
 3520: sub log {
 3521:     my ($dom,$nam,$hom,$what)=@_;
 3522:     return critical("log:$dom:$nam:$what",$hom);
 3523: }
 3524: 
 3525: # ------------------------------------------------------------------ Course Log
 3526: #
 3527: # This routine flushes several buffers of non-mission-critical nature
 3528: #
 3529: 
 3530: sub flushcourselogs {
 3531:     &logthis('Flushing log buffers');
 3532: #
 3533: # course logs
 3534: # This is a log of all transactions in a course, which can be used
 3535: # for data mining purposes
 3536: #
 3537: # It also collects the courseid database, which lists last transaction
 3538: # times and course titles for all courseids
 3539: #
 3540:     my %courseidbuffer=();
 3541:     foreach my $crsid (keys(%courselogs)) {
 3542:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3543: 		          &escape($courselogs{$crsid}),
 3544: 		          $coursehombuf{$crsid}) eq 'ok') {
 3545: 	    delete $courselogs{$crsid};
 3546:         } else {
 3547:             &logthis('Failed to flush log buffer for '.$crsid);
 3548:             if (length($courselogs{$crsid})>40000) {
 3549:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3550:                         " exceeded maximum size, deleting.</font>");
 3551:                delete $courselogs{$crsid};
 3552:             }
 3553:         }
 3554:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3555:             'description' => $coursedescrbuf{$crsid},
 3556:             'inst_code'    => $courseinstcodebuf{$crsid},
 3557:             'type'        => $coursetypebuf{$crsid},
 3558:             'owner'       => $courseownerbuf{$crsid},
 3559:         };
 3560:     }
 3561: #
 3562: # Write course id database (reverse lookup) to homeserver of courses 
 3563: # Is used in pickcourse
 3564: #
 3565:     foreach my $crs_home (keys(%courseidbuffer)) {
 3566:         my $response = &courseidput(&host_domain($crs_home),
 3567:                                     $courseidbuffer{$crs_home},
 3568:                                     $crs_home,'timeonly');
 3569:     }
 3570: #
 3571: # File accesses
 3572: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3573: #
 3574:     foreach my $entry (keys(%accesshash)) {
 3575:         if ($entry =~ /___count$/) {
 3576:             my ($dom,$name);
 3577:             ($dom,$name,undef)=
 3578: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3579:             if (! defined($dom) || $dom eq '' || 
 3580:                 ! defined($name) || $name eq '') {
 3581:                 my $cid = $env{'request.course.id'};
 3582:                 $dom  = $env{'request.'.$cid.'.domain'};
 3583:                 $name = $env{'request.'.$cid.'.num'};
 3584:             }
 3585:             my $value = $accesshash{$entry};
 3586:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3587:             my %temphash=($url => $value);
 3588:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3589:             if ($result eq 'ok') {
 3590:                 delete $accesshash{$entry};
 3591:             }
 3592:         } else {
 3593:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3594:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3595:             my %temphash=($entry => $accesshash{$entry});
 3596:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3597:                 delete $accesshash{$entry};
 3598:             }
 3599:         }
 3600:     }
 3601: #
 3602: # Roles
 3603: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3604: #
 3605:     foreach my $entry (keys(%userrolehash)) {
 3606:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3607: 	    split(/\:/,$entry);
 3608:         if (&Apache::lonnet::put('nohist_userroles',
 3609:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3610:                 $rudom,$runame) eq 'ok') {
 3611: 	    delete $userrolehash{$entry};
 3612:         }
 3613:     }
 3614: #
 3615: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3616: #
 3617:     my %domrolebuffer = ();
 3618:     foreach my $entry (keys(%domainrolehash)) {
 3619:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3620:         if ($domrolebuffer{$rudom}) {
 3621:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3622:                       '='.&escape($domainrolehash{$entry});
 3623:         } else {
 3624:             $domrolebuffer{$rudom}.=&escape($entry).
 3625:                       '='.&escape($domainrolehash{$entry});
 3626:         }
 3627:         delete $domainrolehash{$entry};
 3628:     }
 3629:     foreach my $dom (keys(%domrolebuffer)) {
 3630: 	my %servers = &get_servers($dom,'library');
 3631: 	foreach my $tryserver (keys(%servers)) {
 3632: 	    unless (&reply('domroleput:'.$dom.':'.
 3633: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3634: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3635: 	    }
 3636:         }
 3637:     }
 3638:     $dumpcount++;
 3639: }
 3640: 
 3641: sub courselog {
 3642:     my $what=shift;
 3643:     $what=time.':'.$what;
 3644:     unless ($env{'request.course.id'}) { return ''; }
 3645:     $coursedombuf{$env{'request.course.id'}}=
 3646:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3647:     $coursenumbuf{$env{'request.course.id'}}=
 3648:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3649:     $coursehombuf{$env{'request.course.id'}}=
 3650:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3651:     $coursedescrbuf{$env{'request.course.id'}}=
 3652:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3653:     $courseinstcodebuf{$env{'request.course.id'}}=
 3654:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3655:     $courseownerbuf{$env{'request.course.id'}}=
 3656:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3657:     $coursetypebuf{$env{'request.course.id'}}=
 3658:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3659:     if (defined $courselogs{$env{'request.course.id'}}) {
 3660: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3661:     } else {
 3662: 	$courselogs{$env{'request.course.id'}}.=$what;
 3663:     }
 3664:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3665: 	&flushcourselogs();
 3666:     }
 3667: }
 3668: 
 3669: sub courseacclog {
 3670:     my $fnsymb=shift;
 3671:     unless ($env{'request.course.id'}) { return ''; }
 3672:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3673:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3674:         $what.=':POST';
 3675:         # FIXME: Probably ought to escape things....
 3676: 	foreach my $key (keys(%env)) {
 3677:             if ($key=~/^form\.(.*)/) {
 3678:                 my $formitem = $1;
 3679:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3680:                     $what.=':'.$formitem.'='.$env{$key};
 3681:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3682:                     $what.=':'.$formitem.'='.$env{$key};
 3683:                 }
 3684:             }
 3685:         }
 3686:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3687:         # FIXME: We should not be depending on a form parameter that someone
 3688:         # editing lonsearchcat.pm might change in the future.
 3689:         if ($env{'form.phase'} eq 'course_search') {
 3690:             $what.= ':POST';
 3691:             # FIXME: Probably ought to escape things....
 3692:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3693:                                  'crsdiscuss') {
 3694:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3695:             }
 3696:         }
 3697:     }
 3698:     &courselog($what);
 3699: }
 3700: 
 3701: sub countacc {
 3702:     my $url=&declutter(shift);
 3703:     return if (! defined($url) || $url eq '');
 3704:     unless ($env{'request.course.id'}) { return ''; }
 3705: #
 3706: # Mark that this url was used in this course
 3707: #
 3708:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3709: #
 3710: # Increase the access count for this resource in this child process
 3711: #
 3712:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3713:     $accesshash{$key}++;
 3714: }
 3715: 
 3716: sub linklog {
 3717:     my ($from,$to)=@_;
 3718:     $from=&declutter($from);
 3719:     $to=&declutter($to);
 3720:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3721:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3722: }
 3723: 
 3724: sub statslog {
 3725:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3726:     if ($users<2) { return; }
 3727:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3728:             'course'       => $env{'request.course.id'},
 3729:             'sections'     => '"all"',
 3730:             'num_students' => $users,
 3731:             'part'         => $part,
 3732:             'symb'         => $symb,
 3733:             'mean_tries'   => $av_attempts,
 3734:             'deg_of_diff'  => $degdiff});
 3735:     foreach my $key (keys(%dynstore)) {
 3736:         $accesshash{$key}=$dynstore{$key};
 3737:     }
 3738: }
 3739:   
 3740: sub userrolelog {
 3741:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3742:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3743:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3744:        $userrolehash
 3745:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3746:                     =$tend.':'.$tstart;
 3747:     }
 3748:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3749:        $userrolehash
 3750:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3751:                     =$tend.':'.$tstart;
 3752:     }
 3753:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3754:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3755:        $domainrolehash
 3756:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3757:                     = $tend.':'.$tstart;
 3758:     }
 3759: }
 3760: 
 3761: sub courserolelog {
 3762:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3763:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3764:         my $cdom = $1;
 3765:         my $cnum = $2;
 3766:         my $sec = $3;
 3767:         my $namespace = 'rolelog';
 3768:         my %storehash = (
 3769:                            role    => $trole,
 3770:                            start   => $tstart,
 3771:                            end     => $tend,
 3772:                            selfenroll => $selfenroll,
 3773:                            context    => $context,
 3774:                         );
 3775:         if ($trole eq 'gr') {
 3776:             $namespace = 'groupslog';
 3777:             $storehash{'group'} = $sec;
 3778:         } else {
 3779:             $storehash{'section'} = $sec;
 3780:         }
 3781:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3782:                    $domain,$cnum,$cdom);
 3783:         if (($trole ne 'st') || ($sec ne '')) {
 3784:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3785:         }
 3786:     }
 3787:     return;
 3788: }
 3789: 
 3790: sub domainrolelog {
 3791:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3792:     if ($area =~ m{^/($match_domain)/$}) {
 3793:         my $cdom = $1;
 3794:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3795:         my $namespace = 'rolelog';
 3796:         my %storehash = (
 3797:                            role    => $trole,
 3798:                            start   => $tstart,
 3799:                            end     => $tend,
 3800:                            context => $context,
 3801:                         );
 3802:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3803:                    $domain,$domconfiguser,$cdom);
 3804:     }
 3805:     return;
 3806: 
 3807: }
 3808: 
 3809: sub coauthorrolelog {
 3810:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3811:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3812:         my $audom = $1;
 3813:         my $auname = $2;
 3814:         my $namespace = 'rolelog';
 3815:         my %storehash = (
 3816:                            role    => $trole,
 3817:                            start   => $tstart,
 3818:                            end     => $tend,
 3819:                            context => $context,
 3820:                         );
 3821:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3822:                    $domain,$auname,$audom);
 3823:     }
 3824:     return;
 3825: }
 3826: 
 3827: sub get_course_adv_roles {
 3828:     my ($cid,$codes) = @_;
 3829:     $cid=$env{'request.course.id'} unless (defined($cid));
 3830:     my %coursehash=&coursedescription($cid);
 3831:     my $crstype = &Apache::loncommon::course_type($cid);
 3832:     my %nothide=();
 3833:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3834:         if ($user !~ /:/) {
 3835: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3836:         } else {
 3837:             $nothide{$user}=1;
 3838:         }
 3839:     }
 3840:     my %returnhash=();
 3841:     my %dumphash=
 3842:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3843:     my $now=time;
 3844:     my %privileged;
 3845:     foreach my $entry (keys(%dumphash)) {
 3846: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3847:         if (($tstart) && ($tstart<0)) { next; }
 3848:         if (($tend) && ($tend<$now)) { next; }
 3849:         if (($tstart) && ($now<$tstart)) { next; }
 3850:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3851: 	if ($username eq '' || $domain eq '') { next; }
 3852:         unless (ref($privileged{$domain}) eq 'HASH') {
 3853:             my %dompersonnel =
 3854:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3855:             $privileged{$domain} = {};
 3856:             foreach my $server (keys(%dompersonnel)) {
 3857:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3858:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3859:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3860:                         $privileged{$udom}{$uname} = 1;
 3861:                     }
 3862:                 }
 3863:             }
 3864:         }
 3865:         if ((exists($privileged{$domain}{$username})) && 
 3866:             (!$nothide{$username.':'.$domain})) { next; }
 3867: 	if ($role eq 'cr') { next; }
 3868:         if ($codes) {
 3869:             if ($section) { $role .= ':'.$section; }
 3870:             if ($returnhash{$role}) {
 3871:                 $returnhash{$role}.=','.$username.':'.$domain;
 3872:             } else {
 3873:                 $returnhash{$role}=$username.':'.$domain;
 3874:             }
 3875:         } else {
 3876:             my $key=&plaintext($role,$crstype);
 3877:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3878:             if ($returnhash{$key}) {
 3879: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3880:             } else {
 3881:                 $returnhash{$key}=$username.':'.$domain;
 3882:             }
 3883:         }
 3884:     }
 3885:     return %returnhash;
 3886: }
 3887: 
 3888: sub get_my_roles {
 3889:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3890:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3891:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3892:     my (%dumphash,%nothide);
 3893:     if ($context eq 'userroles') {
 3894:         %dumphash = &dump('roles',$udom,$uname);
 3895:     } else {
 3896:         %dumphash=
 3897:             &dump('nohist_userroles',$udom,$uname);
 3898:         if ($hidepriv) {
 3899:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3900:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3901:                 if ($user !~ /:/) {
 3902:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3903:                 } else {
 3904:                     $nothide{$user} = 1;
 3905:                 }
 3906:             }
 3907:         }
 3908:     }
 3909:     my %returnhash=();
 3910:     my $now=time;
 3911:     my %privileged;
 3912:     foreach my $entry (keys(%dumphash)) {
 3913:         my ($role,$tend,$tstart);
 3914:         if ($context eq 'userroles') {
 3915:             next if ($entry =~ /^rolesdef/);
 3916: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3917:         } else {
 3918:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3919:         }
 3920:         if (($tstart) && ($tstart<0)) { next; }
 3921:         my $status = 'active';
 3922:         if (($tend) && ($tend<=$now)) {
 3923:             $status = 'previous';
 3924:         } 
 3925:         if (($tstart) && ($now<$tstart)) {
 3926:             $status = 'future';
 3927:         }
 3928:         if (ref($types) eq 'ARRAY') {
 3929:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3930:                 next;
 3931:             } 
 3932:         } else {
 3933:             if ($status ne 'active') {
 3934:                 next;
 3935:             }
 3936:         }
 3937:         my ($rolecode,$username,$domain,$section,$area);
 3938:         if ($context eq 'userroles') {
 3939:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3940:             (undef,$domain,$username,$section) = split(/\//,$area);
 3941:         } else {
 3942:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3943:         }
 3944:         if (ref($roledoms) eq 'ARRAY') {
 3945:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3946:                 next;
 3947:             }
 3948:         }
 3949:         if (ref($roles) eq 'ARRAY') {
 3950:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3951:                 if ($role =~ /^cr\//) {
 3952:                     if (!grep(/^cr$/,@{$roles})) {
 3953:                         next;
 3954:                     }
 3955:                 } elsif ($role =~ /^gr\//) {
 3956:                     if (!grep(/^gr$/,@{$roles})) {
 3957:                         next;
 3958:                     }
 3959:                 } else {
 3960:                     next;
 3961:                 }
 3962:             }
 3963:         }
 3964:         if ($hidepriv) {
 3965:             if ($context eq 'userroles') {
 3966:                 if ((&privileged($username,$domain)) &&
 3967:                     (!$nothide{$username.':'.$domain})) {
 3968:                     next;
 3969:                 }
 3970:             } else {
 3971:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3972:                     my %dompersonnel =
 3973:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3974:                     $privileged{$domain} = {};
 3975:                     if (keys(%dompersonnel)) {
 3976:                         foreach my $server (keys(%dompersonnel)) {
 3977:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3978:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3979:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3980:                                     $privileged{$udom}{$uname} = $trole;
 3981:                                 }
 3982:                             }
 3983:                         }
 3984:                     }
 3985:                 }
 3986:                 if (exists($privileged{$domain}{$username})) {
 3987:                     if (!$nothide{$username.':'.$domain}) {
 3988:                         next;
 3989:                     }
 3990:                 }
 3991:             }
 3992:         }
 3993:         if ($withsec) {
 3994:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3995:                 $tstart.':'.$tend;
 3996:         } else {
 3997:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3998:         }
 3999:     }
 4000:     return %returnhash;
 4001: }
 4002: 
 4003: # ----------------------------------------------------- Frontpage Announcements
 4004: #
 4005: #
 4006: 
 4007: sub postannounce {
 4008:     my ($server,$text)=@_;
 4009:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4010:     unless ($text=~/\w/) { $text=''; }
 4011:     return &reply('setannounce:'.&escape($text),$server);
 4012: }
 4013: 
 4014: sub getannounce {
 4015: 
 4016:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4017: 	my $announcement='';
 4018: 	while (my $line = <$fh>) { $announcement .= $line; }
 4019: 	close($fh);
 4020: 	if ($announcement=~/\w/) { 
 4021: 	    return 
 4022:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4023:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4024: 	} else {
 4025: 	    return '';
 4026: 	}
 4027:     } else {
 4028: 	return '';
 4029:     }
 4030: }
 4031: 
 4032: # ---------------------------------------------------------- Course ID routines
 4033: # Deal with domain's nohist_courseid.db files
 4034: #
 4035: 
 4036: sub courseidput {
 4037:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4038:     return unless (ref($storehash) eq 'HASH');
 4039:     my $outcome;
 4040:     if ($caller eq 'timeonly') {
 4041:         my $cids = '';
 4042:         foreach my $item (keys(%$storehash)) {
 4043:             $cids.=&escape($item).'&';
 4044:         }
 4045:         $cids=~s/\&$//;
 4046:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4047:                           $coursehome);       
 4048:     } else {
 4049:         my $items = '';
 4050:         foreach my $item (keys(%$storehash)) {
 4051:             $items.= &escape($item).'='.
 4052:                      &freeze_escape($$storehash{$item}).'&';
 4053:         }
 4054:         $items=~s/\&$//;
 4055:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4056:                           $coursehome);
 4057:     }
 4058:     if ($outcome eq 'unknown_cmd') {
 4059:         my $what;
 4060:         foreach my $cid (keys(%$storehash)) {
 4061:             $what .= &escape($cid).'=';
 4062:             foreach my $item ('description','inst_code','owner','type') {
 4063:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4064:             }
 4065:             $what =~ s/\:$/&/;
 4066:         }
 4067:         $what =~ s/\&$//;  
 4068:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4069:     } else {
 4070:         return $outcome;
 4071:     }
 4072: }
 4073: 
 4074: sub courseiddump {
 4075:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4076:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4077:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4078:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4079:     my $as_hash = 1;
 4080:     my %returnhash;
 4081:     if (!$domfilter) { $domfilter=''; }
 4082:     my %libserv = &all_library();
 4083:     foreach my $tryserver (keys(%libserv)) {
 4084:         if ( (  $hostidflag == 1 
 4085: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4086: 	     || (!defined($hostidflag)) ) {
 4087: 
 4088: 	    if (($domfilter eq '') ||
 4089: 		(&host_domain($tryserver) eq $domfilter)) {
 4090:                 my $rep;
 4091:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4092:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4093:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4094:                                 &escape($descfilter), &escape($instcodefilter), 
 4095:                                 &escape($ownerfilter), &escape($coursefilter),
 4096:                                 &escape($typefilter), &escape($regexp_ok), 
 4097:                                 $as_hash, &escape($selfenrollonly), 
 4098:                                 &escape($catfilter), $showhidden, $caller, 
 4099:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4100:                                 &escape($createdbefore), &escape($createdafter), 
 4101:                                 &escape($creationcontext), $domcloner)));
 4102:                 } else {
 4103:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4104:                              $sincefilter.':'.&escape($descfilter).':'.
 4105:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4106:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4107:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4108:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4109:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4110:                              &escape($cc_clone).':'.$cloneonly.':'.
 4111:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4112:                              &escape($creationcontext).':'.$domcloner,
 4113:                              $tryserver);
 4114:                 }
 4115:                      
 4116:                 my @pairs=split(/\&/,$rep);
 4117:                 foreach my $item (@pairs) {
 4118:                     my ($key,$value)=split(/\=/,$item,2);
 4119:                     $key = &unescape($key);
 4120:                     next if ($key =~ /^error: 2 /);
 4121:                     my $result = &thaw_unescape($value);
 4122:                     if (ref($result) eq 'HASH') {
 4123:                         $returnhash{$key}=$result;
 4124:                     } else {
 4125:                         my @responses = split(/:/,$value);
 4126:                         my @items = ('description','inst_code','owner','type');
 4127:                         for (my $i=0; $i<@responses; $i++) {
 4128:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4129:                         }
 4130:                     }
 4131:                 }
 4132:             }
 4133:         }
 4134:     }
 4135:     return %returnhash;
 4136: }
 4137: 
 4138: sub courselastaccess {
 4139:     my ($cdom,$cnum,$hostidref) = @_;
 4140:     my %returnhash;
 4141:     if ($cdom && $cnum) {
 4142:         my $chome = &homeserver($cnum,$cdom);
 4143:         if ($chome ne 'no_host') {
 4144:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4145:             &extract_lastaccess(\%returnhash,$rep);
 4146:         }
 4147:     } else {
 4148:         if (!$cdom) { $cdom=''; }
 4149:         my %libserv = &all_library();
 4150:         foreach my $tryserver (keys(%libserv)) {
 4151:             if (ref($hostidref) eq 'ARRAY') {
 4152:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4153:             } 
 4154:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4155:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4156:                 &extract_lastaccess(\%returnhash,$rep);
 4157:             }
 4158:         }
 4159:     }
 4160:     return %returnhash;
 4161: }
 4162: 
 4163: sub extract_lastaccess {
 4164:     my ($returnhash,$rep) = @_;
 4165:     if (ref($returnhash) eq 'HASH') {
 4166:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4167:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4168:                  $rep eq '') {
 4169:             my @pairs=split(/\&/,$rep);
 4170:             foreach my $item (@pairs) {
 4171:                 my ($key,$value)=split(/\=/,$item,2);
 4172:                 $key = &unescape($key);
 4173:                 next if ($key =~ /^error: 2 /);
 4174:                 $returnhash->{$key} = &thaw_unescape($value);
 4175:             }
 4176:         }
 4177:     }
 4178:     return;
 4179: }
 4180: 
 4181: # ---------------------------------------------------------- DC e-mail
 4182: 
 4183: sub dcmailput {
 4184:     my ($domain,$msgid,$message,$server)=@_;
 4185:     my $status = &Apache::lonnet::critical(
 4186:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4187:        &escape($message),$server);
 4188:     return $status;
 4189: }
 4190: 
 4191: sub dcmaildump {
 4192:     my ($dom,$startdate,$enddate,$senders) = @_;
 4193:     my %returnhash=();
 4194: 
 4195:     if (defined(&domain($dom,'primary'))) {
 4196:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4197:                                                          &escape($enddate).':';
 4198: 	my @esc_senders=map { &escape($_)} @$senders;
 4199: 	$cmd.=&escape(join('&',@esc_senders));
 4200: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4201:             my ($key,$value) = split(/\=/,$line,2);
 4202:             if (($key) && ($value)) {
 4203:                 $returnhash{&unescape($key)} = &unescape($value);
 4204:             }
 4205:         }
 4206:     }
 4207:     return %returnhash;
 4208: }
 4209: # ---------------------------------------------------------- Domain roles
 4210: 
 4211: sub get_domain_roles {
 4212:     my ($dom,$roles,$startdate,$enddate)=@_;
 4213:     if ((!defined($startdate)) || ($startdate eq '')) {
 4214:         $startdate = '.';
 4215:     }
 4216:     if ((!defined($enddate)) || ($enddate eq '')) {
 4217:         $enddate = '.';
 4218:     }
 4219:     my $rolelist;
 4220:     if (ref($roles) eq 'ARRAY') {
 4221:         $rolelist = join(':',@{$roles});
 4222:     }
 4223:     my %personnel = ();
 4224: 
 4225:     my %servers = &get_servers($dom,'library');
 4226:     foreach my $tryserver (keys(%servers)) {
 4227: 	%{$personnel{$tryserver}}=();
 4228: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4229: 					    &escape($startdate).':'.
 4230: 					    &escape($enddate).':'.
 4231: 					    &escape($rolelist), $tryserver))) {
 4232: 	    my ($key,$value) = split(/\=/,$line,2);
 4233: 	    if (($key) && ($value)) {
 4234: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4235: 	    }
 4236: 	}
 4237:     }
 4238:     return %personnel;
 4239: }
 4240: 
 4241: # ----------------------------------------------------------- Interval timing 
 4242: 
 4243: {
 4244: # Caches needed for speedup of navmaps
 4245: # We don't want to cache this for very long at all (5 seconds at most)
 4246: # 
 4247: # The user for whom we cache
 4248: my $cachedkey='';
 4249: # The cached times for this user
 4250: my %cachedtimes=();
 4251: # When this was last done
 4252: my $cachedtime=();
 4253: 
 4254: sub load_all_first_access {
 4255:     my ($uname,$udom)=@_;
 4256:     if (($cachedkey eq $uname.':'.$udom) &&
 4257:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4258:         return;
 4259:     }
 4260:     $cachedtime=time;
 4261:     $cachedkey=$uname.':'.$udom;
 4262:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4263: }
 4264: 
 4265: sub get_first_access {
 4266:     my ($type,$argsymb,$argmap)=@_;
 4267:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4268:     if ($argsymb) { $symb=$argsymb; }
 4269:     my ($map,$id,$res)=&decode_symb($symb);
 4270:     if ($argmap) { $map = $argmap; }
 4271:     if ($type eq 'course') {
 4272: 	$res='course';
 4273:     } elsif ($type eq 'map') {
 4274: 	$res=&symbread($map);
 4275:     } else {
 4276: 	$res=$symb;
 4277:     }
 4278:     &load_all_first_access($uname,$udom);
 4279:     return $cachedtimes{"$courseid\0$res"};
 4280: }
 4281: 
 4282: sub set_first_access {
 4283:     my ($type,$interval)=@_;
 4284:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4285:     my ($map,$id,$res)=&decode_symb($symb);
 4286:     if ($type eq 'course') {
 4287: 	$res='course';
 4288:     } elsif ($type eq 'map') {
 4289: 	$res=&symbread($map);
 4290:     } else {
 4291: 	$res=$symb;
 4292:     }
 4293:     $cachedkey='';
 4294:     my $firstaccess=&get_first_access($type,$symb,$map);
 4295:     if (!$firstaccess) {
 4296:         my $start = time;
 4297: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4298:                           $udom,$uname);
 4299:         if ($putres eq 'ok') {
 4300:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4301:                  $udom,$uname); 
 4302:             &appenv(
 4303:                      {
 4304:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4305:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4306:                      }
 4307:                   );
 4308:         }
 4309:         return $putres;
 4310:     }
 4311:     return 'already_set';
 4312: }
 4313: }
 4314: # --------------------------------------------- Set Expire Date for Spreadsheet
 4315: 
 4316: sub expirespread {
 4317:     my ($uname,$udom,$stype,$usymb)=@_;
 4318:     my $cid=$env{'request.course.id'}; 
 4319:     if ($cid) {
 4320:        my $now=time;
 4321:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4322:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4323:                             $env{'course.'.$cid.'.num'}.
 4324: 	        	    ':nohist_expirationdates:'.
 4325:                             &escape($key).'='.$now,
 4326:                             $env{'course.'.$cid.'.home'})
 4327:     }
 4328:     return 'ok';
 4329: }
 4330: 
 4331: # ----------------------------------------------------- Devalidate Spreadsheets
 4332: 
 4333: sub devalidate {
 4334:     my ($symb,$uname,$udom)=@_;
 4335:     my $cid=$env{'request.course.id'}; 
 4336:     if ($cid) {
 4337:         # delete the stored spreadsheets for
 4338:         # - the student level sheet of this user in course's homespace
 4339:         # - the assessment level sheet for this resource 
 4340:         #   for this user in user's homespace
 4341: 	# - current conditional state info
 4342: 	my $key=$uname.':'.$udom.':';
 4343:         my $status=
 4344: 	    &del('nohist_calculatedsheets',
 4345: 		 [$key.'studentcalc:'],
 4346: 		 $env{'course.'.$cid.'.domain'},
 4347: 		 $env{'course.'.$cid.'.num'})
 4348: 		.' '.
 4349: 	    &del('nohist_calculatedsheets_'.$cid,
 4350: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4351:         unless ($status eq 'ok ok') {
 4352:            &logthis('Could not devalidate spreadsheet '.
 4353:                     $uname.' at '.$udom.' for '.
 4354: 		    $symb.': '.$status);
 4355:         }
 4356: 	&delenv('user.state.'.$cid);
 4357:     }
 4358: }
 4359: 
 4360: sub get_scalar {
 4361:     my ($string,$end) = @_;
 4362:     my $value;
 4363:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4364: 	$value = $1;
 4365:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4366: 	$value = $1;
 4367:     }
 4368:     return &unescape($value);
 4369: }
 4370: 
 4371: sub array2str {
 4372:   my (@array) = @_;
 4373:   my $result=&arrayref2str(\@array);
 4374:   $result=~s/^__ARRAY_REF__//;
 4375:   $result=~s/__END_ARRAY_REF__$//;
 4376:   return $result;
 4377: }
 4378: 
 4379: sub arrayref2str {
 4380:   my ($arrayref) = @_;
 4381:   my $result='__ARRAY_REF__';
 4382:   foreach my $elem (@$arrayref) {
 4383:     if(ref($elem) eq 'ARRAY') {
 4384:       $result.=&arrayref2str($elem).'&';
 4385:     } elsif(ref($elem) eq 'HASH') {
 4386:       $result.=&hashref2str($elem).'&';
 4387:     } elsif(ref($elem)) {
 4388:       #print("Got a ref of ".(ref($elem))." skipping.");
 4389:     } else {
 4390:       $result.=&escape($elem).'&';
 4391:     }
 4392:   }
 4393:   $result=~s/\&$//;
 4394:   $result .= '__END_ARRAY_REF__';
 4395:   return $result;
 4396: }
 4397: 
 4398: sub hash2str {
 4399:   my (%hash) = @_;
 4400:   my $result=&hashref2str(\%hash);
 4401:   $result=~s/^__HASH_REF__//;
 4402:   $result=~s/__END_HASH_REF__$//;
 4403:   return $result;
 4404: }
 4405: 
 4406: sub hashref2str {
 4407:   my ($hashref)=@_;
 4408:   my $result='__HASH_REF__';
 4409:   foreach my $key (sort(keys(%$hashref))) {
 4410:     if (ref($key) eq 'ARRAY') {
 4411:       $result.=&arrayref2str($key).'=';
 4412:     } elsif (ref($key) eq 'HASH') {
 4413:       $result.=&hashref2str($key).'=';
 4414:     } elsif (ref($key)) {
 4415:       $result.='=';
 4416:       #print("Got a ref of ".(ref($key))." skipping.");
 4417:     } else {
 4418: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4419:     }
 4420: 
 4421:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4422:       $result.=&arrayref2str($hashref->{$key}).'&';
 4423:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4424:       $result.=&hashref2str($hashref->{$key}).'&';
 4425:     } elsif(ref($hashref->{$key})) {
 4426:        $result.='&';
 4427:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4428:     } else {
 4429:       $result.=&escape($hashref->{$key}).'&';
 4430:     }
 4431:   }
 4432:   $result=~s/\&$//;
 4433:   $result .= '__END_HASH_REF__';
 4434:   return $result;
 4435: }
 4436: 
 4437: sub str2hash {
 4438:     my ($string)=@_;
 4439:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4440:     return %$hash;
 4441: }
 4442: 
 4443: sub str2hashref {
 4444:   my ($string) = @_;
 4445: 
 4446:   my %hash;
 4447: 
 4448:   if($string !~ /^__HASH_REF__/) {
 4449:       if (! ($string eq '' || !defined($string))) {
 4450: 	  $hash{'error'}='Not hash reference';
 4451:       }
 4452:       return (\%hash, $string);
 4453:   }
 4454: 
 4455:   $string =~ s/^__HASH_REF__//;
 4456: 
 4457:   while($string !~ /^__END_HASH_REF__/) {
 4458:       #key
 4459:       my $key='';
 4460:       if($string =~ /^__HASH_REF__/) {
 4461:           ($key, $string)=&str2hashref($string);
 4462:           if(defined($key->{'error'})) {
 4463:               $hash{'error'}='Bad data';
 4464:               return (\%hash, $string);
 4465:           }
 4466:       } elsif($string =~ /^__ARRAY_REF__/) {
 4467:           ($key, $string)=&str2arrayref($string);
 4468:           if($key->[0] eq 'Array reference error') {
 4469:               $hash{'error'}='Bad data';
 4470:               return (\%hash, $string);
 4471:           }
 4472:       } else {
 4473:           $string =~ s/^(.*?)=//;
 4474: 	  $key=&unescape($1);
 4475:       }
 4476:       $string =~ s/^=//;
 4477: 
 4478:       #value
 4479:       my $value='';
 4480:       if($string =~ /^__HASH_REF__/) {
 4481:           ($value, $string)=&str2hashref($string);
 4482:           if(defined($value->{'error'})) {
 4483:               $hash{'error'}='Bad data';
 4484:               return (\%hash, $string);
 4485:           }
 4486:       } elsif($string =~ /^__ARRAY_REF__/) {
 4487:           ($value, $string)=&str2arrayref($string);
 4488:           if($value->[0] eq 'Array reference error') {
 4489:               $hash{'error'}='Bad data';
 4490:               return (\%hash, $string);
 4491:           }
 4492:       } else {
 4493: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4494:       }
 4495:       $string =~ s/^&//;
 4496: 
 4497:       $hash{$key}=$value;
 4498:   }
 4499: 
 4500:   $string =~ s/^__END_HASH_REF__//;
 4501: 
 4502:   return (\%hash, $string);
 4503: }
 4504: 
 4505: sub str2array {
 4506:     my ($string)=@_;
 4507:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4508:     return @$array;
 4509: }
 4510: 
 4511: sub str2arrayref {
 4512:   my ($string) = @_;
 4513:   my @array;
 4514: 
 4515:   if($string !~ /^__ARRAY_REF__/) {
 4516:       if (! ($string eq '' || !defined($string))) {
 4517: 	  $array[0]='Array reference error';
 4518:       }
 4519:       return (\@array, $string);
 4520:   }
 4521: 
 4522:   $string =~ s/^__ARRAY_REF__//;
 4523: 
 4524:   while($string !~ /^__END_ARRAY_REF__/) {
 4525:       my $value='';
 4526:       if($string =~ /^__HASH_REF__/) {
 4527:           ($value, $string)=&str2hashref($string);
 4528:           if(defined($value->{'error'})) {
 4529:               $array[0] ='Array reference error';
 4530:               return (\@array, $string);
 4531:           }
 4532:       } elsif($string =~ /^__ARRAY_REF__/) {
 4533:           ($value, $string)=&str2arrayref($string);
 4534:           if($value->[0] eq 'Array reference error') {
 4535:               $array[0] ='Array reference error';
 4536:               return (\@array, $string);
 4537:           }
 4538:       } else {
 4539: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4540:       }
 4541:       $string =~ s/^&//;
 4542: 
 4543:       push(@array, $value);
 4544:   }
 4545: 
 4546:   $string =~ s/^__END_ARRAY_REF__//;
 4547: 
 4548:   return (\@array, $string);
 4549: }
 4550: 
 4551: # -------------------------------------------------------------------Temp Store
 4552: 
 4553: sub tmpreset {
 4554:   my ($symb,$namespace,$domain,$stuname) = @_;
 4555:   if (!$symb) {
 4556:     $symb=&symbread();
 4557:     if (!$symb) { $symb= $env{'request.url'}; }
 4558:   }
 4559:   $symb=escape($symb);
 4560: 
 4561:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4562:   $namespace=~s/\//\_/g;
 4563:   $namespace=~s/\W//g;
 4564: 
 4565:   if (!$domain) { $domain=$env{'user.domain'}; }
 4566:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4567:   if ($domain eq 'public' && $stuname eq 'public') {
 4568:       $stuname=$ENV{'REMOTE_ADDR'};
 4569:   }
 4570:   my $path=LONCAPA::tempdir();
 4571:   my %hash;
 4572:   if (tie(%hash,'GDBM_File',
 4573: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4574: 	  &GDBM_WRCREAT(),0640)) {
 4575:     foreach my $key (keys(%hash)) {
 4576:       if ($key=~ /:$symb/) {
 4577: 	delete($hash{$key});
 4578:       }
 4579:     }
 4580:   }
 4581: }
 4582: 
 4583: sub tmpstore {
 4584:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4585: 
 4586:   if (!$symb) {
 4587:     $symb=&symbread();
 4588:     if (!$symb) { $symb= $env{'request.url'}; }
 4589:   }
 4590:   $symb=escape($symb);
 4591: 
 4592:   if (!$namespace) {
 4593:     # I don't think we would ever want to store this for a course.
 4594:     # it seems this will only be used if we don't have a course.
 4595:     #$namespace=$env{'request.course.id'};
 4596:     #if (!$namespace) {
 4597:       $namespace=$env{'request.state'};
 4598:     #}
 4599:   }
 4600:   $namespace=~s/\//\_/g;
 4601:   $namespace=~s/\W//g;
 4602:   if (!$domain) { $domain=$env{'user.domain'}; }
 4603:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4604:   if ($domain eq 'public' && $stuname eq 'public') {
 4605:       $stuname=$ENV{'REMOTE_ADDR'};
 4606:   }
 4607:   my $now=time;
 4608:   my %hash;
 4609:   my $path=LONCAPA::tempdir();
 4610:   if (tie(%hash,'GDBM_File',
 4611: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4612: 	  &GDBM_WRCREAT(),0640)) {
 4613:     $hash{"version:$symb"}++;
 4614:     my $version=$hash{"version:$symb"};
 4615:     my $allkeys=''; 
 4616:     foreach my $key (keys(%$storehash)) {
 4617:       $allkeys.=$key.':';
 4618:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4619:     }
 4620:     $hash{"$version:$symb:timestamp"}=$now;
 4621:     $allkeys.='timestamp';
 4622:     $hash{"$version:keys:$symb"}=$allkeys;
 4623:     if (untie(%hash)) {
 4624:       return 'ok';
 4625:     } else {
 4626:       return "error:$!";
 4627:     }
 4628:   } else {
 4629:     return "error:$!";
 4630:   }
 4631: }
 4632: 
 4633: # -----------------------------------------------------------------Temp Restore
 4634: 
 4635: sub tmprestore {
 4636:   my ($symb,$namespace,$domain,$stuname) = @_;
 4637: 
 4638:   if (!$symb) {
 4639:     $symb=&symbread();
 4640:     if (!$symb) { $symb= $env{'request.url'}; }
 4641:   }
 4642:   $symb=escape($symb);
 4643: 
 4644:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4645: 
 4646:   if (!$domain) { $domain=$env{'user.domain'}; }
 4647:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4648:   if ($domain eq 'public' && $stuname eq 'public') {
 4649:       $stuname=$ENV{'REMOTE_ADDR'};
 4650:   }
 4651:   my %returnhash;
 4652:   $namespace=~s/\//\_/g;
 4653:   $namespace=~s/\W//g;
 4654:   my %hash;
 4655:   my $path=LONCAPA::tempdir();
 4656:   if (tie(%hash,'GDBM_File',
 4657: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4658: 	  &GDBM_READER(),0640)) {
 4659:     my $version=$hash{"version:$symb"};
 4660:     $returnhash{'version'}=$version;
 4661:     my $scope;
 4662:     for ($scope=1;$scope<=$version;$scope++) {
 4663:       my $vkeys=$hash{"$scope:keys:$symb"};
 4664:       my @keys=split(/:/,$vkeys);
 4665:       my $key;
 4666:       $returnhash{"$scope:keys"}=$vkeys;
 4667:       foreach $key (@keys) {
 4668: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4669: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4670:       }
 4671:     }
 4672:     if (!(untie(%hash))) {
 4673:       return "error:$!";
 4674:     }
 4675:   } else {
 4676:     return "error:$!";
 4677:   }
 4678:   return %returnhash;
 4679: }
 4680: 
 4681: # ----------------------------------------------------------------------- Store
 4682: 
 4683: sub store {
 4684:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4685:     my $home='';
 4686: 
 4687:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4688: 
 4689:     $symb=&symbclean($symb);
 4690:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4691: 
 4692:     if (!$domain) { $domain=$env{'user.domain'}; }
 4693:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4694: 
 4695:     &devalidate($symb,$stuname,$domain);
 4696: 
 4697:     $symb=escape($symb);
 4698:     if (!$namespace) { 
 4699:        unless ($namespace=$env{'request.course.id'}) { 
 4700:           return ''; 
 4701:        } 
 4702:     }
 4703:     if (!$home) { $home=$env{'user.home'}; }
 4704: 
 4705:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4706:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4707: 
 4708:     my $namevalue='';
 4709:     foreach my $key (keys(%$storehash)) {
 4710:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4711:     }
 4712:     $namevalue=~s/\&$//;
 4713:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4714:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4715: }
 4716: 
 4717: # -------------------------------------------------------------- Critical Store
 4718: 
 4719: sub cstore {
 4720:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4721:     my $home='';
 4722: 
 4723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4724: 
 4725:     $symb=&symbclean($symb);
 4726:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4727: 
 4728:     if (!$domain) { $domain=$env{'user.domain'}; }
 4729:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4730: 
 4731:     &devalidate($symb,$stuname,$domain);
 4732: 
 4733:     $symb=escape($symb);
 4734:     if (!$namespace) { 
 4735:        unless ($namespace=$env{'request.course.id'}) { 
 4736:           return ''; 
 4737:        } 
 4738:     }
 4739:     if (!$home) { $home=$env{'user.home'}; }
 4740: 
 4741:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4742:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4743: 
 4744:     my $namevalue='';
 4745:     foreach my $key (keys(%$storehash)) {
 4746:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4747:     }
 4748:     $namevalue=~s/\&$//;
 4749:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4750:     return critical
 4751:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4752: }
 4753: 
 4754: # --------------------------------------------------------------------- Restore
 4755: 
 4756: sub restore {
 4757:     my ($symb,$namespace,$domain,$stuname) = @_;
 4758:     my $home='';
 4759: 
 4760:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4761: 
 4762:     if (!$symb) {
 4763:       unless ($symb=escape(&symbread())) { return ''; }
 4764:     } else {
 4765:       $symb=&escape(&symbclean($symb));
 4766:     }
 4767:     if (!$namespace) { 
 4768:        unless ($namespace=$env{'request.course.id'}) { 
 4769:           return ''; 
 4770:        } 
 4771:     }
 4772:     if (!$domain) { $domain=$env{'user.domain'}; }
 4773:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4774:     if (!$home) { $home=$env{'user.home'}; }
 4775:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4776: 
 4777:     my %returnhash=();
 4778:     foreach my $line (split(/\&/,$answer)) {
 4779: 	my ($name,$value)=split(/\=/,$line);
 4780:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4781:     }
 4782:     my $version;
 4783:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4784:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4785:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4786:        }
 4787:     }
 4788:     return %returnhash;
 4789: }
 4790: 
 4791: # ---------------------------------------------------------- Course Description
 4792: #
 4793: #  
 4794: 
 4795: sub coursedescription {
 4796:     my ($courseid,$args)=@_;
 4797:     $courseid=~s/^\///;
 4798:     $courseid=~s/\_/\//g;
 4799:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4800:     my $chome=&homeserver($cnum,$cdomain);
 4801:     my $normalid=$cdomain.'_'.$cnum;
 4802:     # need to always cache even if we get errors otherwise we keep 
 4803:     # trying and trying and trying to get the course description.
 4804:     my %envhash=();
 4805:     my %returnhash=();
 4806:     
 4807:     my $expiretime=600;
 4808:     if ($env{'request.course.id'} eq $normalid) {
 4809: 	$expiretime=120;
 4810:     }
 4811: 
 4812:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4813:     if (!$args->{'freshen_cache'}
 4814: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4815: 	foreach my $key (keys(%env)) {
 4816: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4817: 	    my ($setting) = $1;
 4818: 	    $returnhash{$setting} = $env{$key};
 4819: 	}
 4820: 	return %returnhash;
 4821:     }
 4822: 
 4823:     # get the data again
 4824: 
 4825:     if (!$args->{'one_time'}) {
 4826: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4827:     }
 4828: 
 4829:     if ($chome ne 'no_host') {
 4830:        %returnhash=&dump('environment',$cdomain,$cnum);
 4831:        if (!exists($returnhash{'con_lost'})) {
 4832: 	   my $username = $env{'user.name'}; # Defult username
 4833: 	   if(defined $args->{'user'}) {
 4834: 	       $username = $args->{'user'};
 4835: 	   }
 4836:            $returnhash{'home'}= $chome;
 4837: 	   $returnhash{'domain'} = $cdomain;
 4838: 	   $returnhash{'num'} = $cnum;
 4839:            if (!defined($returnhash{'type'})) {
 4840:                $returnhash{'type'} = 'Course';
 4841:            }
 4842:            while (my ($name,$value) = each %returnhash) {
 4843:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4844:            }
 4845:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4846:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4847: 	       $username.'_'.$cdomain.'_'.$cnum;
 4848:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4849:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4850:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4851:        }
 4852:     }
 4853:     if (!$args->{'one_time'}) {
 4854: 	&appenv(\%envhash);
 4855:     }
 4856:     return %returnhash;
 4857: }
 4858: 
 4859: sub update_released_required {
 4860:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4861:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4862:         $cid = $env{'request.course.id'};
 4863:         $cdom = $env{'course.'.$cid.'.domain'};
 4864:         $cnum = $env{'course.'.$cid.'.num'};
 4865:         $chome = $env{'course.'.$cid.'.home'};
 4866:     }
 4867:     if ($needsrelease) {
 4868:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4869:         my $needsupdate;
 4870:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4871:             $needsupdate = 1;
 4872:         } else {
 4873:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4874:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4875:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4876:                 $needsupdate = 1;
 4877:             }
 4878:         }
 4879:         if ($needsupdate) {
 4880:             my %needshash = (
 4881:                              'internal.releaserequired' => $needsrelease,
 4882:                             );
 4883:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4884:             if ($putresult eq 'ok') {
 4885:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4886:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4887:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4888:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4889:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4890:                 }
 4891:             }
 4892:         }
 4893:     }
 4894:     return;
 4895: }
 4896: 
 4897: # -------------------------------------------------See if a user is privileged
 4898: 
 4899: sub privileged {
 4900:     my ($username,$domain)=@_;
 4901: 
 4902:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4903:     my $now = time;
 4904: 
 4905:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4906:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4907:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4908:                 return 1 unless ($tend && $tend < $now) 
 4909:                     or ($tstart && $tstart > $now);
 4910:             }
 4911: 	}
 4912: 
 4913:     return 0;
 4914: }
 4915: 
 4916: # -------------------------------------------------------- Get user privileges
 4917: 
 4918: sub rolesinit {
 4919:     my ($domain, $username) = @_;
 4920:     my %userroles = ('user.login.time' => time);
 4921:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4922: 
 4923:     # firstaccess and timerinterval are related to timed maps/resources. 
 4924:     # also, blocking can be triggered by an activating timer
 4925:     # it's saved in the user's %env.
 4926:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4927:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4928:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4929:         %timerintchk, %timerintenv);
 4930: 
 4931:     foreach my $key (keys(%firstaccess)) {
 4932:         my ($cid, $rest) = split(/\0/, $key);
 4933:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4934:     }
 4935: 
 4936:     foreach my $key (keys(%timerinterval)) {
 4937:         my ($cid,$rest) = split(/\0/,$key);
 4938:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4939:     }
 4940: 
 4941:     my %allroles=();
 4942:     my %allgroups=();
 4943: 
 4944:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4945:         my $role = $rolesdump{$area};
 4946:         $area =~ s/\_\w\w$//;
 4947: 
 4948:         my ($trole, $tend, $tstart, $group_privs);
 4949: 
 4950:         if ($role =~ /^cr/) {
 4951:         # Custom role, defined by a user 
 4952:         # e.g., user.role.cr/msu/smith/mynewrole
 4953:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4954:                 $trole = $1;
 4955:                 ($tend, $tstart) = split('_', $2);
 4956:             } else {
 4957:                 $trole = $role;
 4958:             }
 4959:         } elsif ($role =~ m|^gr/|) {
 4960:         # Role of member in a group, defined within a course/community
 4961:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4962:             ($trole, $tend, $tstart) = split(/_/, $role);
 4963:             next if $tstart eq '-1';
 4964:             ($trole, $group_privs) = split(/\//, $trole);
 4965:             $group_privs = &unescape($group_privs);
 4966:         } else {
 4967:         # Just a normal role, defined in roles.tab
 4968:             ($trole, $tend, $tstart) = split(/_/,$role);
 4969:         }
 4970: 
 4971:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4972:                  $username);
 4973:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4974: 
 4975:         # role expired or not available yet?
 4976:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4977:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4978: 
 4979:         next if $area eq '' or $trole eq '';
 4980: 
 4981:         my $spec = "$trole.$area";
 4982:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4983: 
 4984:         if ($trole =~ /^cr\//) {
 4985:         # Custom role, defined by a user
 4986:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4987:         } elsif ($trole eq 'gr') {
 4988:         # Role of a member in a group, defined within a course/community
 4989:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4990:             next;
 4991:         } else {
 4992:         # Normal role, defined in roles.tab
 4993:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4994:         }
 4995: 
 4996:         my $cid = $tdomain.'_'.$trest;
 4997:         unless ($firstaccchk{$cid}) {
 4998:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4999:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5000:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5001:                         $coursetimerstarts{$cid}{$item}; 
 5002:                 }
 5003:             }
 5004:             $firstaccchk{$cid} = 1;
 5005:         }
 5006:         unless ($timerintchk{$cid}) {
 5007:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5008:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5009:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5010:                        $coursetimerintervals{$cid}{$item};
 5011:                 }
 5012:             }
 5013:             $timerintchk{$cid} = 1;
 5014:         }
 5015:     }
 5016: 
 5017:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5018:         \%allroles, \%allgroups);
 5019:     $env{'user.adv'} = $userroles{'user.adv'};
 5020: 
 5021:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5022: }
 5023: 
 5024: sub set_arearole {
 5025:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 5026: # log the associated role with the area
 5027:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5028:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5029: }
 5030: 
 5031: sub custom_roleprivs {
 5032:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5033:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5034:     my $homsvr=homeserver($rauthor,$rdomain);
 5035:     if (&hostname($homsvr) ne '') {
 5036:         my ($rdummy,$roledef)=
 5037:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5038:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5039:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5040:             if (defined($syspriv)) {
 5041:                 if ($trest =~ /^$match_community$/) {
 5042:                     $syspriv =~ s/bre\&S//; 
 5043:                 }
 5044:                 $$allroles{'cm./'}.=':'.$syspriv;
 5045:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5046:             }
 5047:             if ($tdomain ne '') {
 5048:                 if (defined($dompriv)) {
 5049:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5050:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5051:                 }
 5052:                 if (($trest ne '') && (defined($coursepriv))) {
 5053:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5054:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5055:                 }
 5056:             }
 5057:         }
 5058:     }
 5059: }
 5060: 
 5061: sub group_roleprivs {
 5062:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5063:     my $access = 1;
 5064:     my $now = time;
 5065:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5066:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5067:     if ($access) {
 5068:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5069:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5070:     }
 5071: }
 5072: 
 5073: sub standard_roleprivs {
 5074:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5075:     if (defined($pr{$trole.':s'})) {
 5076:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5077:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5078:     }
 5079:     if ($tdomain ne '') {
 5080:         if (defined($pr{$trole.':d'})) {
 5081:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5082:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5083:         }
 5084:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5085:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5086:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5087:         }
 5088:     }
 5089: }
 5090: 
 5091: sub set_userprivs {
 5092:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5093:     my $author=0;
 5094:     my $adv=0;
 5095:     my %grouproles = ();
 5096:     if (keys(%{$allgroups}) > 0) {
 5097:         my @groupkeys; 
 5098:         foreach my $role (keys(%{$allroles})) {
 5099:             push(@groupkeys,$role);
 5100:         }
 5101:         if (ref($groups_roles) eq 'HASH') {
 5102:             foreach my $key (keys(%{$groups_roles})) {
 5103:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5104:                     push(@groupkeys,$key);
 5105:                 }
 5106:             }
 5107:         }
 5108:         if (@groupkeys > 0) {
 5109:             foreach my $role (@groupkeys) {
 5110:                 my ($trole,$area,$sec,$extendedarea);
 5111:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5112:                     $trole = $1;
 5113:                     $area = $2;
 5114:                     $sec = $3;
 5115:                     $extendedarea = $area.$sec;
 5116:                     if (exists($$allgroups{$area})) {
 5117:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5118:                             my $spec = $trole.'.'.$extendedarea;
 5119:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5120:                                                 $$allgroups{$area}{$group};
 5121:                         }
 5122:                     }
 5123:                 }
 5124:             }
 5125:         }
 5126:     }
 5127:     foreach my $group (keys(%grouproles)) {
 5128:         $$allroles{$group} = $grouproles{$group};
 5129:     }
 5130:     foreach my $role (keys(%{$allroles})) {
 5131:         my %thesepriv;
 5132:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5133:         foreach my $item (split(/:/,$$allroles{$role})) {
 5134:             if ($item ne '') {
 5135:                 my ($privilege,$restrictions)=split(/&/,$item);
 5136:                 if ($restrictions eq '') {
 5137:                     $thesepriv{$privilege}='F';
 5138:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5139:                     $thesepriv{$privilege}.=$restrictions;
 5140:                 }
 5141:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5142:             }
 5143:         }
 5144:         my $thesestr='';
 5145:         foreach my $priv (sort(keys(%thesepriv))) {
 5146: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5147: 	}
 5148:         $userroles->{'user.priv.'.$role} = $thesestr;
 5149:     }
 5150:     return ($author,$adv);
 5151: }
 5152: 
 5153: sub role_status {
 5154:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5155:     my @pwhere = ();
 5156:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5157:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5158:         unless (!defined($$role) || $$role eq '') {
 5159:             $$where=join('.',@pwhere);
 5160:             $$trolecode=$$role.'.'.$$where;
 5161:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5162:             $$tstatus='is';
 5163:             if ($$tstart && $$tstart>$update) {
 5164:                 $$tstatus='future';
 5165:                 if ($$tstart<$now) {
 5166:                     if ($$tstart && $$tstart>$refresh) {
 5167:                         if (($$where ne '') && ($$role ne '')) {
 5168:                             my (%allroles,%allgroups,$group_privs,
 5169:                                 %groups_roles,@rolecodes);
 5170:                             my %userroles = (
 5171:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5172:                             );
 5173:                             @rolecodes = ('cm'); 
 5174:                             my $spec=$$role.'.'.$$where;
 5175:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5176:                             if ($$role =~ /^cr\//) {
 5177:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5178:                                 push(@rolecodes,'cr');
 5179:                             } elsif ($$role eq 'gr') {
 5180:                                 push(@rolecodes,$$role);
 5181:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5182:                                                     $env{'user.name'});
 5183:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5184:                                 (undef,my $group_privs) = split(/\//,$trole);
 5185:                                 $group_privs = &unescape($group_privs);
 5186:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5187:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5188:                                 &get_groups_roles($tdomain,$trest,
 5189:                                                   \%course_roles,\@rolecodes,
 5190:                                                   \%groups_roles);
 5191:                             } else {
 5192:                                 push(@rolecodes,$$role);
 5193:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5194:                             }
 5195:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5196:                             &appenv(\%userroles,\@rolecodes);
 5197:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5198:                         }
 5199:                     }
 5200:                     $$tstatus = 'is';
 5201:                 }
 5202:             }
 5203:             if ($$tend) {
 5204:                 if ($$tend<$update) {
 5205:                     $$tstatus='expired';
 5206:                 } elsif ($$tend<$now) {
 5207:                     $$tstatus='will_not';
 5208:                 }
 5209:             }
 5210:         }
 5211:     }
 5212: }
 5213: 
 5214: sub get_groups_roles {
 5215:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5216:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5217:                   (ref($rolecodes) eq 'ARRAY') && 
 5218:                   (ref($groups_roles) eq 'HASH')); 
 5219:     if (keys(%{$cdom_courseroles}) > 0) {
 5220:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5221:         if ($cdom ne '' && $cnum ne '') {
 5222:             foreach my $key (keys(%{$cdom_courseroles})) {
 5223:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5224:                     my $crsrole = $1;
 5225:                     my $crssec = $2;
 5226:                     if ($crsrole =~ /^cr/) {
 5227:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5228:                             push(@{$rolecodes},'cr');
 5229:                         }
 5230:                     } else {
 5231:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5232:                             push(@{$rolecodes},$crsrole);
 5233:                         }
 5234:                     }
 5235:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5236:                     if ($crssec ne '') {
 5237:                         $rolekey .= "/$crssec";
 5238:                     }
 5239:                     $rolekey .= './';
 5240:                     $groups_roles->{$rolekey} = $rolecodes;
 5241:                 }
 5242:             }
 5243:         }
 5244:     }
 5245:     return;
 5246: }
 5247: 
 5248: sub delete_env_groupprivs {
 5249:     my ($where,$courseroles,$possroles) = @_;
 5250:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5251:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5252:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5253:         %{$courseroles->{$udom}} =
 5254:             &get_my_roles('','','userroles',['active'],
 5255:                           $possroles,[$udom],1);
 5256:     }
 5257:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5258:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5259:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5260:             my $area = '/'.$cdom.'/'.$cnum;
 5261:             my $privkey = "user.priv.$crsrole.$area";
 5262:             if ($crssec ne '') {
 5263:                 $privkey .= '/'.$crssec;
 5264:             }
 5265:             $privkey .= ".$area/$group";
 5266:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5267:         }
 5268:     }
 5269:     return;
 5270: }
 5271: 
 5272: sub check_adhoc_privs {
 5273:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5274:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5275:     my $setprivs;
 5276:     if ($env{$cckey}) {
 5277:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5278:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5279:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5280:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5281:             $setprivs = 1;
 5282:         }
 5283:     } else {
 5284:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5285:         $setprivs = 1;
 5286:     }
 5287:     return $setprivs;
 5288: }
 5289: 
 5290: sub set_adhoc_privileges {
 5291: # role can be cc or ca
 5292:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5293:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5294:     my $spec = $role.'.'.$area;
 5295:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5296:                                   $env{'user.name'});
 5297:     my %ccrole = ();
 5298:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5299:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5300:     &appenv(\%userroles,[$role,'cm']);
 5301:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5302:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5303:         &appenv( {'request.role'        => $spec,
 5304:                   'request.role.domain' => $dcdom,
 5305:                   'request.course.sec'  => ''
 5306:                  }
 5307:                );
 5308:         my $tadv=0;
 5309:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5310:         &appenv({'request.role.adv'    => $tadv});
 5311:     }
 5312: }
 5313: 
 5314: # --------------------------------------------------------------- get interface
 5315: 
 5316: sub get {
 5317:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5318:    my $items='';
 5319:    foreach my $item (@$storearr) {
 5320:        $items.=&escape($item).'&';
 5321:    }
 5322:    $items=~s/\&$//;
 5323:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5324:    if (!$uname) { $uname=$env{'user.name'}; }
 5325:    my $uhome=&homeserver($uname,$udomain);
 5326: 
 5327:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5328:    my @pairs=split(/\&/,$rep);
 5329:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5330:      return @pairs;
 5331:    }
 5332:    my %returnhash=();
 5333:    my $i=0;
 5334:    foreach my $item (@$storearr) {
 5335:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5336:       $i++;
 5337:    }
 5338:    return %returnhash;
 5339: }
 5340: 
 5341: # --------------------------------------------------------------- del interface
 5342: 
 5343: sub del {
 5344:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5345:    my $items='';
 5346:    foreach my $item (@$storearr) {
 5347:        $items.=&escape($item).'&';
 5348:    }
 5349: 
 5350:    $items=~s/\&$//;
 5351:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5352:    if (!$uname) { $uname=$env{'user.name'}; }
 5353:    my $uhome=&homeserver($uname,$udomain);
 5354:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5355: }
 5356: 
 5357: # -------------------------------------------------------------- dump interface
 5358: 
 5359: sub unserialize {
 5360:     my ($rep, $escapedkeys) = @_;
 5361: 
 5362:     return {} if $rep =~ /^error/;
 5363: 
 5364:     my %returnhash=();
 5365: 	foreach my $item (split /\&/, $rep) {
 5366: 	    my ($key, $value) = split(/=/, $item, 2);
 5367: 	    $key = unescape($key) unless $escapedkeys;
 5368: 	    next if $key =~ /^error: 2 /;
 5369: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5370: 	}
 5371:     #return %returnhash;
 5372:     return \%returnhash;
 5373: }        
 5374: 
 5375: # see Lond::dump_with_regexp
 5376: # if $escapedkeys hash keys won't get unescaped.
 5377: sub dump {
 5378:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5379:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5380:     if (!$uname) { $uname=$env{'user.name'}; }
 5381:     my $uhome=&homeserver($uname,$udomain);
 5382: 
 5383:     my $reply;
 5384:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5385:         # user is hosted on this machine
 5386:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5387:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5388:         return %{unserialize($reply, $escapedkeys)};
 5389:     }
 5390:     if ($regexp) {
 5391: 	$regexp=&escape($regexp);
 5392:     } else {
 5393: 	$regexp='.';
 5394:     }
 5395:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5396:     my @pairs=split(/\&/,$rep);
 5397:     my %returnhash=();
 5398:     if (!($rep =~ /^error/ )) {
 5399: 	foreach my $item (@pairs) {
 5400: 	    my ($key,$value)=split(/=/,$item,2);
 5401:         $key = unescape($key) unless $escapedkeys;
 5402:         #$key = &unescape($key);
 5403: 	    next if ($key =~ /^error: 2 /);
 5404: 	    $returnhash{$key}=&thaw_unescape($value);
 5405: 	}
 5406:     }
 5407:     return %returnhash;
 5408: }
 5409: 
 5410: 
 5411: # --------------------------------------------------------- dumpstore interface
 5412: 
 5413: sub dumpstore {
 5414:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5415:    # same as dump but keys must be escaped. They may contain colon separated
 5416:    # lists of values that may themself contain colons (e.g. symbs).
 5417:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5418: }
 5419: 
 5420: # -------------------------------------------------------------- keys interface
 5421: 
 5422: sub getkeys {
 5423:    my ($namespace,$udomain,$uname)=@_;
 5424:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5425:    if (!$uname) { $uname=$env{'user.name'}; }
 5426:    my $uhome=&homeserver($uname,$udomain);
 5427:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5428:    my @keyarray=();
 5429:    foreach my $key (split(/\&/,$rep)) {
 5430:       next if ($key =~ /^error: 2 /);
 5431:       push(@keyarray,&unescape($key));
 5432:    }
 5433:    return @keyarray;
 5434: }
 5435: 
 5436: # --------------------------------------------------------------- currentdump
 5437: sub currentdump {
 5438:    my ($courseid,$sdom,$sname)=@_;
 5439:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5440:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5441:    $sname    = $env{'user.name'}         if (! defined($sname));
 5442:    my $uhome = &homeserver($sname,$sdom);
 5443:    my $rep;
 5444: 
 5445:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5446:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5447:                    $courseid)));
 5448:    } else {
 5449:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5450:    }
 5451: 
 5452:    return if ($rep =~ /^(error:|no_such_host)/);
 5453:    #
 5454:    my %returnhash=();
 5455:    #
 5456:    if ($rep eq "unknown_cmd") { 
 5457:        # an old lond will not know currentdump
 5458:        # Do a dump and make it look like a currentdump
 5459:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5460:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5461:        my %hash = @tmp;
 5462:        @tmp=();
 5463:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5464:    } else {
 5465:        my @pairs=split(/\&/,$rep);
 5466:        foreach my $pair (@pairs) {
 5467:            my ($key,$value)=split(/=/,$pair,2);
 5468:            my ($symb,$param) = split(/:/,$key);
 5469:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5470:                                                         &thaw_unescape($value);
 5471:        }
 5472:    }
 5473:    return %returnhash;
 5474: }
 5475: 
 5476: sub convert_dump_to_currentdump{
 5477:     my %hash = %{shift()};
 5478:     my %returnhash;
 5479:     # Code ripped from lond, essentially.  The only difference
 5480:     # here is the unescaping done by lonnet::dump().  Conceivably
 5481:     # we might run in to problems with parameter names =~ /^v\./
 5482:     while (my ($key,$value) = each(%hash)) {
 5483:         my ($v,$symb,$param) = split(/:/,$key);
 5484: 	$symb  = &unescape($symb);
 5485: 	$param = &unescape($param);
 5486:         next if ($v eq 'version' || $symb eq 'keys');
 5487:         next if (exists($returnhash{$symb}) &&
 5488:                  exists($returnhash{$symb}->{$param}) &&
 5489:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5490:         $returnhash{$symb}->{$param}=$value;
 5491:         $returnhash{$symb}->{'v.'.$param}=$v;
 5492:     }
 5493:     #
 5494:     # Remove all of the keys in the hashes which keep track of
 5495:     # the version of the parameter.
 5496:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5497:         # use a foreach because we are going to delete from the hash.
 5498:         foreach my $key (keys(%$param_hash)) {
 5499:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5500:         }
 5501:     }
 5502:     return \%returnhash;
 5503: }
 5504: 
 5505: # ------------------------------------------------------ critical inc interface
 5506: 
 5507: sub cinc {
 5508:     return &inc(@_,'critical');
 5509: }
 5510: 
 5511: # --------------------------------------------------------------- inc interface
 5512: 
 5513: sub inc {
 5514:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5515:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5516:     if (!$uname) { $uname=$env{'user.name'}; }
 5517:     my $uhome=&homeserver($uname,$udomain);
 5518:     my $items='';
 5519:     if (! ref($store)) {
 5520:         # got a single value, so use that instead
 5521:         $items = &escape($store).'=&';
 5522:     } elsif (ref($store) eq 'SCALAR') {
 5523:         $items = &escape($$store).'=&';        
 5524:     } elsif (ref($store) eq 'ARRAY') {
 5525:         $items = join('=&',map {&escape($_);} @{$store});
 5526:     } elsif (ref($store) eq 'HASH') {
 5527:         while (my($key,$value) = each(%{$store})) {
 5528:             $items.= &escape($key).'='.&escape($value).'&';
 5529:         }
 5530:     }
 5531:     $items=~s/\&$//;
 5532:     if ($critical) {
 5533: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5534:     } else {
 5535: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5536:     }
 5537: }
 5538: 
 5539: # --------------------------------------------------------------- put interface
 5540: 
 5541: sub put {
 5542:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5543:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5544:    if (!$uname) { $uname=$env{'user.name'}; }
 5545:    my $uhome=&homeserver($uname,$udomain);
 5546:    my $items='';
 5547:    foreach my $item (keys(%$storehash)) {
 5548:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5549:    }
 5550:    $items=~s/\&$//;
 5551:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5552: }
 5553: 
 5554: # ------------------------------------------------------------ newput interface
 5555: 
 5556: sub newput {
 5557:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5559:    if (!$uname) { $uname=$env{'user.name'}; }
 5560:    my $uhome=&homeserver($uname,$udomain);
 5561:    my $items='';
 5562:    foreach my $key (keys(%$storehash)) {
 5563:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5564:    }
 5565:    $items=~s/\&$//;
 5566:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5567: }
 5568: 
 5569: # ---------------------------------------------------------  putstore interface
 5570: 
 5571: sub putstore {
 5572:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5573:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5574:    if (!$uname) { $uname=$env{'user.name'}; }
 5575:    my $uhome=&homeserver($uname,$udomain);
 5576:    my $items='';
 5577:    foreach my $key (keys(%$storehash)) {
 5578:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5579:    }
 5580:    $items=~s/\&$//;
 5581:    my $esc_symb=&escape($symb);
 5582:    my $esc_v=&escape($version);
 5583:    my $reply =
 5584:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5585: 	      $uhome);
 5586:    if ($reply eq 'unknown_cmd') {
 5587:        # gfall back to way things use to be done
 5588:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5589: 			    $uname);
 5590:    }
 5591:    return $reply;
 5592: }
 5593: 
 5594: sub old_putstore {
 5595:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5596:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5597:     if (!$uname) { $uname=$env{'user.name'}; }
 5598:     my $uhome=&homeserver($uname,$udomain);
 5599:     my %newstorehash;
 5600:     foreach my $item (keys(%$storehash)) {
 5601: 	my $key = $version.':'.&escape($symb).':'.$item;
 5602: 	$newstorehash{$key} = $storehash->{$item};
 5603:     }
 5604:     my $items='';
 5605:     my %allitems = ();
 5606:     foreach my $item (keys(%newstorehash)) {
 5607: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5608: 	    my $key = $1.':keys:'.$2;
 5609: 	    $allitems{$key} .= $3.':';
 5610: 	}
 5611: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5612:     }
 5613:     foreach my $item (keys(%allitems)) {
 5614: 	$allitems{$item} =~ s/\:$//;
 5615: 	$items.= $item.'='.$allitems{$item}.'&';
 5616:     }
 5617:     $items=~s/\&$//;
 5618:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5619: }
 5620: 
 5621: # ------------------------------------------------------ critical put interface
 5622: 
 5623: sub cput {
 5624:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5625:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5626:    if (!$uname) { $uname=$env{'user.name'}; }
 5627:    my $uhome=&homeserver($uname,$udomain);
 5628:    my $items='';
 5629:    foreach my $item (keys(%$storehash)) {
 5630:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5631:    }
 5632:    $items=~s/\&$//;
 5633:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5634: }
 5635: 
 5636: # -------------------------------------------------------------- eget interface
 5637: 
 5638: sub eget {
 5639:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5640:    my $items='';
 5641:    foreach my $item (@$storearr) {
 5642:        $items.=&escape($item).'&';
 5643:    }
 5644:    $items=~s/\&$//;
 5645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5646:    if (!$uname) { $uname=$env{'user.name'}; }
 5647:    my $uhome=&homeserver($uname,$udomain);
 5648:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5649:    my @pairs=split(/\&/,$rep);
 5650:    my %returnhash=();
 5651:    my $i=0;
 5652:    foreach my $item (@$storearr) {
 5653:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5654:       $i++;
 5655:    }
 5656:    return %returnhash;
 5657: }
 5658: 
 5659: # ------------------------------------------------------------ tmpput interface
 5660: sub tmpput {
 5661:     my ($storehash,$server,$context)=@_;
 5662:     my $items='';
 5663:     foreach my $item (keys(%$storehash)) {
 5664: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5665:     }
 5666:     $items=~s/\&$//;
 5667:     if (defined($context)) {
 5668:         $items .= ':'.&escape($context);
 5669:     }
 5670:     return &reply("tmpput:$items",$server);
 5671: }
 5672: 
 5673: # ------------------------------------------------------------ tmpget interface
 5674: sub tmpget {
 5675:     my ($token,$server)=@_;
 5676:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5677:     my $rep=&reply("tmpget:$token",$server);
 5678:     my %returnhash;
 5679:     foreach my $item (split(/\&/,$rep)) {
 5680: 	my ($key,$value)=split(/=/,$item);
 5681:         next if ($key =~ /^error: 2 /);
 5682: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5683:     }
 5684:     return %returnhash;
 5685: }
 5686: 
 5687: # ------------------------------------------------------------ tmpdel interface
 5688: sub tmpdel {
 5689:     my ($token,$server)=@_;
 5690:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5691:     return &reply("tmpdel:$token",$server);
 5692: }
 5693: 
 5694: # ------------------------------------------------------------ get_timebased_id 
 5695: 
 5696: sub get_timebased_id {
 5697:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5698:         $maxtries) = @_;
 5699:     my ($newid,$error,$dellock);
 5700:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5701:         return ('','ok','invalid call to get suffix');
 5702:     }
 5703: 
 5704: # set defaults for any optional args for which values were not supplied
 5705:     if ($who eq '') {
 5706:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5707:     }
 5708:     if (!$locktries) {
 5709:         $locktries = 3;
 5710:     }
 5711:     if (!$maxtries) {
 5712:         $maxtries = 10;
 5713:     }
 5714:     
 5715:     if (($cdom eq '') || ($cnum eq '')) {
 5716:         if ($env{'request.course.id'}) {
 5717:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5718:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5719:         }
 5720:         if (($cdom eq '') || ($cnum eq '')) {
 5721:             return ('','ok','call to get suffix not in course context');
 5722:         }
 5723:     }
 5724: 
 5725: # construct locking item
 5726:     my $lockhash = {
 5727:                       $prefix."\0".'locked_'.$keyid => $who,
 5728:                    };
 5729:     my $tries = 0;
 5730: 
 5731: # attempt to get lock on nohist_$namespace file
 5732:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5733:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5734:         $tries ++;
 5735:         sleep 1;
 5736:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5737:     }
 5738: 
 5739: # attempt to get unique identifier, based on current timestamp
 5740:     if ($gotlock eq 'ok') {
 5741:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5742:         my $id = time;
 5743:         $newid = $id;
 5744:         my $idtries = 0;
 5745:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5746:             if ($idtype eq 'concat') {
 5747:                 $newid = $id.$idtries;
 5748:             } else {
 5749:                 $newid ++;
 5750:             }
 5751:             $idtries ++;
 5752:         }
 5753:         if (!exists($inuse{$prefix."\0".$newid})) {
 5754:             my %new_item =  (
 5755:                               $prefix."\0".$newid => $who,
 5756:                             );
 5757:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5758:                                                  $cdom,$cnum);
 5759:             if ($putresult ne 'ok') {
 5760:                 undef($newid);
 5761:                 $error = 'error saving new item: '.$putresult;
 5762:             }
 5763:         } else {
 5764:              $error = ('error: no unique suffix available for the new item ');
 5765:         }
 5766: #  remove lock
 5767:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5768:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5769:     } else {
 5770:         $error = "error: could not obtain lockfile\n";
 5771:         $dellock = 'ok';
 5772:     }
 5773:     return ($newid,$dellock,$error);
 5774: }
 5775: 
 5776: # -------------------------------------------------- portfolio access checking
 5777: 
 5778: sub portfolio_access {
 5779:     my ($requrl) = @_;
 5780:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5781:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5782:     if ($result) {
 5783:         my %setters;
 5784:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5785:             my ($startblock,$endblock) =
 5786:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5787:             if ($startblock && $endblock) {
 5788:                 return 'B';
 5789:             }
 5790:         } else {
 5791:             my ($startblock,$endblock) =
 5792:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5793:             if ($startblock && $endblock) {
 5794:                 return 'B';
 5795:             }
 5796:         }
 5797:     }
 5798:     if ($result eq 'ok') {
 5799:        return 'F';
 5800:     } elsif ($result =~ /^[^:]+:guest_/) {
 5801:        return 'A';
 5802:     }
 5803:     return '';
 5804: }
 5805: 
 5806: sub get_portfolio_access {
 5807:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5808: 
 5809:     if (!ref($access_hash)) {
 5810: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5811: 	my %access_controls = &get_access_controls($current_perms,$group,
 5812: 						   $file_name);
 5813: 	$access_hash = $access_controls{$file_name};
 5814:     }
 5815: 
 5816:     my ($public,$guest,@domains,@users,@courses,@groups);
 5817:     my $now = time;
 5818:     if (ref($access_hash) eq 'HASH') {
 5819:         foreach my $key (keys(%{$access_hash})) {
 5820:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5821:             if ($start > $now) {
 5822:                 next;
 5823:             }
 5824:             if ($end && $end<$now) {
 5825:                 next;
 5826:             }
 5827:             if ($scope eq 'public') {
 5828:                 $public = $key;
 5829:                 last;
 5830:             } elsif ($scope eq 'guest') {
 5831:                 $guest = $key;
 5832:             } elsif ($scope eq 'domains') {
 5833:                 push(@domains,$key);
 5834:             } elsif ($scope eq 'users') {
 5835:                 push(@users,$key);
 5836:             } elsif ($scope eq 'course') {
 5837:                 push(@courses,$key);
 5838:             } elsif ($scope eq 'group') {
 5839:                 push(@groups,$key);
 5840:             }
 5841:         }
 5842:         if ($public) {
 5843:             return 'ok';
 5844:         }
 5845:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5846:             if ($guest) {
 5847:                 return $guest;
 5848:             }
 5849:         } else {
 5850:             if (@domains > 0) {
 5851:                 foreach my $domkey (@domains) {
 5852:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5853:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5854:                             return 'ok';
 5855:                         }
 5856:                     }
 5857:                 }
 5858:             }
 5859:             if (@users > 0) {
 5860:                 foreach my $userkey (@users) {
 5861:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5862:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5863:                             if (ref($item) eq 'HASH') {
 5864:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5865:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5866:                                     return 'ok';
 5867:                                 }
 5868:                             }
 5869:                         }
 5870:                     } 
 5871:                 }
 5872:             }
 5873:             my %roleshash;
 5874:             my @courses_and_groups = @courses;
 5875:             push(@courses_and_groups,@groups); 
 5876:             if (@courses_and_groups > 0) {
 5877:                 my (%allgroups,%allroles); 
 5878:                 my ($start,$end,$role,$sec,$group);
 5879:                 foreach my $envkey (%env) {
 5880:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5881:                         my $cid = $2.'_'.$3; 
 5882:                         if ($1 eq 'gr') {
 5883:                             $group = $4;
 5884:                             $allgroups{$cid}{$group} = $env{$envkey};
 5885:                         } else {
 5886:                             if ($4 eq '') {
 5887:                                 $sec = 'none';
 5888:                             } else {
 5889:                                 $sec = $4;
 5890:                             }
 5891:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5892:                         }
 5893:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5894:                         my $cid = $2.'_'.$3;
 5895:                         if ($4 eq '') {
 5896:                             $sec = 'none';
 5897:                         } else {
 5898:                             $sec = $4;
 5899:                         }
 5900:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5901:                     }
 5902:                 }
 5903:                 if (keys(%allroles) == 0) {
 5904:                     return;
 5905:                 }
 5906:                 foreach my $key (@courses_and_groups) {
 5907:                     my %content = %{$$access_hash{$key}};
 5908:                     my $cnum = $content{'number'};
 5909:                     my $cdom = $content{'domain'};
 5910:                     my $cid = $cdom.'_'.$cnum;
 5911:                     if (!exists($allroles{$cid})) {
 5912:                         next;
 5913:                     }    
 5914:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5915:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5916:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5917:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5918:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5919:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5920:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5921:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5922:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5923:                                         if (grep/^all$/,@sections) {
 5924:                                             return 'ok';
 5925:                                         } else {
 5926:                                             if (grep/^$sec$/,@sections) {
 5927:                                                 return 'ok';
 5928:                                             }
 5929:                                         }
 5930:                                     }
 5931:                                 }
 5932:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5933:                                     if (grep/^none$/,@groups) {
 5934:                                         return 'ok';
 5935:                                     }
 5936:                                 } else {
 5937:                                     if (grep/^all$/,@groups) {
 5938:                                         return 'ok';
 5939:                                     } 
 5940:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5941:                                         if (grep/^$group$/,@groups) {
 5942:                                             return 'ok';
 5943:                                         }
 5944:                                     }
 5945:                                 } 
 5946:                             }
 5947:                         }
 5948:                     }
 5949:                 }
 5950:             }
 5951:             if ($guest) {
 5952:                 return $guest;
 5953:             }
 5954:         }
 5955:     }
 5956:     return;
 5957: }
 5958: 
 5959: sub course_group_datechecker {
 5960:     my ($dates,$now,$status) = @_;
 5961:     my ($start,$end) = split(/\./,$dates);
 5962:     if (!$start && !$end) {
 5963:         return 'ok';
 5964:     }
 5965:     if (grep/^active$/,@{$status}) {
 5966:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5967:             return 'ok';
 5968:         }
 5969:     }
 5970:     if (grep/^previous$/,@{$status}) {
 5971:         if ($end > $now ) {
 5972:             return 'ok';
 5973:         }
 5974:     }
 5975:     if (grep/^future$/,@{$status}) {
 5976:         if ($start > $now) {
 5977:             return 'ok';
 5978:         }
 5979:     }
 5980:     return; 
 5981: }
 5982: 
 5983: sub parse_portfolio_url {
 5984:     my ($url) = @_;
 5985: 
 5986:     my ($type,$udom,$unum,$group,$file_name);
 5987:     
 5988:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5989: 	$type = 1;
 5990:         $udom = $1;
 5991:         $unum = $2;
 5992:         $file_name = $3;
 5993:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5994: 	$type = 2;
 5995:         $udom = $1;
 5996:         $unum = $2;
 5997:         $group = $3;
 5998:         $file_name = $3.'/'.$4;
 5999:     }
 6000:     if (wantarray) {
 6001: 	return ($type,$udom,$unum,$file_name,$group);
 6002:     }
 6003:     return $type;
 6004: }
 6005: 
 6006: sub is_portfolio_url {
 6007:     my ($url) = @_;
 6008:     return scalar(&parse_portfolio_url($url));
 6009: }
 6010: 
 6011: sub is_portfolio_file {
 6012:     my ($file) = @_;
 6013:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6014:         return 1;
 6015:     }
 6016:     return;
 6017: }
 6018: 
 6019: sub usertools_access {
 6020:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6021:     my ($access,%tools);
 6022:     if ($context eq '') {
 6023:         $context = 'tools';
 6024:     }
 6025:     if ($context eq 'requestcourses') {
 6026:         %tools = (
 6027:                       official   => 1,
 6028:                       unofficial => 1,
 6029:                       community  => 1,
 6030:                  );
 6031:     } elsif ($context eq 'requestauthor') {
 6032:         %tools = (
 6033:                       requestauthor => 1,
 6034:                  );
 6035:     } else {
 6036:         %tools = (
 6037:                       aboutme   => 1,
 6038:                       blog      => 1,
 6039:                       webdav    => 1,
 6040:                       portfolio => 1,
 6041:                  );
 6042:     }
 6043:     return if (!defined($tools{$tool}));
 6044: 
 6045:     if ((!defined($udom)) || (!defined($uname))) {
 6046:         $udom = $env{'user.domain'};
 6047:         $uname = $env{'user.name'};
 6048:     }
 6049: 
 6050:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6051:         if ($action ne 'reload') {
 6052:             if ($context eq 'requestcourses') {
 6053:                 return $env{'environment.canrequest.'.$tool};
 6054:             } elsif ($context eq 'requestauthor') {
 6055:                 return $env{'environment.canrequest.author'};
 6056:             } else {
 6057:                 return $env{'environment.availabletools.'.$tool};
 6058:             }
 6059:         }
 6060:     }
 6061: 
 6062:     my ($toolstatus,$inststatus,$envkey);
 6063:     if ($context eq 'requestauthor') {
 6064:         $envkey = $context; 
 6065:     } else {
 6066:         $envkey = $context.'.'.$tool;
 6067:     }
 6068: 
 6069:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6070:          ($action ne 'reload')) {
 6071:         $toolstatus = $env{'environment.'.$envkey};
 6072:         $inststatus = $env{'environment.inststatus'};
 6073:     } else {
 6074:         if (ref($userenvref) eq 'HASH') {
 6075:             $toolstatus = $userenvref->{$envkey};
 6076:             $inststatus = $userenvref->{'inststatus'};
 6077:         } else {
 6078:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6079:             $toolstatus = $userenv{$envkey};
 6080:             $inststatus = $userenv{'inststatus'};
 6081:         }
 6082:     }
 6083: 
 6084:     if ($toolstatus ne '') {
 6085:         if ($toolstatus) {
 6086:             $access = 1;
 6087:         } else {
 6088:             $access = 0;
 6089:         }
 6090:         return $access;
 6091:     }
 6092: 
 6093:     my ($is_adv,%domdef);
 6094:     if (ref($is_advref) eq 'HASH') {
 6095:         $is_adv = $is_advref->{'is_adv'};
 6096:     } else {
 6097:         $is_adv = &is_advanced_user($udom,$uname);
 6098:     }
 6099:     if (ref($domdefref) eq 'HASH') {
 6100:         %domdef = %{$domdefref};
 6101:     } else {
 6102:         %domdef = &get_domain_defaults($udom);
 6103:     }
 6104:     if (ref($domdef{$tool}) eq 'HASH') {
 6105:         if ($is_adv) {
 6106:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6107:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6108:                     $access = 1;
 6109:                 } else {
 6110:                     $access = 0;
 6111:                 }
 6112:                 return $access;
 6113:             }
 6114:         }
 6115:         if ($inststatus ne '') {
 6116:             my ($hasaccess,$hasnoaccess);
 6117:             foreach my $affiliation (split(/:/,$inststatus)) {
 6118:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6119:                     if ($domdef{$tool}{$affiliation}) {
 6120:                         $hasaccess = 1;
 6121:                     } else {
 6122:                         $hasnoaccess = 1;
 6123:                     }
 6124:                 }
 6125:             }
 6126:             if ($hasaccess || $hasnoaccess) {
 6127:                 if ($hasaccess) {
 6128:                     $access = 1;
 6129:                 } elsif ($hasnoaccess) {
 6130:                     $access = 0; 
 6131:                 }
 6132:                 return $access;
 6133:             }
 6134:         } else {
 6135:             if ($domdef{$tool}{'default'} ne '') {
 6136:                 if ($domdef{$tool}{'default'}) {
 6137:                     $access = 1;
 6138:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6139:                     $access = 0;
 6140:                 }
 6141:                 return $access;
 6142:             }
 6143:         }
 6144:     } else {
 6145:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6146:             $access = 1;
 6147:         } else {
 6148:             $access = 0;
 6149:         }
 6150:         return $access;
 6151:     }
 6152: }
 6153: 
 6154: sub is_course_owner {
 6155:     my ($cdom,$cnum,$udom,$uname) = @_;
 6156:     if (($udom eq '') || ($uname eq '')) {
 6157:         $udom = $env{'user.domain'};
 6158:         $uname = $env{'user.name'};
 6159:     }
 6160:     unless (($udom eq '') || ($uname eq '')) {
 6161:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6162:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6163:                 return 1;
 6164:             } else {
 6165:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6166:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6167:                     return 1;
 6168:                 }
 6169:             }
 6170:         }
 6171:     }
 6172:     return;
 6173: }
 6174: 
 6175: sub is_advanced_user {
 6176:     my ($udom,$uname) = @_;
 6177:     if ($udom ne '' && $uname ne '') {
 6178:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6179:             if (wantarray) {
 6180:                 return ($env{'user.adv'},$env{'user.author'});
 6181:             } else {
 6182:                 return $env{'user.adv'};
 6183:             }
 6184:         }
 6185:     }
 6186:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6187:     my %allroles;
 6188:     my ($is_adv,$is_author);
 6189:     foreach my $role (keys(%roleshash)) {
 6190:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6191:         my $area = '/'.$tdomain.'/'.$trest;
 6192:         if ($sec ne '') {
 6193:             $area .= '/'.$sec;
 6194:         }
 6195:         if (($area ne '') && ($trole ne '')) {
 6196:             my $spec=$trole.'.'.$area;
 6197:             if ($trole =~ /^cr\//) {
 6198:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6199:             } elsif ($trole ne 'gr') {
 6200:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6201:             }
 6202:             if ($trole eq 'au') {
 6203:                 $is_author = 1;
 6204:             }
 6205:         }
 6206:     }
 6207:     foreach my $role (keys(%allroles)) {
 6208:         last if ($is_adv);
 6209:         foreach my $item (split(/:/,$allroles{$role})) {
 6210:             if ($item ne '') {
 6211:                 my ($privilege,$restrictions)=split(/&/,$item);
 6212:                 if ($privilege eq 'adv') {
 6213:                     $is_adv = 1;
 6214:                     last;
 6215:                 }
 6216:             }
 6217:         }
 6218:     }
 6219:     if (wantarray) {
 6220:         return ($is_adv,$is_author);
 6221:     }
 6222:     return $is_adv;
 6223: }
 6224: 
 6225: sub check_can_request {
 6226:     my ($dom,$can_request,$request_domains) = @_;
 6227:     my $canreq = 0;
 6228:     my ($types,$typename) = &Apache::loncommon::course_types();
 6229:     my @options = ('approval','validate','autolimit');
 6230:     my $optregex = join('|',@options);
 6231:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6232:         foreach my $type (@{$types}) {
 6233:             if (&usertools_access($env{'user.name'},
 6234:                                   $env{'user.domain'},
 6235:                                   $type,undef,'requestcourses')) {
 6236:                 $canreq ++;
 6237:                 if (ref($request_domains) eq 'HASH') {
 6238:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6239:                 }
 6240:                 if ($dom eq $env{'user.domain'}) {
 6241:                     $can_request->{$type} = 1;
 6242:                 }
 6243:             }
 6244:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6245:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6246:                 if (@curr > 0) {
 6247:                     foreach my $item (@curr) {
 6248:                         if (ref($request_domains) eq 'HASH') {
 6249:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6250:                             if ($otherdom ne '') {
 6251:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6252:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6253:                                         push(@{$request_domains->{$type}},$otherdom);
 6254:                                     }
 6255:                                 } else {
 6256:                                     push(@{$request_domains->{$type}},$otherdom);
 6257:                                 }
 6258:                             }
 6259:                         }
 6260:                     }
 6261:                     unless($dom eq $env{'user.domain'}) {
 6262:                         $canreq ++;
 6263:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6264:                             $can_request->{$type} = 1;
 6265:                         }
 6266:                     }
 6267:                 }
 6268:             }
 6269:         }
 6270:     }
 6271:     return $canreq;
 6272: }
 6273: 
 6274: # ---------------------------------------------- Custom access rule evaluation
 6275: 
 6276: sub customaccess {
 6277:     my ($priv,$uri)=@_;
 6278:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6279:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6280:     $udom = &LONCAPA::clean_domain($udom);
 6281:     $ucrs = &LONCAPA::clean_username($ucrs);
 6282:     my $access=0;
 6283:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6284: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6285: 	if ($type eq 'user') {
 6286: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6287: 		my ($tdom,$tuname)=split(m{/},$scope);
 6288: 		if ($tdom) {
 6289: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6290: 		}
 6291: 		if ($tuname) {
 6292: 		    if ($tuname ne $env{'user.name'}) { next; }
 6293: 		}
 6294: 		$access=($effect eq 'allow');
 6295: 		last;
 6296: 	    }
 6297: 	} else {
 6298: 	    if ($role) {
 6299: 		if ($role ne $urole) { next; }
 6300: 	    }
 6301: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6302: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6303: 		if ($tdom) {
 6304: 		    if ($tdom ne $udom) { next; }
 6305: 		}
 6306: 		if ($tcrs) {
 6307: 		    if ($tcrs ne $ucrs) { next; }
 6308: 		}
 6309: 		if ($tsec) {
 6310: 		    if ($tsec ne $usec) { next; }
 6311: 		}
 6312: 		$access=($effect eq 'allow');
 6313: 		last;
 6314: 	    }
 6315: 	    if ($realm eq '' && $role eq '') {
 6316: 		$access=($effect eq 'allow');
 6317: 	    }
 6318: 	}
 6319:     }
 6320:     return $access;
 6321: }
 6322: 
 6323: # ------------------------------------------------- Check for a user privilege
 6324: 
 6325: sub allowed {
 6326:     my ($priv,$uri,$symb,$role)=@_;
 6327:     my $ver_orguri=$uri;
 6328:     $uri=&deversion($uri);
 6329:     my $orguri=$uri;
 6330:     $uri=&declutter($uri);
 6331: 
 6332:     if ($priv eq 'evb') {
 6333: # Evade communication block restrictions for specified role in a course
 6334:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6335:             return $1;
 6336:         } else {
 6337:             return;
 6338:         }
 6339:     }
 6340: 
 6341:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6342: # Free bre access to adm and meta resources
 6343:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6344: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6345: 	&& ($priv eq 'bre')) {
 6346: 	return 'F';
 6347:     }
 6348: 
 6349: # Free bre access to user's own portfolio contents
 6350:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6351:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6352: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6353:         my %setters;
 6354:         my ($startblock,$endblock) = 
 6355:             &Apache::loncommon::blockcheck(\%setters,'port');
 6356:         if ($startblock && $endblock) {
 6357:             return 'B';
 6358:         } else {
 6359:             return 'F';
 6360:         }
 6361:     }
 6362: 
 6363: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6364:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6365:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6366:         if (exists($env{'request.course.id'})) {
 6367:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6368:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6369:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6370:                 my $courseprivid=$env{'request.course.id'};
 6371:                 $courseprivid=~s/\_/\//;
 6372:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6373:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6374:                     return $1; 
 6375:                 } else {
 6376:                     if ($env{'request.course.sec'}) {
 6377:                         $courseprivid.='/'.$env{'request.course.sec'};
 6378:                     }
 6379:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6380:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6381:                         return $2;
 6382:                     }
 6383:                 }
 6384:             }
 6385:         }
 6386:     }
 6387: 
 6388: # Free bre to public access
 6389: 
 6390:     if ($priv eq 'bre') {
 6391:         my $copyright=&metadata($uri,'copyright');
 6392: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6393:            return 'F'; 
 6394:         }
 6395:         if ($copyright eq 'priv') {
 6396:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6397: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6398: 		return '';
 6399:             }
 6400:         }
 6401:         if ($copyright eq 'domain') {
 6402:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6403: 	    unless (($env{'user.domain'} eq $1) ||
 6404:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6405: 		return '';
 6406:             }
 6407:         }
 6408:         if ($env{'request.role'}=~ /li\.\//) {
 6409:             # Library role, so allow browsing of resources in this domain.
 6410:             return 'F';
 6411:         }
 6412:         if ($copyright eq 'custom') {
 6413: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6414:         }
 6415:     }
 6416:     # Domain coordinator is trying to create a course
 6417:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6418:         # uri is the requested domain in this case.
 6419:         # comparison to 'request.role.domain' shows if the user has selected
 6420:         # a role of dc for the domain in question.
 6421:         return 'F' if ($uri eq $env{'request.role.domain'});
 6422:     }
 6423: 
 6424:     my $thisallowed='';
 6425:     my $statecond=0;
 6426:     my $courseprivid='';
 6427: 
 6428:     my $ownaccess;
 6429:     # Community Coordinator or Assistant Co-author browsing resource space.
 6430:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6431:         if ($uri eq '') {
 6432:             $ownaccess = 1;
 6433:         } else {
 6434:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6435:                 my $udom = $env{'user.domain'};
 6436:                 my $uname = $env{'user.name'};
 6437:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6438:                     $ownaccess = 1;
 6439:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6440:                     unless ($uri =~ m{\.\./}) {
 6441:                         $ownaccess = 1;
 6442:                     }
 6443:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6444:                     my $now = time;
 6445:                     if ($uri =~ m{^([^/]+)/?$}) {
 6446:                         my $adom = $1;
 6447:                         foreach my $key (keys(%env)) {
 6448:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6449:                                 my ($start,$end) = split('.',$env{$key});
 6450:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6451:                                     $ownaccess = 1;
 6452:                                     last;
 6453:                                 }
 6454:                             }
 6455:                         }
 6456:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6457:                         my $adom = $1;
 6458:                         my $aname = $2;
 6459:                         foreach my $role ('ca','aa') { 
 6460:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6461:                                 my ($start,$end) =
 6462:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6463:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6464:                                     $ownaccess = 1;
 6465:                                     last;
 6466:                                 }
 6467:                             }
 6468:                         }
 6469:                     }
 6470:                 }
 6471:             }
 6472:         }
 6473:     }
 6474: 
 6475: # Course
 6476: 
 6477:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6478:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6479:             $thisallowed.=$1;
 6480:         }
 6481:     }
 6482: 
 6483: # Domain
 6484: 
 6485:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6486:        =~/\Q$priv\E\&([^\:]*)/) {
 6487:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6488:             $thisallowed.=$1;
 6489:         }
 6490:     }
 6491: 
 6492: # User who is not author or co-author might still be able to edit
 6493: # resource of an author in the domain (e.g., if Domain Coordinator).
 6494:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6495:         (&allowed('mdc',$env{'request.course.id'}))) {
 6496:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6497:             $thisallowed.=$1;
 6498:         }
 6499:     }
 6500: 
 6501: # Course: uri itself is a course
 6502:     my $courseuri=$uri;
 6503:     $courseuri=~s/\_(\d)/\/$1/;
 6504:     $courseuri=~s/^([^\/])/\/$1/;
 6505: 
 6506:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6507:        =~/\Q$priv\E\&([^\:]*)/) {
 6508:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6509:             $thisallowed.=$1;
 6510:         }
 6511:     }
 6512: 
 6513: # URI is an uploaded document for this course, default permissions don't matter
 6514: # not allowing 'edit' access (editupload) to uploaded course docs
 6515:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6516: 	$thisallowed='';
 6517:         my ($match)=&is_on_map($uri);
 6518:         if ($match) {
 6519:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6520:                   =~/\Q$priv\E\&([^\:]*)/) {
 6521:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6522:                 if (@blockers > 0) {
 6523:                     $thisallowed = 'B';
 6524:                 } else {
 6525:                     $thisallowed.=$1;
 6526:                 }
 6527:             }
 6528:         } else {
 6529:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6530:             if ($refuri) {
 6531:                 if ($refuri =~ m|^/adm/|) {
 6532:                     $thisallowed='F';
 6533:                 } else {
 6534:                     $refuri=&declutter($refuri);
 6535:                     my ($match) = &is_on_map($refuri);
 6536:                     if ($match) {
 6537:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6538:                         if (@blockers > 0) {
 6539:                             $thisallowed = 'B';
 6540:                         } else {
 6541:                             $thisallowed='F';
 6542:                         }
 6543:                     }
 6544:                 }
 6545:             }
 6546:         }
 6547:     }
 6548: 
 6549:     if ($priv eq 'bre'
 6550: 	&& $thisallowed ne 'F' 
 6551: 	&& $thisallowed ne '2'
 6552: 	&& &is_portfolio_url($uri)) {
 6553: 	$thisallowed = &portfolio_access($uri);
 6554:     }
 6555:     
 6556: # Full access at system, domain or course-wide level? Exit.
 6557:     if ($thisallowed=~/F/) {
 6558: 	return 'F';
 6559:     }
 6560: 
 6561: # If this is generating or modifying users, exit with special codes
 6562: 
 6563:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6564: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6565: 	    my ($audom,$auname)=split('/',$uri);
 6566: # no author name given, so this just checks on the general right to make a co-author in this domain
 6567: 	    unless ($auname) { return $thisallowed; }
 6568: # an author name is given, so we are about to actually make a co-author for a certain account
 6569: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6570: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6571: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6572: 	}
 6573: 	return $thisallowed;
 6574:     }
 6575: #
 6576: # Gathered so far: system, domain and course wide privileges
 6577: #
 6578: # Course: See if uri or referer is an individual resource that is part of 
 6579: # the course
 6580: 
 6581:     if ($env{'request.course.id'}) {
 6582: 
 6583:        $courseprivid=$env{'request.course.id'};
 6584:        if ($env{'request.course.sec'}) {
 6585:           $courseprivid.='/'.$env{'request.course.sec'};
 6586:        }
 6587:        $courseprivid=~s/\_/\//;
 6588:        my $checkreferer=1;
 6589:        my ($match,$cond)=&is_on_map($uri);
 6590:        if ($match) {
 6591:            $statecond=$cond;
 6592:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6593:                =~/\Q$priv\E\&([^\:]*)/) {
 6594:                my $value = $1;
 6595:                if ($priv eq 'bre') {
 6596:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6597:                    if (@blockers > 0) {
 6598:                        $thisallowed = 'B';
 6599:                    } else {
 6600:                        $thisallowed.=$value;
 6601:                    }
 6602:                } else {
 6603:                    $thisallowed.=$value;
 6604:                }
 6605:                $checkreferer=0;
 6606:            }
 6607:        }
 6608:        
 6609:        if ($checkreferer) {
 6610: 	  my $refuri=$env{'httpref.'.$orguri};
 6611:             unless ($refuri) {
 6612:                 foreach my $key (keys(%env)) {
 6613: 		    if ($key=~/^httpref\..*\*/) {
 6614: 			my $pattern=$key;
 6615:                         $pattern=~s/^httpref\.\/res\///;
 6616:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6617:                         $pattern=~s/\//\\\//g;
 6618:                         if ($orguri=~/$pattern/) {
 6619: 			    $refuri=$env{$key};
 6620:                         }
 6621:                     }
 6622:                 }
 6623:             }
 6624: 
 6625:          if ($refuri) { 
 6626: 	  $refuri=&declutter($refuri);
 6627:           my ($match,$cond)=&is_on_map($refuri);
 6628:             if ($match) {
 6629:               my $refstatecond=$cond;
 6630:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6631:                   =~/\Q$priv\E\&([^\:]*)/) {
 6632:                   my $value = $1;
 6633:                   if ($priv eq 'bre') {
 6634:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6635:                       if (@blockers > 0) {
 6636:                           $thisallowed = 'B';
 6637:                       } else {
 6638:                           $thisallowed.=$value;
 6639:                       }
 6640:                   } else {
 6641:                       $thisallowed.=$value;
 6642:                   }
 6643:                   $uri=$refuri;
 6644:                   $statecond=$refstatecond;
 6645:               }
 6646:           }
 6647:         }
 6648:        }
 6649:    }
 6650: 
 6651: #
 6652: # Gathered now: all privileges that could apply, and condition number
 6653: # 
 6654: #
 6655: # Full or no access?
 6656: #
 6657: 
 6658:     if ($thisallowed=~/F/) {
 6659: 	return 'F';
 6660:     }
 6661: 
 6662:     unless ($thisallowed) {
 6663:         return '';
 6664:     }
 6665: 
 6666: # Restrictions exist, deal with them
 6667: #
 6668: #   C:according to course preferences
 6669: #   R:according to resource settings
 6670: #   L:unless locked
 6671: #   X:according to user session state
 6672: #
 6673: 
 6674: # Possibly locked functionality, check all courses
 6675: # Locks might take effect only after 10 minutes cache expiration for other
 6676: # courses, and 2 minutes for current course
 6677: 
 6678:     my $envkey;
 6679:     if ($thisallowed=~/L/) {
 6680:         foreach $envkey (keys(%env)) {
 6681:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6682:                my $courseid=$2;
 6683:                my $roleid=$1.'.'.$2;
 6684:                $courseid=~s/^\///;
 6685:                my $expiretime=600;
 6686:                if ($env{'request.role'} eq $roleid) {
 6687: 		  $expiretime=120;
 6688:                }
 6689: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6690:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6691:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6692: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6693:                }
 6694:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6695:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6696: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6697:                        &log($env{'user.domain'},$env{'user.name'},
 6698:                             $env{'user.home'},
 6699:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6700:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6701:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6702: 		       return '';
 6703:                    }
 6704:                }
 6705:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6706:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6707: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6708:                        &log($env{'user.domain'},$env{'user.name'},
 6709:                             $env{'user.home'},
 6710:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6711:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6712:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6713: 		       return '';
 6714:                    }
 6715:                }
 6716: 	   }
 6717:        }
 6718:     }
 6719:    
 6720: #
 6721: # Rest of the restrictions depend on selected course
 6722: #
 6723: 
 6724:     unless ($env{'request.course.id'}) {
 6725: 	if ($thisallowed eq 'A') {
 6726: 	    return 'A';
 6727:         } elsif ($thisallowed eq 'B') {
 6728:             return 'B';
 6729: 	} else {
 6730: 	    return '1';
 6731: 	}
 6732:     }
 6733: 
 6734: #
 6735: # Now user is definitely in a course
 6736: #
 6737: 
 6738: 
 6739: # Course preferences
 6740: 
 6741:    if ($thisallowed=~/C/) {
 6742:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6743:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6744:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6745: 	   =~/\Q$rolecode\E/) {
 6746: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6747: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6748: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6749: 			$env{'request.course.id'});
 6750: 	   }
 6751:            return '';
 6752:        }
 6753: 
 6754:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6755: 	   =~/\Q$unamedom\E/) {
 6756: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6757: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6758: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6759: 			$env{'request.course.id'});
 6760: 	   }
 6761:            return '';
 6762:        }
 6763:    }
 6764: 
 6765: # Resource preferences
 6766: 
 6767:    if ($thisallowed=~/R/) {
 6768:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6769:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6770: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6771: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6772: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6773: 	   }
 6774: 	   return '';
 6775:        }
 6776:    }
 6777: 
 6778: # Restricted by state or randomout?
 6779: 
 6780:    if ($thisallowed=~/X/) {
 6781:       if ($env{'acc.randomout'}) {
 6782: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6783:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6784:             return ''; 
 6785:          }
 6786:       }
 6787:       if (&condval($statecond)) {
 6788: 	 return '2';
 6789:       } else {
 6790:          return '';
 6791:       }
 6792:    }
 6793: 
 6794:     if ($thisallowed eq 'A') {
 6795: 	return 'A';
 6796:     } elsif ($thisallowed eq 'B') {
 6797:         return 'B';
 6798:     }
 6799:    return 'F';
 6800: }
 6801: 
 6802: # ------------------------------------------- Check construction space access
 6803: 
 6804: sub constructaccess {
 6805:     my ($url,$setpriv)=@_;
 6806: 
 6807: # We do not allow editing of previous versions of files
 6808:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6809: 
 6810: # Get username and domain from URL
 6811:     my ($ownername,$ownerdomain,$ownerhome);
 6812: 
 6813:     ($ownerdomain,$ownername) =
 6814:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6815: 
 6816: # The URL does not really point to any authorspace, forget it
 6817:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6818: 
 6819: # Now we need to see if the user has access to the authorspace of
 6820: # $ownername at $ownerdomain
 6821: 
 6822:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6823: # Real author for this?
 6824:        $ownerhome = $env{'user.home'};
 6825:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6826:           return ($ownername,$ownerdomain,$ownerhome);
 6827:        }
 6828:     } else {
 6829: # Co-author for this?
 6830:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6831:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6832:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6833:             return ($ownername,$ownerdomain,$ownerhome);
 6834:         }
 6835:     }
 6836: 
 6837: # We don't have any access right now. If we are not possibly going to do anything about this,
 6838: # we might as well leave
 6839:    unless ($setpriv) { return ''; }
 6840: 
 6841: # Backdoor access?
 6842:     my $allowed=&allowed('eco',$ownerdomain);
 6843: # Nope
 6844:     unless ($allowed) { return ''; }
 6845: # Looks like we may have access, but could be locked by the owner of the construction space
 6846:     if ($allowed eq 'U') {
 6847:         my %blocked=&get('environment',['domcoord.author'],
 6848:                          $ownerdomain,$ownername);
 6849: # Is blocked by owner
 6850:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6851:     }
 6852:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6853: # Grant temporary access
 6854:         my $then=$env{'user.login.time'};
 6855:         my $update==$env{'user.update.time'};
 6856:         if (!$update) { $update = $then; }
 6857:         my $refresh=$env{'user.refresh.time'};
 6858:         if (!$refresh) { $refresh = $update; }
 6859:         my $now = time;
 6860:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6861:                            $now,'ca','constructaccess');
 6862:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6863:         return($ownername,$ownerdomain,$ownerhome);
 6864:     }
 6865: # No business here
 6866:     return '';
 6867: }
 6868: 
 6869: sub get_comm_blocks {
 6870:     my ($cdom,$cnum) = @_;
 6871:     if ($cdom eq '' || $cnum eq '') {
 6872:         return unless ($env{'request.course.id'});
 6873:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6874:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6875:     }
 6876:     my %commblocks;
 6877:     my $hashid=$cdom.'_'.$cnum;
 6878:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6879:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6880:         %commblocks = %{$blocksref};
 6881:     } else {
 6882:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6883:         my $cachetime = 600;
 6884:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6885:     }
 6886:     return %commblocks;
 6887: }
 6888: 
 6889: sub has_comm_blocking {
 6890:     my ($priv,$symb,$uri,$blocks) = @_;
 6891:     return unless ($env{'request.course.id'});
 6892:     return unless ($priv eq 'bre');
 6893:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6894:     my %commblocks;
 6895:     if (ref($blocks) eq 'HASH') {
 6896:         %commblocks = %{$blocks};
 6897:     } else {
 6898:         %commblocks = &get_comm_blocks();
 6899:     }
 6900:     return unless (keys(%commblocks) > 0);
 6901:     if (!$symb) { $symb=&symbread($uri,1); }
 6902:     my ($map,$resid,undef)=&decode_symb($symb);
 6903:     my %tocheck = (
 6904:                     maps      => $map,
 6905:                     resources => $symb,
 6906:                   );
 6907:     my @blockers;
 6908:     my $now = time;
 6909:     my $navmap = Apache::lonnavmaps::navmap->new();
 6910:     foreach my $block (keys(%commblocks)) {
 6911:         if ($block =~ /^(\d+)____(\d+)$/) {
 6912:             my ($start,$end) = ($1,$2);
 6913:             if ($start <= $now && $end >= $now) {
 6914:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6915:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6916:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6917:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6918:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6919:                                     push(@blockers,$block);
 6920:                                 }
 6921:                             }
 6922:                         }
 6923:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6924:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6925:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6926:                                     push(@blockers,$block);
 6927:                                 }
 6928:                             }
 6929:                         }
 6930:                     }
 6931:                 }
 6932:             }
 6933:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6934:             my $item = $1;
 6935:             my @to_test;
 6936:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6937:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6938:                     my $check_interval;
 6939:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6940:                         my @interval;
 6941:                         my $type = 'map';
 6942:                         if ($item eq 'course') {
 6943:                             $type = 'course';
 6944:                             @interval=&EXT("resource.0.interval");
 6945:                         } else {
 6946:                             if ($item =~ /___\d+___/) {
 6947:                                 $type = 'resource';
 6948:                                 @interval=&EXT("resource.0.interval",$item);
 6949:                                 if (ref($navmap)) {                        
 6950:                                     my $res = $navmap->getBySymb($item); 
 6951:                                     push(@to_test,$res);
 6952:                                 }
 6953:                             } else {
 6954:                                 my $mapsymb = &symbread($item,1);
 6955:                                 if ($mapsymb) {
 6956:                                     if (ref($navmap)) {
 6957:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6958:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6959:                                         foreach my $res (@to_test) {
 6960:                                             my $symb = $res->symb();
 6961:                                             next if ($symb eq $mapsymb);
 6962:                                             if ($symb ne '') {
 6963:                                                 @interval=&EXT("resource.0.interval",$symb);
 6964:                                                 last;
 6965:                                             }
 6966:                                         }
 6967:                                     }
 6968:                                 }
 6969:                             }
 6970:                         }
 6971:                         if ($interval[0] =~ /\d+/) {
 6972:                             my $first_access;
 6973:                             if ($type eq 'resource') {
 6974:                                 $first_access=&get_first_access($interval[1],$item);
 6975:                             } elsif ($type eq 'map') {
 6976:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6977:                             } else {
 6978:                                 $first_access=&get_first_access($interval[1]);
 6979:                             }
 6980:                             if ($first_access) {
 6981:                                 my $timesup = $first_access+$interval[0];
 6982:                                 if ($timesup > $now) {
 6983:                                     foreach my $res (@to_test) {
 6984:                                         if ($res->is_problem()) {
 6985:                                             if ($res->completable()) {
 6986:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6987:                                                     push(@blockers,$block);
 6988:                                                 }
 6989:                                                 last;
 6990:                                             }
 6991:                                         }
 6992:                                     }
 6993:                                 }
 6994:                             }
 6995:                         }
 6996:                     }
 6997:                 }
 6998:             }
 6999:         }
 7000:     }
 7001:     return @blockers;
 7002: }
 7003: 
 7004: sub check_docs_block {
 7005:     my ($docsblock,$tocheck) =@_;
 7006:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7007:         return;
 7008:     }
 7009:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7010:         if ($tocheck->{'maps'}) {
 7011:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7012:                 return 1;
 7013:             }
 7014:         }
 7015:     }
 7016:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7017:         if ($tocheck->{'resources'}) {
 7018:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7019:                 return 1;
 7020:             }
 7021:         }
 7022:     }
 7023:     return;
 7024: }
 7025: 
 7026: #
 7027: #   Removes the versino from a URI and
 7028: #   splits it in to its filename and path to the filename.
 7029: #   Seems like File::Basename could have done this more clearly.
 7030: #   Parameters:
 7031: #      $uri   - input URI
 7032: #   Returns:
 7033: #     Two element list consisting of 
 7034: #     $pathname  - the URI up to and excluding the trailing /
 7035: #     $filename  - The part of the URI following the last /
 7036: #  NOTE:
 7037: #    Another realization of this is simply:
 7038: #    use File::Basename;
 7039: #    ...
 7040: #    $uri = shift;
 7041: #    $filename = basename($uri);
 7042: #    $path     = dirname($uri);
 7043: #    return ($filename, $path);
 7044: #
 7045: #     The implementation below is probably faster however.
 7046: #
 7047: sub split_uri_for_cond {
 7048:     my $uri=&deversion(&declutter(shift));
 7049:     my @uriparts=split(/\//,$uri);
 7050:     my $filename=pop(@uriparts);
 7051:     my $pathname=join('/',@uriparts);
 7052:     return ($pathname,$filename);
 7053: }
 7054: # --------------------------------------------------- Is a resource on the map?
 7055: 
 7056: sub is_on_map {
 7057:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7058:     #Trying to find the conditional for the file
 7059:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7060: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7061:     if ($match) {
 7062: 	return (1,$1);
 7063:     } else {
 7064: 	return (0,0);
 7065:     }
 7066: }
 7067: 
 7068: # --------------------------------------------------------- Get symb from alias
 7069: 
 7070: sub get_symb_from_alias {
 7071:     my $symb=shift;
 7072:     my ($map,$resid,$url)=&decode_symb($symb);
 7073: # Already is a symb
 7074:     if ($url) { return $symb; }
 7075: # Must be an alias
 7076:     my $aliassymb='';
 7077:     my %bighash;
 7078:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7079:                             &GDBM_READER(),0640)) {
 7080:         my $rid=$bighash{'mapalias_'.$symb};
 7081: 	if ($rid) {
 7082: 	    my ($mapid,$resid)=split(/\./,$rid);
 7083: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7084: 				    $resid,$bighash{'src_'.$rid});
 7085: 	}
 7086:         untie %bighash;
 7087:     }
 7088:     return $aliassymb;
 7089: }
 7090: 
 7091: # ----------------------------------------------------------------- Define Role
 7092: 
 7093: sub definerole {
 7094:   if (allowed('mcr','/')) {
 7095:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7096:     foreach my $role (split(':',$sysrole)) {
 7097: 	my ($crole,$cqual)=split(/\&/,$role);
 7098:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7099:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7100: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7101:                return "refused:s:$crole&$cqual"; 
 7102:             }
 7103:         }
 7104:     }
 7105:     foreach my $role (split(':',$domrole)) {
 7106: 	my ($crole,$cqual)=split(/\&/,$role);
 7107:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7108:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7109: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7110:                return "refused:d:$crole&$cqual"; 
 7111:             }
 7112:         }
 7113:     }
 7114:     foreach my $role (split(':',$courole)) {
 7115: 	my ($crole,$cqual)=split(/\&/,$role);
 7116:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7117:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7118: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7119:                return "refused:c:$crole&$cqual"; 
 7120:             }
 7121:         }
 7122:     }
 7123:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7124:                 "$env{'user.domain'}:$env{'user.name'}:".
 7125: 	        "rolesdef_$rolename=".
 7126:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7127:     return reply($command,$env{'user.home'});
 7128:   } else {
 7129:     return 'refused';
 7130:   }
 7131: }
 7132: 
 7133: # ---------------- Make a metadata query against the network of library servers
 7134: 
 7135: sub metadata_query {
 7136:     my ($query,$custom,$customshow,$server_array)=@_;
 7137:     my %rhash;
 7138:     my %libserv = &all_library();
 7139:     my @server_list = (defined($server_array) ? @$server_array
 7140:                                               : keys(%libserv) );
 7141:     for my $server (@server_list) {
 7142: 	unless ($custom or $customshow) {
 7143: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7144: 	    $rhash{$server}=$reply;
 7145: 	}
 7146: 	else {
 7147: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7148: 			     &escape($custom).':'.&escape($customshow),
 7149: 			     $server);
 7150: 	    $rhash{$server}=$reply;
 7151: 	}
 7152:     }
 7153:     return \%rhash;
 7154: }
 7155: 
 7156: # ----------------------------------------- Send log queries and wait for reply
 7157: 
 7158: sub log_query {
 7159:     my ($uname,$udom,$query,%filters)=@_;
 7160:     my $uhome=&homeserver($uname,$udom);
 7161:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7162:     my $uhost=&hostname($uhome);
 7163:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7164:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7165:                        $uhome);
 7166:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7167:     return get_query_reply($queryid);
 7168: }
 7169: 
 7170: # -------------------------- Update MySQL table for portfolio file
 7171: 
 7172: sub update_portfolio_table {
 7173:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7174:     if ($group ne '') {
 7175:         $file_name =~s /^\Q$group\E//;
 7176:     }
 7177:     my $homeserver = &homeserver($uname,$udom);
 7178:     my $queryid=
 7179:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7180:                ':'.&escape($file_name).':'.$action,$homeserver);
 7181:     my $reply = &get_query_reply($queryid);
 7182:     return $reply;
 7183: }
 7184: 
 7185: # -------------------------- Update MySQL allusers table
 7186: 
 7187: sub update_allusers_table {
 7188:     my ($uname,$udom,$names) = @_;
 7189:     my $homeserver = &homeserver($uname,$udom);
 7190:     my $queryid=
 7191:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7192:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7193:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7194:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7195:                'generation='.&escape($names->{'generation'}).'%%'.
 7196:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7197:                'id='.&escape($names->{'id'}),$homeserver);
 7198:     return;
 7199: }
 7200: 
 7201: # ------- Request retrieval of institutional classlists for course(s)
 7202: 
 7203: sub fetch_enrollment_query {
 7204:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7205:     my $homeserver;
 7206:     my $maxtries = 1;
 7207:     if ($context eq 'automated') {
 7208:         $homeserver = $perlvar{'lonHostID'};
 7209:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7210:     } else {
 7211:         $homeserver = &homeserver($cnum,$dom);
 7212:     }
 7213:     my $host=&hostname($homeserver);
 7214:     my $cmd = '';
 7215:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7216:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7217:     }
 7218:     $cmd =~ s/%%$//;
 7219:     $cmd = &escape($cmd);
 7220:     my $query = 'fetchenrollment';
 7221:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7222:     unless ($queryid=~/^\Q$host\E\_/) { 
 7223:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7224:         return 'error: '.$queryid;
 7225:     }
 7226:     my $reply = &get_query_reply($queryid);
 7227:     my $tries = 1;
 7228:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7229:         $reply = &get_query_reply($queryid);
 7230:         $tries ++;
 7231:     }
 7232:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7233:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7234:     } else {
 7235:         my @responses = split(/:/,$reply);
 7236:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7237:             foreach my $line (@responses) {
 7238:                 my ($key,$value) = split(/=/,$line,2);
 7239:                 $$replyref{$key} = $value;
 7240:             }
 7241:         } else {
 7242:             my $pathname = LONCAPA::tempdir();
 7243:             foreach my $line (@responses) {
 7244:                 my ($key,$value) = split(/=/,$line);
 7245:                 $$replyref{$key} = $value;
 7246:                 if ($value > 0) {
 7247:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7248:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7249:                         my $destname = $pathname.'/'.$filename;
 7250:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7251:                         if ($xml_classlist =~ /^error/) {
 7252:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7253:                         } else {
 7254:                             if ( open(FILE,">$destname") ) {
 7255:                                 print FILE &unescape($xml_classlist);
 7256:                                 close(FILE);
 7257:                             } else {
 7258:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7259:                             }
 7260:                         }
 7261:                     }
 7262:                 }
 7263:             }
 7264:         }
 7265:         return 'ok';
 7266:     }
 7267:     return 'error';
 7268: }
 7269: 
 7270: sub get_query_reply {
 7271:     my $queryid=shift;
 7272:     my $replyfile=LONCAPA::tempdir().$queryid;
 7273:     my $reply='';
 7274:     for (1..100) {
 7275: 	sleep 2;
 7276:         if (-e $replyfile.'.end') {
 7277: 	    if (open(my $fh,$replyfile)) {
 7278: 		$reply = join('',<$fh>);
 7279: 		close($fh);
 7280: 	   } else { return 'error: reply_file_error'; }
 7281:            return &unescape($reply);
 7282: 	}
 7283:     }
 7284:     return 'timeout:'.$queryid;
 7285: }
 7286: 
 7287: sub courselog_query {
 7288: #
 7289: # possible filters:
 7290: # url: url or symb
 7291: # username
 7292: # domain
 7293: # action: view, submit, grade
 7294: # start: timestamp
 7295: # end: timestamp
 7296: #
 7297:     my (%filters)=@_;
 7298:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7299:     if ($filters{'url'}) {
 7300: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7301:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7302:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7303:     }
 7304:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7305:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7306:     return &log_query($cname,$cdom,'courselog',%filters);
 7307: }
 7308: 
 7309: sub userlog_query {
 7310: #
 7311: # possible filters:
 7312: # action: log check role
 7313: # start: timestamp
 7314: # end: timestamp
 7315: #
 7316:     my ($uname,$udom,%filters)=@_;
 7317:     return &log_query($uname,$udom,'userlog',%filters);
 7318: }
 7319: 
 7320: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7321: 
 7322: sub auto_run {
 7323:     my ($cnum,$cdom) = @_;
 7324:     my $response = 0;
 7325:     my $settings;
 7326:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7327:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7328:         $settings = $domconfig{'autoenroll'};
 7329:         if ($settings->{'run'} eq '1') {
 7330:             $response = 1;
 7331:         }
 7332:     } else {
 7333:         my $homeserver;
 7334:         if (&is_course($cdom,$cnum)) {
 7335:             $homeserver = &homeserver($cnum,$cdom);
 7336:         } else {
 7337:             $homeserver = &domain($cdom,'primary');
 7338:         }
 7339:         if ($homeserver ne 'no_host') {
 7340:             $response = &reply('autorun:'.$cdom,$homeserver);
 7341:         }
 7342:     }
 7343:     return $response;
 7344: }
 7345: 
 7346: sub auto_get_sections {
 7347:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7348:     my $homeserver;
 7349:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7350:         $homeserver = &homeserver($cnum,$cdom);
 7351:     }
 7352:     if (!defined($homeserver)) { 
 7353:         if ($cdom =~ /^$match_domain$/) {
 7354:             $homeserver = &domain($cdom,'primary');
 7355:         }
 7356:     }
 7357:     my @secs;
 7358:     if (defined($homeserver)) {
 7359:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7360:         unless ($response eq 'refused') {
 7361:             @secs = split(/:/,$response);
 7362:         }
 7363:     }
 7364:     return @secs;
 7365: }
 7366: 
 7367: sub auto_new_course {
 7368:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7369:     my $homeserver = &homeserver($cnum,$cdom);
 7370:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7371:     return $response;
 7372: }
 7373: 
 7374: sub auto_validate_courseID {
 7375:     my ($cnum,$cdom,$inst_course_id) = @_;
 7376:     my $homeserver = &homeserver($cnum,$cdom);
 7377:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7378:     return $response;
 7379: }
 7380: 
 7381: sub auto_validate_instcode {
 7382:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7383:     my ($homeserver,$response);
 7384:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7385:         $homeserver = &homeserver($cnum,$cdom);
 7386:     }
 7387:     if (!defined($homeserver)) {
 7388:         if ($cdom =~ /^$match_domain$/) {
 7389:             $homeserver = &domain($cdom,'primary');
 7390:         }
 7391:     }
 7392:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7393:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7394:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7395:     return ($outcome,$description);
 7396: }
 7397: 
 7398: sub auto_create_password {
 7399:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7400:     my ($homeserver,$response);
 7401:     my $create_passwd = 0;
 7402:     my $authchk = '';
 7403:     if ($udom =~ /^$match_domain$/) {
 7404:         $homeserver = &domain($udom,'primary');
 7405:     }
 7406:     if ($homeserver eq '') {
 7407:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7408:             $homeserver = &homeserver($cnum,$cdom);
 7409:         }
 7410:     }
 7411:     if ($homeserver eq '') {
 7412:         $authchk = 'nodomain';
 7413:     } else {
 7414:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7415:         if ($response eq 'refused') {
 7416:             $authchk = 'refused';
 7417:         } else {
 7418:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7419:         }
 7420:     }
 7421:     return ($authparam,$create_passwd,$authchk);
 7422: }
 7423: 
 7424: sub auto_photo_permission {
 7425:     my ($cnum,$cdom,$students) = @_;
 7426:     my $homeserver = &homeserver($cnum,$cdom);
 7427:     my ($outcome,$perm_reqd,$conditions) = 
 7428: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7429:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7430: 	return (undef,undef);
 7431:     }
 7432:     return ($outcome,$perm_reqd,$conditions);
 7433: }
 7434: 
 7435: sub auto_checkphotos {
 7436:     my ($uname,$udom,$pid) = @_;
 7437:     my $homeserver = &homeserver($uname,$udom);
 7438:     my ($result,$resulttype);
 7439:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7440: 				   &escape($uname).':'.&escape($pid),
 7441: 				   $homeserver));
 7442:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7443: 	return (undef,undef);
 7444:     }
 7445:     if ($outcome) {
 7446:         ($result,$resulttype) = split(/:/,$outcome);
 7447:     } 
 7448:     return ($result,$resulttype);
 7449: }
 7450: 
 7451: sub auto_photochoice {
 7452:     my ($cnum,$cdom) = @_;
 7453:     my $homeserver = &homeserver($cnum,$cdom);
 7454:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7455: 						       &escape($cdom),
 7456: 						       $homeserver)));
 7457:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7458: 	return (undef,undef);
 7459:     }
 7460:     return ($update,$comment);
 7461: }
 7462: 
 7463: sub auto_photoupdate {
 7464:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7465:     my $homeserver = &homeserver($cnum,$dom);
 7466:     my $host=&hostname($homeserver);
 7467:     my $cmd = '';
 7468:     my $maxtries = 1;
 7469:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7470:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7471:     }
 7472:     $cmd =~ s/%%$//;
 7473:     $cmd = &escape($cmd);
 7474:     my $query = 'institutionalphotos';
 7475:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7476:     unless ($queryid=~/^\Q$host\E\_/) {
 7477:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7478:         return 'error: '.$queryid;
 7479:     }
 7480:     my $reply = &get_query_reply($queryid);
 7481:     my $tries = 1;
 7482:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7483:         $reply = &get_query_reply($queryid);
 7484:         $tries ++;
 7485:     }
 7486:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7487:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7488:     } else {
 7489:         my @responses = split(/:/,$reply);
 7490:         my $outcome = shift(@responses); 
 7491:         foreach my $item (@responses) {
 7492:             my ($key,$value) = split(/=/,$item);
 7493:             $$photo{$key} = $value;
 7494:         }
 7495:         return $outcome;
 7496:     }
 7497:     return 'error';
 7498: }
 7499: 
 7500: sub auto_instcode_format {
 7501:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7502: 	$cat_order) = @_;
 7503:     my $courses = '';
 7504:     my @homeservers;
 7505:     if ($caller eq 'global') {
 7506: 	my %servers = &get_servers($codedom,'library');
 7507: 	foreach my $tryserver (keys(%servers)) {
 7508: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7509: 		push(@homeservers,$tryserver);
 7510: 	    }
 7511:         }
 7512:     } elsif ($caller eq 'requests') {
 7513:         if ($codedom =~ /^$match_domain$/) {
 7514:             my $chome = &domain($codedom,'primary');
 7515:             unless ($chome eq 'no_host') {
 7516:                 push(@homeservers,$chome);
 7517:             }
 7518:         }
 7519:     } else {
 7520:         push(@homeservers,&homeserver($caller,$codedom));
 7521:     }
 7522:     foreach my $code (keys(%{$instcodes})) {
 7523:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7524:     }
 7525:     chop($courses);
 7526:     my $ok_response = 0;
 7527:     my $response;
 7528:     while (@homeservers > 0 && $ok_response == 0) {
 7529:         my $server = shift(@homeservers); 
 7530:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7531:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7532:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7533: 		split(/:/,$response);
 7534:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7535:             push(@{$codetitles},&str2array($codetitles_str));
 7536:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7537:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7538:             $ok_response = 1;
 7539:         }
 7540:     }
 7541:     if ($ok_response) {
 7542:         return 'ok';
 7543:     } else {
 7544:         return $response;
 7545:     }
 7546: }
 7547: 
 7548: sub auto_instcode_defaults {
 7549:     my ($domain,$returnhash,$code_order) = @_;
 7550:     my @homeservers;
 7551: 
 7552:     my %servers = &get_servers($domain,'library');
 7553:     foreach my $tryserver (keys(%servers)) {
 7554: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7555: 	    push(@homeservers,$tryserver);
 7556: 	}
 7557:     }
 7558: 
 7559:     my $response;
 7560:     foreach my $server (@homeservers) {
 7561:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7562:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7563: 	
 7564: 	foreach my $pair (split(/\&/,$response)) {
 7565: 	    my ($name,$value)=split(/\=/,$pair);
 7566: 	    if ($name eq 'code_order') {
 7567: 		@{$code_order} = split(/\&/,&unescape($value));
 7568: 	    } else {
 7569: 		$returnhash->{&unescape($name)}=&unescape($value);
 7570: 	    }
 7571: 	}
 7572: 	return 'ok';
 7573:     }
 7574: 
 7575:     return $response;
 7576: }
 7577: 
 7578: sub auto_possible_instcodes {
 7579:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7580:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7581:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7582:         return;
 7583:     }
 7584:     my (@homeservers,$uhome);
 7585:     if (defined(&domain($domain,'primary'))) {
 7586:         $uhome=&domain($domain,'primary');
 7587:         push(@homeservers,&domain($domain,'primary'));
 7588:     } else {
 7589:         my %servers = &get_servers($domain,'library');
 7590:         foreach my $tryserver (keys(%servers)) {
 7591:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7592:                 push(@homeservers,$tryserver);
 7593:             }
 7594:         }
 7595:     }
 7596:     my $response;
 7597:     foreach my $server (@homeservers) {
 7598:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7599:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7600:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7601:             split(':',$response);
 7602:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7603:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7604:         foreach my $item (split('&',$cat_title)) {   
 7605:             my ($name,$value)=split('=',$item);
 7606:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7607:         }
 7608:         foreach my $item (split('&',$cat_order)) {
 7609:             my ($name,$value)=split('=',$item);
 7610:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7611:         }
 7612:         return 'ok';
 7613:     }
 7614:     return $response;
 7615: }
 7616: 
 7617: sub auto_courserequest_checks {
 7618:     my ($dom) = @_;
 7619:     my ($homeserver,%validations);
 7620:     if ($dom =~ /^$match_domain$/) {
 7621:         $homeserver = &domain($dom,'primary');
 7622:     }
 7623:     unless ($homeserver eq 'no_host') {
 7624:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7625:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7626:             my @items = split(/&/,$response);
 7627:             foreach my $item (@items) {
 7628:                 my ($key,$value) = split('=',$item);
 7629:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7630:             }
 7631:         }
 7632:     }
 7633:     return %validations; 
 7634: }
 7635: 
 7636: sub auto_courserequest_validation {
 7637:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7638:     my ($homeserver,$response);
 7639:     if ($dom =~ /^$match_domain$/) {
 7640:         $homeserver = &domain($dom,'primary');
 7641:     }
 7642:     unless ($homeserver eq 'no_host') {  
 7643:           
 7644:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7645:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7646:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7647:                                     $homeserver));
 7648:     }
 7649:     return $response;
 7650: }
 7651: 
 7652: sub auto_validate_class_sec {
 7653:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7654:     my $homeserver = &homeserver($cnum,$cdom);
 7655:     my $ownerlist;
 7656:     if (ref($owners) eq 'ARRAY') {
 7657:         $ownerlist = join(',',@{$owners});
 7658:     } else {
 7659:         $ownerlist = $owners;
 7660:     }
 7661:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7662:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7663:     return $response;
 7664: }
 7665: 
 7666: # ------------------------------------------------------- Course Group routines
 7667: 
 7668: sub get_coursegroups {
 7669:     my ($cdom,$cnum,$group,$namespace) = @_;
 7670:     return(&dump($namespace,$cdom,$cnum,$group));
 7671: }
 7672: 
 7673: sub modify_coursegroup {
 7674:     my ($cdom,$cnum,$groupsettings) = @_;
 7675:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7676: }
 7677: 
 7678: sub toggle_coursegroup_status {
 7679:     my ($cdom,$cnum,$group,$action) = @_;
 7680:     my ($from_namespace,$to_namespace);
 7681:     if ($action eq 'delete') {
 7682:         $from_namespace = 'coursegroups';
 7683:         $to_namespace = 'deleted_groups';
 7684:     } else {
 7685:         $from_namespace = 'deleted_groups';
 7686:         $to_namespace = 'coursegroups';
 7687:     }
 7688:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7689:     if (my $tmp = &error(%curr_group)) {
 7690:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7691:         return ('read error',$tmp);
 7692:     } else {
 7693:         my %savedsettings = %curr_group; 
 7694:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7695:         my $deloutcome;
 7696:         if ($result eq 'ok') {
 7697:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7698:         } else {
 7699:             return ('write error',$result);
 7700:         }
 7701:         if ($deloutcome eq 'ok') {
 7702:             return 'ok';
 7703:         } else {
 7704:             return ('delete error',$deloutcome);
 7705:         }
 7706:     }
 7707: }
 7708: 
 7709: sub modify_group_roles {
 7710:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7711:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7712:     my $role = 'gr/'.&escape($userprivs);
 7713:     my ($uname,$udom) = split(/:/,$user);
 7714:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7715:     if ($result eq 'ok') {
 7716:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7717:     }
 7718:     return $result;
 7719: }
 7720: 
 7721: sub modify_coursegroup_membership {
 7722:     my ($cdom,$cnum,$membership) = @_;
 7723:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7724:     return $result;
 7725: }
 7726: 
 7727: sub get_active_groups {
 7728:     my ($udom,$uname,$cdom,$cnum) = @_;
 7729:     my $now = time;
 7730:     my %groups = ();
 7731:     foreach my $key (keys(%env)) {
 7732:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7733:             my ($start,$end) = split(/\./,$env{$key});
 7734:             if (($end!=0) && ($end<$now)) { next; }
 7735:             if (($start!=0) && ($start>$now)) { next; }
 7736:             if ($1 eq $cdom && $2 eq $cnum) {
 7737:                 $groups{$3} = $env{$key} ;
 7738:             }
 7739:         }
 7740:     }
 7741:     return %groups;
 7742: }
 7743: 
 7744: sub get_group_membership {
 7745:     my ($cdom,$cnum,$group) = @_;
 7746:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7747: }
 7748: 
 7749: sub get_users_groups {
 7750:     my ($udom,$uname,$courseid) = @_;
 7751:     my @usersgroups;
 7752:     my $cachetime=1800;
 7753: 
 7754:     my $hashid="$udom:$uname:$courseid";
 7755:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7756:     if (defined($cached)) {
 7757:         @usersgroups = split(/:/,$grouplist);
 7758:     } else {  
 7759:         $grouplist = '';
 7760:         my $courseurl = &courseid_to_courseurl($courseid);
 7761:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7762:         my $access_end = $env{'course.'.$courseid.
 7763:                               '.default_enrollment_end_date'};
 7764:         my $now = time;
 7765:         foreach my $key (keys(%roleshash)) {
 7766:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7767:                 my $group = $1;
 7768:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7769:                     my $start = $2;
 7770:                     my $end = $1;
 7771:                     if ($start == -1) { next; } # deleted from group
 7772:                     if (($start!=0) && ($start>$now)) { next; }
 7773:                     if (($end!=0) && ($end<$now)) {
 7774:                         if ($access_end && $access_end < $now) {
 7775:                             if ($access_end - $end < 86400) {
 7776:                                 push(@usersgroups,$group);
 7777:                             }
 7778:                         }
 7779:                         next;
 7780:                     }
 7781:                     push(@usersgroups,$group);
 7782:                 }
 7783:             }
 7784:         }
 7785:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7786:         $grouplist = join(':',@usersgroups);
 7787:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7788:     }
 7789:     return @usersgroups;
 7790: }
 7791: 
 7792: sub devalidate_getgroups_cache {
 7793:     my ($udom,$uname,$cdom,$cnum)=@_;
 7794:     my $courseid = $cdom.'_'.$cnum;
 7795: 
 7796:     my $hashid="$udom:$uname:$courseid";
 7797:     &devalidate_cache_new('getgroups',$hashid);
 7798: }
 7799: 
 7800: # ------------------------------------------------------------------ Plain Text
 7801: 
 7802: sub plaintext {
 7803:     my ($short,$type,$cid,$forcedefault) = @_;
 7804:     if ($short =~ m{^cr/}) {
 7805: 	return (split('/',$short))[-1];
 7806:     }
 7807:     if (!defined($cid)) {
 7808:         $cid = $env{'request.course.id'};
 7809:     }
 7810:     my %rolenames = (
 7811:                       Course    => 'std',
 7812:                       Community => 'alt1',
 7813:                     );
 7814:     if ($cid ne '') {
 7815:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7816:             unless ($forcedefault) {
 7817:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7818:                 &Apache::lonlocal::mt_escape(\$roletext);
 7819:                 return &Apache::lonlocal::mt($roletext);
 7820:             }
 7821:         }
 7822:     }
 7823:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7824:         (defined($rolenames{$type})) && 
 7825:         (defined($prp{$short}{$rolenames{$type}}))) {
 7826:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7827:     } elsif ($cid ne '') {
 7828:         my $crstype = $env{'course.'.$cid.'.type'};
 7829:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7830:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7831:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7832:         }
 7833:     }
 7834:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7835: }
 7836: 
 7837: # ----------------------------------------------------------------- Assign Role
 7838: 
 7839: sub assignrole {
 7840:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7841:         $context)=@_;
 7842:     my $mrole;
 7843:     if ($role =~ /^cr\//) {
 7844:         my $cwosec=$url;
 7845:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7846: 	unless (&allowed('ccr',$cwosec)) {
 7847:            my $refused = 1;
 7848:            if ($context eq 'requestcourses') {
 7849:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7850:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7851:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7852:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7853:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7854:                            if ($crsenv{'internal.courseowner'} eq
 7855:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7856:                                $refused = '';
 7857:                            }
 7858:                        }
 7859:                    }
 7860:                }
 7861:            }
 7862:            if ($refused) {
 7863:                &logthis('Refused custom assignrole: '.
 7864:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7865:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7866:                return 'refused';
 7867:            }
 7868:         }
 7869:         $mrole='cr';
 7870:     } elsif ($role =~ /^gr\//) {
 7871:         my $cwogrp=$url;
 7872:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7873:         unless (&allowed('mdg',$cwogrp)) {
 7874:             &logthis('Refused group assignrole: '.
 7875:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7876:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7877:             return 'refused';
 7878:         }
 7879:         $mrole='gr';
 7880:     } else {
 7881:         my $cwosec=$url;
 7882:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7883:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7884:             my $refused;
 7885:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7886:                 if (!(&allowed('c'.$role,$url))) {
 7887:                     $refused = 1;
 7888:                 }
 7889:             } else {
 7890:                 $refused = 1;
 7891:             }
 7892:             if ($refused) {
 7893:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7894:                 if (!$selfenroll && $context eq 'course') {
 7895:                     my %crsenv;
 7896:                     if ($role eq 'cc' || $role eq 'co') {
 7897:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7898:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7899:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7900:                                 if ($crsenv{'internal.courseowner'} eq 
 7901:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7902:                                     $refused = '';
 7903:                                 }
 7904:                             }
 7905:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7906:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7907:                                 if ($crsenv{'internal.courseowner'} eq 
 7908:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7909:                                     $refused = '';
 7910:                                 }
 7911:                             }
 7912:                         }
 7913:                     }
 7914:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7915:                     $refused = '';
 7916:                 } elsif ($context eq 'requestcourses') {
 7917:                     my @possroles = ('st','ta','ep','in','cc','co');
 7918:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7919:                         my $wrongcc;
 7920:                         if ($cnum =~ /^$match_community$/) {
 7921:                             $wrongcc = 1 if ($role eq 'cc');
 7922:                         } else {
 7923:                             $wrongcc = 1 if ($role eq 'co');
 7924:                         }
 7925:                         unless ($wrongcc) {
 7926:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7927:                             if ($crsenv{'internal.courseowner'} eq 
 7928:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7929:                                 $refused = '';
 7930:                             }
 7931:                         }
 7932:                     }
 7933:                 } elsif ($context eq 'requestauthor') {
 7934:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7935:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7936:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7937:                             $refused = '';
 7938:                         } else {
 7939:                             my %domdefaults = &get_domain_defaults($udom);
 7940:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7941:                                 my $checkbystatus;
 7942:                                 if ($env{'user.adv'}) { 
 7943:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7944:                                     if ($disposition eq 'automatic') {
 7945:                                         $refused = '';
 7946:                                     } elsif ($disposition eq '') {
 7947:                                         $checkbystatus = 1;
 7948:                                     } 
 7949:                                 } else {
 7950:                                     $checkbystatus = 1;
 7951:                                 }
 7952:                                 if ($checkbystatus) {
 7953:                                     if ($env{'environment.inststatus'}) {
 7954:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7955:                                         foreach my $type (@inststatuses) {
 7956:                                             if (($type ne '') &&
 7957:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7958:                                                 $refused = '';
 7959:                                             }
 7960:                                         }
 7961:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7962:                                         $refused = '';
 7963:                                     }
 7964:                                 }
 7965:                             }
 7966:                         }
 7967:                     }
 7968:                 }
 7969:                 if ($refused) {
 7970:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7971:                              ' '.$role.' '.$end.' '.$start.' by '.
 7972: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7973:                     return 'refused';
 7974:                 }
 7975:             }
 7976:         } elsif ($role eq 'au') {
 7977:             if ($url ne '/'.$udom.'/') {
 7978:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7979:                          ' to assign author role for '.$uname.':'.$udom.
 7980:                          ' in domain: '.$url.' refused (wrong domain).');
 7981:                 return 'refused';
 7982:             }
 7983:         }
 7984:         $mrole=$role;
 7985:     }
 7986:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7987:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7988:     if ($end) { $command.='_'.$end; }
 7989:     if ($start) {
 7990: 	if ($end) { 
 7991:            $command.='_'.$start; 
 7992:         } else {
 7993:            $command.='_0_'.$start;
 7994:         }
 7995:     }
 7996:     my $origstart = $start;
 7997:     my $origend = $end;
 7998:     my $delflag;
 7999: # actually delete
 8000:     if ($deleteflag) {
 8001: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8002: # modify command to delete the role
 8003:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8004:                 "$udom:$uname:$url".'_'."$mrole";
 8005: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8006: # set start and finish to negative values for userrolelog
 8007:            $start=-1;
 8008:            $end=-1;
 8009:            $delflag = 1;
 8010:         }
 8011:     }
 8012: # send command
 8013:     my $answer=&reply($command,&homeserver($uname,$udom));
 8014: # log new user role if status is ok
 8015:     if ($answer eq 'ok') {
 8016: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8017: # for course roles, perform group memberships changes triggered by role change.
 8018:         unless ($role =~ /^gr/) {
 8019:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8020:                                              $origstart,$selfenroll,$context);
 8021:         }
 8022:         if (($role eq 'cc') || ($role eq 'in') ||
 8023:             ($role eq 'ep') || ($role eq 'ad') ||
 8024:             ($role eq 'ta') || ($role eq 'st') ||
 8025:             ($role=~/^cr/) || ($role eq 'gr') ||
 8026:             ($role eq 'co')) {
 8027:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8028:                            $selfenroll,$context);
 8029:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8030:                  ($role eq 'au') || ($role eq 'dc')) {
 8031:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8032:                            $context);
 8033:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8034:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8035:                              $context); 
 8036:         }
 8037:         if ($role eq 'cc') {
 8038:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8039:         }
 8040:     }
 8041:     return $answer;
 8042: }
 8043: 
 8044: sub autoupdate_coowners {
 8045:     my ($url,$end,$start,$uname,$udom) = @_;
 8046:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8047:     if (($cdom ne '') && ($cnum ne '')) {
 8048:         my $now = time;
 8049:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8050:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8051:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8052:             my $instcode = $coursehash{'internal.coursecode'};
 8053:             if ($instcode ne '') {
 8054:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8055:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8056:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8057:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8058:                         if ($result eq 'valid') {
 8059:                             if ($coursehash{'internal.co-owners'}) {
 8060:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8061:                                     push(@newcoowners,$coowner);
 8062:                                 }
 8063:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8064:                                     push(@newcoowners,$uname.':'.$udom);
 8065:                                 }
 8066:                                 @newcoowners = sort(@newcoowners);
 8067:                             } else {
 8068:                                 push(@newcoowners,$uname.':'.$udom);
 8069:                             }
 8070:                         } else {
 8071:                             if ($coursehash{'internal.co-owners'}) {
 8072:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8073:                                     unless ($coowner eq $uname.':'.$udom) {
 8074:                                         push(@newcoowners,$coowner);
 8075:                                     }
 8076:                                 }
 8077:                                 unless (@newcoowners > 0) {
 8078:                                     $delcoowners = 1;
 8079:                                     $coowners = '';
 8080:                                 }
 8081:                             }
 8082:                         }
 8083:                         if (@newcoowners || $delcoowners) {
 8084:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8085:                                             $delcoowners,@newcoowners);
 8086:                         }
 8087:                     }
 8088:                 }
 8089:             }
 8090:         }
 8091:     }
 8092: }
 8093: 
 8094: sub store_coowners {
 8095:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8096:     my $cid = $cdom.'_'.$cnum;
 8097:     my ($coowners,$delresult,$putresult);
 8098:     if (@newcoowners) {
 8099:         $coowners = join(',',@newcoowners);
 8100:         my %coownershash = (
 8101:                             'internal.co-owners' => $coowners,
 8102:                            );
 8103:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8104:         if ($putresult eq 'ok') {
 8105:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8106:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8107:             }
 8108:         }
 8109:     }
 8110:     if ($delcoowners) {
 8111:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8112:         if ($delresult eq 'ok') {
 8113:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8114:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8115:             }
 8116:         }
 8117:     }
 8118:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8119:         my %crsinfo =
 8120:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8121:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8122:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8123:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8124:         }
 8125:     }
 8126: }
 8127: 
 8128: # -------------------------------------------------- Modify user authentication
 8129: # Overrides without validation
 8130: 
 8131: sub modifyuserauth {
 8132:     my ($udom,$uname,$umode,$upass)=@_;
 8133:     my $uhome=&homeserver($uname,$udom);
 8134:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8135:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8136:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8137:              ' in domain '.$env{'request.role.domain'});  
 8138:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8139: 		     &escape($upass),$uhome);
 8140:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8141:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8142:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8143:     &log($udom,,$uname,$uhome,
 8144:         'Authentication changed by '.$env{'user.domain'}.', '.
 8145:                                      $env{'user.name'}.', '.$umode.
 8146:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8147:     unless ($reply eq 'ok') {
 8148:         &logthis('Authentication mode error: '.$reply);
 8149: 	return 'error: '.$reply;
 8150:     }   
 8151:     return 'ok';
 8152: }
 8153: 
 8154: # --------------------------------------------------------------- Modify a user
 8155: 
 8156: sub modifyuser {
 8157:     my ($udom,    $uname, $uid,
 8158:         $umode,   $upass, $first,
 8159:         $middle,  $last,  $gene,
 8160:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8161:     $udom= &LONCAPA::clean_domain($udom);
 8162:     $uname=&LONCAPA::clean_username($uname);
 8163:     my $showcandelete = 'none';
 8164:     if (ref($candelete) eq 'ARRAY') {
 8165:         if (@{$candelete} > 0) {
 8166:             $showcandelete = join(', ',@{$candelete});
 8167:         }
 8168:     }
 8169:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8170:              $umode.', '.$first.', '.$middle.', '.
 8171: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8172:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8173:                                      ' desiredhome not specified'). 
 8174:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8175:              ' in domain '.$env{'request.role.domain'});
 8176:     my $uhome=&homeserver($uname,$udom,'true');
 8177:     my $newuser;
 8178:     if ($uhome eq 'no_host') {
 8179:         $newuser = 1;
 8180:     }
 8181: # ----------------------------------------------------------------- Create User
 8182:     if (($uhome eq 'no_host') && 
 8183: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8184:         my $unhome='';
 8185:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8186:             $unhome = $desiredhome;
 8187: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8188: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8189:         } else { # load balancing routine for determining $unhome
 8190:             my $loadm=10000000;
 8191: 	    my %servers = &get_servers($udom,'library');
 8192: 	    foreach my $tryserver (keys(%servers)) {
 8193: 		my $answer=reply('load',$tryserver);
 8194: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8195: 		    $loadm=$answer;
 8196: 		    $unhome=$tryserver;
 8197: 		}
 8198: 	    }
 8199:         }
 8200:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8201: 	    return 'error: unable to find a home server for '.$uname.
 8202:                    ' in domain '.$udom;
 8203:         }
 8204:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8205:                          &escape($upass),$unhome);
 8206: 	unless ($reply eq 'ok') {
 8207:             return 'error: '.$reply;
 8208:         }   
 8209:         $uhome=&homeserver($uname,$udom,'true');
 8210:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8211: 	    return 'error: unable verify users home machine.';
 8212:         }
 8213:     }   # End of creation of new user
 8214: # ---------------------------------------------------------------------- Add ID
 8215:     if ($uid) {
 8216:        $uid=~tr/A-Z/a-z/;
 8217:        my %uidhash=&idrget($udom,$uname);
 8218:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8219:          && (!$forceid)) {
 8220: 	  unless ($uid eq $uidhash{$uname}) {
 8221: 	      return 'error: user id "'.$uid.'" does not match '.
 8222:                   'current user id "'.$uidhash{$uname}.'".';
 8223:           }
 8224:        } else {
 8225: 	  &idput($udom,($uname => $uid));
 8226:        }
 8227:     }
 8228: # -------------------------------------------------------------- Add names, etc
 8229:     my @tmp=&get('environment',
 8230: 		   ['firstname','middlename','lastname','generation','id',
 8231:                     'permanentemail','inststatus'],
 8232: 		   $udom,$uname);
 8233:     my (%names,%oldnames);
 8234:     if ($tmp[0] =~ m/^error:.*/) { 
 8235:         %names=(); 
 8236:     } else {
 8237:         %names = @tmp;
 8238:         %oldnames = %names;
 8239:     }
 8240: #
 8241: # If name, email and/or uid are blank (e.g., because an uploaded file
 8242: # of users did not contain them), do not overwrite existing values
 8243: # unless field is in $candelete array ref.  
 8244: #
 8245: 
 8246:     my @fields = ('firstname','middlename','lastname','generation',
 8247:                   'permanentemail','id');
 8248:     my %newvalues;
 8249:     if (ref($candelete) eq 'ARRAY') {
 8250:         foreach my $field (@fields) {
 8251:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8252:                 if ($field eq 'firstname') {
 8253:                     $names{$field} = $first;
 8254:                 } elsif ($field eq 'middlename') {
 8255:                     $names{$field} = $middle;
 8256:                 } elsif ($field eq 'lastname') {
 8257:                     $names{$field} = $last;
 8258:                 } elsif ($field eq 'generation') { 
 8259:                     $names{$field} = $gene;
 8260:                 } elsif ($field eq 'permanentemail') {
 8261:                     $names{$field} = $email;
 8262:                 } elsif ($field eq 'id') {
 8263:                     $names{$field}  = $uid;
 8264:                 }
 8265:             }
 8266:         }
 8267:     }
 8268:     if ($first)  { $names{'firstname'}  = $first; }
 8269:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8270:     if ($last)   { $names{'lastname'}   = $last; }
 8271:     if (defined($gene))   { $names{'generation'} = $gene; }
 8272:     if ($email) {
 8273:        $email=~s/[^\w\@\.\-\,]//gs;
 8274:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8275:     }
 8276:     if ($uid) { $names{'id'}  = $uid; }
 8277:     if (defined($inststatus)) {
 8278:         $names{'inststatus'} = '';
 8279:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8280:         if (ref($usertypes) eq 'HASH') {
 8281:             my @okstatuses; 
 8282:             foreach my $item (split(/:/,$inststatus)) {
 8283:                 if (defined($usertypes->{$item})) {
 8284:                     push(@okstatuses,$item);  
 8285:                 }
 8286:             }
 8287:             if (@okstatuses) {
 8288:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8289:             }
 8290:         }
 8291:     }
 8292:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8293:                  $umode.', '.$first.', '.$middle.', '.
 8294:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8295:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8296:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8297:     } else {
 8298:         $logmsg .= ' during self creation';
 8299:     }
 8300:     my $changed;
 8301:     if ($newuser) {
 8302:         $changed = 1;
 8303:     } else {
 8304:         foreach my $field (@fields) {
 8305:             if ($names{$field} ne $oldnames{$field}) {
 8306:                 $changed = 1;
 8307:                 last;
 8308:             }
 8309:         }
 8310:     }
 8311:     unless ($changed) {
 8312:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8313:         &logthis($logmsg);
 8314:         return 'ok';
 8315:     }
 8316:     my $reply = &put('environment', \%names, $udom,$uname);
 8317:     if ($reply ne 'ok') { 
 8318:         return 'error: '.$reply;
 8319:     }
 8320:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8321:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8322:     }
 8323:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8324:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8325:     $logmsg = 'Success modifying user '.$logmsg;
 8326:     &logthis($logmsg);
 8327:     return 'ok';
 8328: }
 8329: 
 8330: # -------------------------------------------------------------- Modify student
 8331: 
 8332: sub modifystudent {
 8333:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8334:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8335:         $selfenroll,$context,$inststatus)=@_;
 8336:     if (!$cid) {
 8337: 	unless ($cid=$env{'request.course.id'}) {
 8338: 	    return 'not_in_class';
 8339: 	}
 8340:     }
 8341: # --------------------------------------------------------------- Make the user
 8342:     my $reply=&modifyuser
 8343: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8344:          $desiredhome,$email,$inststatus);
 8345:     unless ($reply eq 'ok') { return $reply; }
 8346:     # This will cause &modify_student_enrollment to get the uid from the
 8347:     # students environment
 8348:     $uid = undef if (!$forceid);
 8349:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8350: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8351:     return $reply;
 8352: }
 8353: 
 8354: sub modify_student_enrollment {
 8355:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8356:     my ($cdom,$cnum,$chome);
 8357:     if (!$cid) {
 8358: 	unless ($cid=$env{'request.course.id'}) {
 8359: 	    return 'not_in_class';
 8360: 	}
 8361: 	$cdom=$env{'course.'.$cid.'.domain'};
 8362: 	$cnum=$env{'course.'.$cid.'.num'};
 8363:     } else {
 8364: 	($cdom,$cnum)=split(/_/,$cid);
 8365:     }
 8366:     $chome=$env{'course.'.$cid.'.home'};
 8367:     if (!$chome) {
 8368: 	$chome=&homeserver($cnum,$cdom);
 8369:     }
 8370:     if (!$chome) { return 'unknown_course'; }
 8371:     # Make sure the user exists
 8372:     my $uhome=&homeserver($uname,$udom);
 8373:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8374: 	return 'error: no such user';
 8375:     }
 8376:     # Get student data if we were not given enough information
 8377:     if (!defined($first)  || $first  eq '' || 
 8378:         !defined($last)   || $last   eq '' || 
 8379:         !defined($uid)    || $uid    eq '' || 
 8380:         !defined($middle) || $middle eq '' || 
 8381:         !defined($gene)   || $gene   eq '') {
 8382:         # They did not supply us with enough data to enroll the student, so
 8383:         # we need to pick up more information.
 8384:         my %tmp = &get('environment',
 8385:                        ['firstname','middlename','lastname', 'generation','id']
 8386:                        ,$udom,$uname);
 8387: 
 8388:         #foreach my $key (keys(%tmp)) {
 8389:         #    &logthis("key $key = ".$tmp{$key});
 8390:         #}
 8391:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8392:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8393:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8394:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8395:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8396:     }
 8397:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8398:     my $user = "$uname:$udom";
 8399:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8400:     my $reply=cput('classlist',
 8401: 		   {$user => 
 8402: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8403: 		   $cdom,$cnum);
 8404:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8405:         &devalidate_getsection_cache($udom,$uname,$cid);
 8406:     } else { 
 8407: 	return 'error: '.$reply;
 8408:     }
 8409:     # Add student role to user
 8410:     my $uurl='/'.$cid;
 8411:     $uurl=~s/\_/\//g;
 8412:     if ($usec) {
 8413: 	$uurl.='/'.$usec;
 8414:     }
 8415:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8416:                              $selfenroll,$context);
 8417:     if ($result ne 'ok') {
 8418:         if ($old_entry{$user} ne '') {
 8419:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8420:         } else {
 8421:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8422:         }
 8423:     }
 8424:     return $result; 
 8425: }
 8426: 
 8427: sub format_name {
 8428:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8429:     my $name;
 8430:     if ($first ne 'lastname') {
 8431: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8432:     } else {
 8433: 	if ($lastname=~/\S/) {
 8434: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8435: 	    $name=~s/\s+,/,/;
 8436: 	} else {
 8437: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8438: 	}
 8439:     }
 8440:     $name=~s/^\s+//;
 8441:     $name=~s/\s+$//;
 8442:     $name=~s/\s+/ /g;
 8443:     return $name;
 8444: }
 8445: 
 8446: # ------------------------------------------------- Write to course preferences
 8447: 
 8448: sub writecoursepref {
 8449:     my ($courseid,%prefs)=@_;
 8450:     $courseid=~s/^\///;
 8451:     $courseid=~s/\_/\//g;
 8452:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8453:     my $chome=homeserver($cnum,$cdomain);
 8454:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8455: 	return 'error: no such course';
 8456:     }
 8457:     my $cstring='';
 8458:     foreach my $pref (keys(%prefs)) {
 8459: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8460:     }
 8461:     $cstring=~s/\&$//;
 8462:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8463: }
 8464: 
 8465: # ---------------------------------------------------------- Make/modify course
 8466: 
 8467: sub createcourse {
 8468:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8469:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8470:     $url=&declutter($url);
 8471:     my $cid='';
 8472:     if ($context eq 'requestcourses') {
 8473:         my $can_create = 0;
 8474:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8475:         if ($udom eq $ownerdom) {
 8476:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8477:                                   $context)) {
 8478:                 $can_create = 1;
 8479:             }
 8480:         } else {
 8481:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8482:                                            $category);
 8483:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8484:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8485:                 if (@curr > 0) {
 8486:                     my @options = qw(approval validate autolimit);
 8487:                     my $optregex = join('|',@options);
 8488:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8489:                         $can_create = 1;
 8490:                     }
 8491:                 }
 8492:             }
 8493:         }
 8494:         if ($can_create) {
 8495:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8496:                 unless (&allowed('ccc',$udom)) {
 8497:                     return 'refused'; 
 8498:                 }
 8499:             }
 8500:         } else {
 8501:             return 'refused';
 8502:         }
 8503:     } elsif (!&allowed('ccc',$udom)) {
 8504:         return 'refused';
 8505:     }
 8506: # --------------------------------------------------------------- Get Unique ID
 8507:     my $uname;
 8508:     if ($cnum =~ /^$match_courseid$/) {
 8509:         my $chome=&homeserver($cnum,$udom,'true');
 8510:         if (($chome eq '') || ($chome eq 'no_host')) {
 8511:             $uname = $cnum;
 8512:         } else {
 8513:             $uname = &generate_coursenum($udom,$crstype);
 8514:         }
 8515:     } else {
 8516:         $uname = &generate_coursenum($udom,$crstype);
 8517:     }
 8518:     return $uname if ($uname =~ /^error/);
 8519: # -------------------------------------------------- Check supplied server name
 8520:     if (!defined($course_server)) {
 8521:         if (defined(&domain($udom,'primary'))) {
 8522:             $course_server = &domain($udom,'primary');
 8523:         } else {
 8524:             $course_server = $env{'user.home'}; 
 8525:         }
 8526:     }
 8527:     my %host_servers =
 8528:         &Apache::lonnet::get_servers($udom,'library');
 8529:     unless ($host_servers{$course_server}) {
 8530:         return 'error: invalid home server for course: '.$course_server;
 8531:     }
 8532: # ------------------------------------------------------------- Make the course
 8533:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8534:                       $course_server);
 8535:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8536:     my $uhome=&homeserver($uname,$udom,'true');
 8537:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8538: 	return 'error: no such course';
 8539:     }
 8540: # ----------------------------------------------------------------- Course made
 8541: # log existence
 8542:     my $now = time;
 8543:     my $newcourse = {
 8544:                     $udom.'_'.$uname => {
 8545:                                      description => $description,
 8546:                                      inst_code   => $inst_code,
 8547:                                      owner       => $course_owner,
 8548:                                      type        => $crstype,
 8549:                                      creator     => $env{'user.name'}.':'.
 8550:                                                     $env{'user.domain'},
 8551:                                      created     => $now,
 8552:                                      context     => $context,
 8553:                                                 },
 8554:                     };
 8555:     &courseidput($udom,$newcourse,$uhome,'notime');
 8556: # set toplevel url
 8557:     my $topurl=$url;
 8558:     unless ($nonstandard) {
 8559: # ------------------------------------------ For standard courses, make top url
 8560:         my $mapurl=&clutter($url);
 8561:         if ($mapurl eq '/res/') { $mapurl=''; }
 8562:         $env{'form.initmap'}=(<<ENDINITMAP);
 8563: <map>
 8564: <resource id="1" type="start"></resource>
 8565: <resource id="2" src="$mapurl"></resource>
 8566: <resource id="3" type="finish"></resource>
 8567: <link index="1" from="1" to="2"></link>
 8568: <link index="2" from="2" to="3"></link>
 8569: </map>
 8570: ENDINITMAP
 8571:         $topurl=&declutter(
 8572:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8573:                           );
 8574:     }
 8575: # ----------------------------------------------------------- Write preferences
 8576:     &writecoursepref($udom.'_'.$uname,
 8577:                      ('description'              => $description,
 8578:                       'url'                      => $topurl,
 8579:                       'internal.creator'         => $env{'user.name'}.':'.
 8580:                                                     $env{'user.domain'},
 8581:                       'internal.created'         => $now,
 8582:                       'internal.creationcontext' => $context)
 8583:                     );
 8584:     return '/'.$udom.'/'.$uname;
 8585: }
 8586: 
 8587: # ------------------------------------------------------------------- Create ID
 8588: sub generate_coursenum {
 8589:     my ($udom,$crstype) = @_;
 8590:     my $domdesc = &domain($udom);
 8591:     return 'error: invalid domain' if ($domdesc eq '');
 8592:     my $first;
 8593:     if ($crstype eq 'Community') {
 8594:         $first = '0';
 8595:     } else {
 8596:         $first = int(1+rand(9)); 
 8597:     } 
 8598:     my $uname=$first.
 8599:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8600:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8601:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8602: # ----------------------------------------------- Make sure that does not exist
 8603:     my $uhome=&homeserver($uname,$udom,'true');
 8604:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8605:         if ($crstype eq 'Community') {
 8606:             $first = '0';
 8607:         } else {
 8608:             $first = int(1+rand(9));
 8609:         }
 8610:         $uname=$first.
 8611:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8612:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8613:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8614:         $uhome=&homeserver($uname,$udom,'true');
 8615:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8616:             return 'error: unable to generate unique course-ID';
 8617:         }
 8618:     }
 8619:     return $uname;
 8620: }
 8621: 
 8622: sub is_course {
 8623:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8624:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8625: 
 8626:     return unless $cdom and $cnum;
 8627: 
 8628:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8629:         '.');
 8630: 
 8631:     return unless exists($courses{$cdom.'_'.$cnum});
 8632:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8633: }
 8634: 
 8635: sub store_userdata {
 8636:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8637:     my $result;
 8638:     if ($datakey ne '') {
 8639:         if (ref($storehash) eq 'HASH') {
 8640:             if ($udom eq '' || $uname eq '') {
 8641:                 $udom = $env{'user.domain'};
 8642:                 $uname = $env{'user.name'};
 8643:             }
 8644:             my $uhome=&homeserver($uname,$udom);
 8645:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8646:                 $result = 'error: no_host';
 8647:             } else {
 8648:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8649:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8650: 
 8651:                 my $namevalue='';
 8652:                 foreach my $key (keys(%{$storehash})) {
 8653:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8654:                 }
 8655:                 $namevalue=~s/\&$//;
 8656:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8657:                                   $namevalue,$uhome);
 8658:             }
 8659:         } else {
 8660:             $result = 'error: data to store was not a hash reference'; 
 8661:         }
 8662:     } else {
 8663:         $result= 'error: invalid requestkey'; 
 8664:     }
 8665:     return $result;
 8666: }
 8667: 
 8668: # ---------------------------------------------------------- Assign Custom Role
 8669: 
 8670: sub assigncustomrole {
 8671:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8672:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8673:                        $end,$start,$deleteflag,$selfenroll,$context);
 8674: }
 8675: 
 8676: # ----------------------------------------------------------------- Revoke Role
 8677: 
 8678: sub revokerole {
 8679:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8680:     my $now=time;
 8681:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8682: }
 8683: 
 8684: # ---------------------------------------------------------- Revoke Custom Role
 8685: 
 8686: sub revokecustomrole {
 8687:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8688:     my $now=time;
 8689:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8690:            $deleteflag,$selfenroll,$context);
 8691: }
 8692: 
 8693: # ------------------------------------------------------------ Disk usage
 8694: sub diskusage {
 8695:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8696:     $directorypath =~ s/\/$//;
 8697:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8698:                        .&escape($getpropath).':'.&escape($uname).':'
 8699:                        .&escape($udom),homeserver($uname,$udom));
 8700:     if ($listing eq 'unknown_cmd') {
 8701:         if ($getpropath) {
 8702:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8703:         }
 8704:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8705:     }
 8706:     return $listing;
 8707: }
 8708: 
 8709: sub is_locked {
 8710:     my ($file_name, $domain, $user, $which) = @_;
 8711:     my @check;
 8712:     my $is_locked;
 8713:     push (@check,$file_name);
 8714:     my %locked = &get('file_permissions',\@check,
 8715: 		      $env{'user.domain'},$env{'user.name'});
 8716:     my ($tmp)=keys(%locked);
 8717:     if ($tmp=~/^error:/) { undef(%locked); }
 8718:     
 8719:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8720:         $is_locked = 'false';
 8721:         foreach my $entry (@{$locked{$file_name}}) {
 8722:            if (ref($entry) eq 'ARRAY') {
 8723:                $is_locked = 'true';
 8724:                if (ref($which) eq 'ARRAY') {
 8725:                    push(@{$which},$entry);
 8726:                } else {
 8727:                    last;
 8728:                }
 8729:            }
 8730:        }
 8731:     } else {
 8732:         $is_locked = 'false';
 8733:     }
 8734:     return $is_locked;
 8735: }
 8736: 
 8737: sub declutter_portfile {
 8738:     my ($file) = @_;
 8739:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8740:     return $file;
 8741: }
 8742: 
 8743: # ------------------------------------------------------------- Mark as Read Only
 8744: 
 8745: sub mark_as_readonly {
 8746:     my ($domain,$user,$files,$what) = @_;
 8747:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8748:     my ($tmp)=keys(%current_permissions);
 8749:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8750:     foreach my $file (@{$files}) {
 8751: 	$file = &declutter_portfile($file);
 8752:         push(@{$current_permissions{$file}},$what);
 8753:     }
 8754:     &put('file_permissions',\%current_permissions,$domain,$user);
 8755:     return;
 8756: }
 8757: 
 8758: # ------------------------------------------------------------Save Selected Files
 8759: 
 8760: sub save_selected_files {
 8761:     my ($user, $path, @files) = @_;
 8762:     my $filename = $user."savedfiles";
 8763:     my @other_files = &files_not_in_path($user, $path);
 8764:     open (OUT, '>'.$tmpdir.$filename);
 8765:     foreach my $file (@files) {
 8766:         print (OUT $env{'form.currentpath'}.$file."\n");
 8767:     }
 8768:     foreach my $file (@other_files) {
 8769:         print (OUT $file."\n");
 8770:     }
 8771:     close (OUT);
 8772:     return 'ok';
 8773: }
 8774: 
 8775: sub clear_selected_files {
 8776:     my ($user) = @_;
 8777:     my $filename = $user."savedfiles";
 8778:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8779:     print (OUT undef);
 8780:     close (OUT);
 8781:     return ("ok");    
 8782: }
 8783: 
 8784: sub files_in_path {
 8785:     my ($user, $path) = @_;
 8786:     my $filename = $user."savedfiles";
 8787:     my %return_files;
 8788:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8789:     while (my $line_in = <IN>) {
 8790:         chomp ($line_in);
 8791:         my @paths_and_file = split (m!/!, $line_in);
 8792:         my $file_part = pop (@paths_and_file);
 8793:         my $path_part = join ('/', @paths_and_file);
 8794:         $path_part.='/';
 8795:         my $path_and_file = $path_part.$file_part;
 8796:         if ($path_part eq $path) {
 8797:             $return_files{$file_part}= 'selected';
 8798:         }
 8799:     }
 8800:     close (IN);
 8801:     return (\%return_files);
 8802: }
 8803: 
 8804: # called in portfolio select mode, to show files selected NOT in current directory
 8805: sub files_not_in_path {
 8806:     my ($user, $path) = @_;
 8807:     my $filename = $user."savedfiles";
 8808:     my @return_files;
 8809:     my $path_part;
 8810:     open(IN, '<'.LONCAPA::.$filename);
 8811:     while (my $line = <IN>) {
 8812:         #ok, I know it's clunky, but I want it to work
 8813:         my @paths_and_file = split(m|/|, $line);
 8814:         my $file_part = pop(@paths_and_file);
 8815:         chomp($file_part);
 8816:         my $path_part = join('/', @paths_and_file);
 8817:         $path_part .= '/';
 8818:         my $path_and_file = $path_part.$file_part;
 8819:         if ($path_part ne $path) {
 8820:             push(@return_files, ($path_and_file));
 8821:         }
 8822:     }
 8823:     close(OUT);
 8824:     return (@return_files);
 8825: }
 8826: 
 8827: #----------------------------------------------Get portfolio file permissions
 8828: 
 8829: sub get_portfile_permissions {
 8830:     my ($domain,$user) = @_;
 8831:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8832:     my ($tmp)=keys(%current_permissions);
 8833:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8834:     return \%current_permissions;
 8835: }
 8836: 
 8837: #---------------------------------------------Get portfolio file access controls
 8838: 
 8839: sub get_access_controls {
 8840:     my ($current_permissions,$group,$file) = @_;
 8841:     my %access;
 8842:     my $real_file = $file;
 8843:     $file =~ s/\.meta$//;
 8844:     if (defined($file)) {
 8845:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8846:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8847:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8848:             }
 8849:         }
 8850:     } else {
 8851:         foreach my $key (keys(%{$current_permissions})) {
 8852:             if ($key =~ /\0accesscontrol$/) {
 8853:                 if (defined($group)) {
 8854:                     if ($key !~ m-^\Q$group\E/-) {
 8855:                         next;
 8856:                     }
 8857:                 }
 8858:                 my ($fullpath) = split(/\0/,$key);
 8859:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8860:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8861:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8862:                     }
 8863:                 }
 8864:             }
 8865:         }
 8866:     }
 8867:     return %access;
 8868: }
 8869: 
 8870: sub modify_access_controls {
 8871:     my ($file_name,$changes,$domain,$user)=@_;
 8872:     my ($outcome,$deloutcome);
 8873:     my %store_permissions;
 8874:     my %new_values;
 8875:     my %new_control;
 8876:     my %translation;
 8877:     my @deletions = ();
 8878:     my $now = time;
 8879:     if (exists($$changes{'activate'})) {
 8880:         if (ref($$changes{'activate'}) eq 'HASH') {
 8881:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8882:             my $numnew = scalar(@newitems);
 8883:             for (my $i=0; $i<$numnew; $i++) {
 8884:                 my $newkey = $newitems[$i];
 8885:                 my $newid = &Apache::loncommon::get_cgi_id();
 8886:                 if ($newkey =~ /^\d+:/) { 
 8887:                     $newkey =~ s/^(\d+)/$newid/;
 8888:                     $translation{$1} = $newid;
 8889:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8890:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8891:                     $translation{$1} = $newid;
 8892:                 }
 8893:                 $new_values{$file_name."\0".$newkey} = 
 8894:                                           $$changes{'activate'}{$newitems[$i]};
 8895:                 $new_control{$newkey} = $now;
 8896:             }
 8897:         }
 8898:     }
 8899:     my %todelete;
 8900:     my %changed_items;
 8901:     foreach my $action ('delete','update') {
 8902:         if (exists($$changes{$action})) {
 8903:             if (ref($$changes{$action}) eq 'HASH') {
 8904:                 foreach my $key (keys(%{$$changes{$action}})) {
 8905:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8906:                     if ($action eq 'delete') { 
 8907:                         $todelete{$itemnum} = 1;
 8908:                     } else {
 8909:                         $changed_items{$itemnum} = $key;
 8910:                     }
 8911:                 }
 8912:             }
 8913:         }
 8914:     }
 8915:     # get lock on access controls for file.
 8916:     my $lockhash = {
 8917:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8918:                                                        ':'.$env{'user.domain'},
 8919:                    }; 
 8920:     my $tries = 0;
 8921:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8922:    
 8923:     while (($gotlock ne 'ok') && $tries <3) {
 8924:         $tries ++;
 8925:         sleep 1;
 8926:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8927:     }
 8928:     if ($gotlock eq 'ok') {
 8929:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8930:         my ($tmp)=keys(%curr_permissions);
 8931:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8932:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8933:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8934:             if (ref($curr_controls) eq 'HASH') {
 8935:                 foreach my $control_item (keys(%{$curr_controls})) {
 8936:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8937:                     if (defined($todelete{$itemnum})) {
 8938:                         push(@deletions,$file_name."\0".$control_item);
 8939:                     } else {
 8940:                         if (defined($changed_items{$itemnum})) {
 8941:                             $new_control{$changed_items{$itemnum}} = $now;
 8942:                             push(@deletions,$file_name."\0".$control_item);
 8943:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8944:                         } else {
 8945:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8946:                         }
 8947:                     }
 8948:                 }
 8949:             }
 8950:         }
 8951:         my ($group);
 8952:         if (&is_course($domain,$user)) {
 8953:             ($group,my $file) = split(/\//,$file_name,2);
 8954:         }
 8955:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8956:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8957:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8958:         #  remove lock
 8959:         my @del_lock = ($file_name."\0".'locked_access_records');
 8960:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8961:         my $sqlresult =
 8962:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8963:                                     $group);
 8964:     } else {
 8965:         $outcome = "error: could not obtain lockfile\n";  
 8966:     }
 8967:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8968: }
 8969: 
 8970: sub make_public_indefinitely {
 8971:     my ($requrl) = @_;
 8972:     my $now = time;
 8973:     my $action = 'activate';
 8974:     my $aclnum = 0;
 8975:     if (&is_portfolio_url($requrl)) {
 8976:         my (undef,$udom,$unum,$file_name,$group) =
 8977:             &parse_portfolio_url($requrl);
 8978:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8979:         my %access_controls = &get_access_controls($current_perms,
 8980:                                                    $group,$file_name);
 8981:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8982:             my ($num,$scope,$end,$start) = 
 8983:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8984:             if ($scope eq 'public') {
 8985:                 if ($start <= $now && $end == 0) {
 8986:                     $action = 'none';
 8987:                 } else {
 8988:                     $action = 'update';
 8989:                     $aclnum = $num;
 8990:                 }
 8991:                 last;
 8992:             }
 8993:         }
 8994:         if ($action eq 'none') {
 8995:              return 'ok';
 8996:         } else {
 8997:             my %changes;
 8998:             my $newend = 0;
 8999:             my $newstart = $now;
 9000:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9001:             $changes{$action}{$newkey} = {
 9002:                 type => 'public',
 9003:                 time => {
 9004:                     start => $newstart,
 9005:                     end   => $newend,
 9006:                 },
 9007:             };
 9008:             my ($outcome,$deloutcome,$new_values,$translation) =
 9009:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9010:             return $outcome;
 9011:         }
 9012:     } else {
 9013:         return 'invalid';
 9014:     }
 9015: }
 9016: 
 9017: #------------------------------------------------------Get Marked as Read Only
 9018: 
 9019: sub get_marked_as_readonly {
 9020:     my ($domain,$user,$what,$group) = @_;
 9021:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9022:     my @readonly_files;
 9023:     my $cmp1=$what;
 9024:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9025:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9026:         if (defined($group)) {
 9027:             if ($file_name !~ m-^\Q$group\E/-) {
 9028:                 next;
 9029:             }
 9030:         }
 9031:         if (ref($value) eq "ARRAY"){
 9032:             foreach my $stored_what (@{$value}) {
 9033:                 my $cmp2=$stored_what;
 9034:                 if (ref($stored_what) eq 'ARRAY') {
 9035:                     $cmp2=join('',@{$stored_what});
 9036:                 }
 9037:                 if ($cmp1 eq $cmp2) {
 9038:                     push(@readonly_files, $file_name);
 9039:                     last;
 9040:                 } elsif (!defined($what)) {
 9041:                     push(@readonly_files, $file_name);
 9042:                     last;
 9043:                 }
 9044:             }
 9045:         }
 9046:     }
 9047:     return @readonly_files;
 9048: }
 9049: #-----------------------------------------------------------Get Marked as Read Only Hash
 9050: 
 9051: sub get_marked_as_readonly_hash {
 9052:     my ($current_permissions,$group,$what) = @_;
 9053:     my %readonly_files;
 9054:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9055:         if (defined($group)) {
 9056:             if ($file_name !~ m-^\Q$group\E/-) {
 9057:                 next;
 9058:             }
 9059:         }
 9060:         if (ref($value) eq "ARRAY"){
 9061:             foreach my $stored_what (@{$value}) {
 9062:                 if (ref($stored_what) eq 'ARRAY') {
 9063:                     foreach my $lock_descriptor(@{$stored_what}) {
 9064:                         if ($lock_descriptor eq 'graded') {
 9065:                             $readonly_files{$file_name} = 'graded';
 9066:                         } elsif ($lock_descriptor eq 'handback') {
 9067:                             $readonly_files{$file_name} = 'handback';
 9068:                         } else {
 9069:                             if (!exists($readonly_files{$file_name})) {
 9070:                                 $readonly_files{$file_name} = 'locked';
 9071:                             }
 9072:                         }
 9073:                     }
 9074:                 } 
 9075:             }
 9076:         } 
 9077:     }
 9078:     return %readonly_files;
 9079: }
 9080: # ------------------------------------------------------------ Unmark as Read Only
 9081: 
 9082: sub unmark_as_readonly {
 9083:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9084:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9085:     my ($domain,$user,$what,$file_name,$group) = @_;
 9086:     $file_name = &declutter_portfile($file_name);
 9087:     my $symb_crs = $what;
 9088:     if (ref($what)) { $symb_crs=join('',@$what); }
 9089:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9090:     my ($tmp)=keys(%current_permissions);
 9091:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9092:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9093:     foreach my $file (@readonly_files) {
 9094: 	my $clean_file = &declutter_portfile($file);
 9095: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9096: 	my $current_locks = $current_permissions{$file};
 9097:         my @new_locks;
 9098:         my @del_keys;
 9099:         if (ref($current_locks) eq "ARRAY"){
 9100:             foreach my $locker (@{$current_locks}) {
 9101:                 my $compare=$locker;
 9102:                 if (ref($locker) eq 'ARRAY') {
 9103:                     $compare=join('',@{$locker});
 9104:                     if ($compare ne $symb_crs) {
 9105:                         push(@new_locks, $locker);
 9106:                     }
 9107:                 }
 9108:             }
 9109:             if (scalar(@new_locks) > 0) {
 9110:                 $current_permissions{$file} = \@new_locks;
 9111:             } else {
 9112:                 push(@del_keys, $file);
 9113:                 &del('file_permissions',\@del_keys, $domain, $user);
 9114:                 delete($current_permissions{$file});
 9115:             }
 9116:         }
 9117:     }
 9118:     &put('file_permissions',\%current_permissions,$domain,$user);
 9119:     return;
 9120: }
 9121: 
 9122: # ------------------------------------------------------------ Directory lister
 9123: 
 9124: sub dirlist {
 9125:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9126:     $uri=~s/^\///;
 9127:     $uri=~s/\/$//;
 9128:     my ($udom, $uname);
 9129:     if ($getuserdir) {
 9130:         $udom = $userdomain;
 9131:         $uname = $username;
 9132:     } else {
 9133:         (undef,$udom,$uname)=split(/\//,$uri);
 9134:         if(defined($userdomain)) {
 9135:             $udom = $userdomain;
 9136:         }
 9137:         if(defined($username)) {
 9138:             $uname = $username;
 9139:         }
 9140:     }
 9141:     my ($dirRoot,$listing,@listing_results);
 9142: 
 9143:     $dirRoot = $perlvar{'lonDocRoot'};
 9144:     if (defined($getpropath)) {
 9145:         $dirRoot = &propath($udom,$uname);
 9146:         $dirRoot =~ s/\/$//;
 9147:     } elsif (defined($getuserdir)) {
 9148:         my $subdir=$uname.'__';
 9149:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9150:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9151:                    ."/$udom/$subdir/$uname";
 9152:     } elsif (defined($alternateRoot)) {
 9153:         $dirRoot = $alternateRoot;
 9154:     }
 9155: 
 9156:     if($udom) {
 9157:         if($uname) {
 9158:             my $uhome = &homeserver($uname,$udom);
 9159:             if ($uhome eq 'no_host') {
 9160:                 return ([],'no_host');
 9161:             }
 9162:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9163:                               .$getuserdir.':'.&escape($dirRoot)
 9164:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9165:             if ($listing eq 'unknown_cmd') {
 9166:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9167:             } else {
 9168:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9169:             }
 9170:             if ($listing eq 'unknown_cmd') {
 9171:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9172:                 @listing_results = split(/:/,$listing);
 9173:             } else {
 9174:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9175:             }
 9176:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9177:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9178:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9179:                 return ([],$listing);
 9180:             } else {
 9181:                 return (\@listing_results);
 9182:             }
 9183:         } elsif(!$alternateRoot) {
 9184:             my (%allusers,%listerror);
 9185: 	    my %servers = &get_servers($udom,'library');
 9186:  	    foreach my $tryserver (keys(%servers)) {
 9187:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9188:                                   &escape($udom),$tryserver);
 9189:                 if ($listing eq 'unknown_cmd') {
 9190: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9191: 				      $udom, $tryserver);
 9192:                 } else {
 9193:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9194:                 }
 9195: 		if ($listing eq 'unknown_cmd') {
 9196: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9197: 				      $udom, $tryserver);
 9198: 		    @listing_results = split(/:/,$listing);
 9199: 		} else {
 9200: 		    @listing_results =
 9201: 			map { &unescape($_); } split(/:/,$listing);
 9202: 		}
 9203:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9204:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9205:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9206:                     $listerror{$tryserver} = $listing;
 9207:                 } else {
 9208: 		    foreach my $line (@listing_results) {
 9209: 			my ($entry) = split(/&/,$line,2);
 9210: 			$allusers{$entry} = 1;
 9211: 		    }
 9212: 		}
 9213:             }
 9214:             my @alluserslist=();
 9215:             foreach my $user (sort(keys(%allusers))) {
 9216:                 push(@alluserslist,$user.'&user');
 9217:             }
 9218:             return (\@alluserslist);
 9219:         } else {
 9220:             return ([],'missing username');
 9221:         }
 9222:     } elsif(!defined($getpropath)) {
 9223:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9224:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9225:         return (\@all_domains);
 9226:     } else {
 9227:         return ([],'missing domain');
 9228:     }
 9229: }
 9230: 
 9231: # --------------------------------------------- GetFileTimestamp
 9232: # This function utilizes dirlist and returns the date stamp for
 9233: # when it was last modified.  It will also return an error of -1
 9234: # if an error occurs
 9235: 
 9236: sub GetFileTimestamp {
 9237:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9238:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9239:     $studentName   = &LONCAPA::clean_username($studentName);
 9240:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9241:                                     undef,$getuserdir);
 9242:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9243:         return -1;
 9244:     }
 9245:     if (ref($fileref) eq 'ARRAY') {
 9246:         my @stats = split('&',$fileref->[0]);
 9247:         # @stats contains first the filename, then the stat output
 9248:         return $stats[10]; # so this is 10 instead of 9.
 9249:     } else {
 9250:         return -1;
 9251:     }
 9252: }
 9253: 
 9254: sub stat_file {
 9255:     my ($uri) = @_;
 9256:     $uri = &clutter_with_no_wrapper($uri);
 9257: 
 9258:     my ($udom,$uname,$file);
 9259:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9260: 	($udom,$uname,$file) =
 9261: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9262: 	$file = 'userfiles/'.$file;
 9263:     }
 9264:     if ($uri =~ m-^/res/-) {
 9265: 	($udom,$uname) = 
 9266: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9267: 	$file = $uri;
 9268:     }
 9269: 
 9270:     if (!$udom || !$uname || !$file) {
 9271: 	# unable to handle the uri
 9272: 	return ();
 9273:     }
 9274:     my $getpropath;
 9275:     if ($file =~ /^userfiles\//) {
 9276:         $getpropath = 1;
 9277:     }
 9278:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9279:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9280:         return ();
 9281:     } else {
 9282:         if (ref($listref) eq 'ARRAY') {
 9283:             my @stats = split('&',$listref->[0]);
 9284: 	    shift(@stats); #filename is first
 9285: 	    return @stats;
 9286:         }
 9287:     }
 9288:     return ();
 9289: }
 9290: 
 9291: # -------------------------------------------------------- Value of a Condition
 9292: 
 9293: # gets the value of a specific preevaluated condition
 9294: #    stored in the string  $env{user.state.<cid>}
 9295: # or looks up a condition reference in the bighash and if if hasn't
 9296: # already been evaluated recurses into docondval to get the value of
 9297: # the condition, then memoizing it to 
 9298: #   $env{user.state.<cid>.<condition>}
 9299: sub directcondval {
 9300:     my $number=shift;
 9301:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9302: 	&Apache::lonuserstate::evalstate();
 9303:     }
 9304:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9305: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9306:     } elsif ($number =~ /^_/) {
 9307: 	my $sub_condition;
 9308: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9309: 		&GDBM_READER(),0640)) {
 9310: 	    $sub_condition=$bighash{'conditions'.$number};
 9311: 	    untie(%bighash);
 9312: 	}
 9313: 	my $value = &docondval($sub_condition);
 9314: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9315: 	return $value;
 9316:     }
 9317:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9318:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9319:     } else {
 9320:        return 2;
 9321:     }
 9322: }
 9323: 
 9324: # get the collection of conditions for this resource
 9325: sub condval {
 9326:     my $condidx=shift;
 9327:     my $allpathcond='';
 9328:     foreach my $cond (split(/\|/,$condidx)) {
 9329: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9330: 	    $allpathcond.=
 9331: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9332: 	}
 9333:     }
 9334:     $allpathcond=~s/\|$//;
 9335:     return &docondval($allpathcond);
 9336: }
 9337: 
 9338: #evaluates an expression of conditions
 9339: sub docondval {
 9340:     my ($allpathcond) = @_;
 9341:     my $result=0;
 9342:     if ($env{'request.course.id'}
 9343: 	&& defined($allpathcond)) {
 9344: 	my $operand='|';
 9345: 	my @stack;
 9346: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9347: 	    if ($chunk eq '(') {
 9348: 		push @stack,($operand,$result);
 9349: 	    } elsif ($chunk eq ')') {
 9350: 		my $before=pop @stack;
 9351: 		if (pop @stack eq '&') {
 9352: 		    $result=$result>$before?$before:$result;
 9353: 		} else {
 9354: 		    $result=$result>$before?$result:$before;
 9355: 		}
 9356: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9357: 		$operand=$chunk;
 9358: 	    } else {
 9359: 		my $new=directcondval($chunk);
 9360: 		if ($operand eq '&') {
 9361: 		    $result=$result>$new?$new:$result;
 9362: 		} else {
 9363: 		    $result=$result>$new?$result:$new;
 9364: 		}
 9365: 	    }
 9366: 	}
 9367:     }
 9368:     return $result;
 9369: }
 9370: 
 9371: # ---------------------------------------------------- Devalidate courseresdata
 9372: 
 9373: sub devalidatecourseresdata {
 9374:     my ($coursenum,$coursedomain)=@_;
 9375:     my $hashid=$coursenum.':'.$coursedomain;
 9376:     &devalidate_cache_new('courseres',$hashid);
 9377: }
 9378: 
 9379: 
 9380: # --------------------------------------------------- Course Resourcedata Query
 9381: #
 9382: #  Parameters:
 9383: #      $coursenum    - Number of the course.
 9384: #      $coursedomain - Domain at which the course was created.
 9385: #  Returns:
 9386: #     A hash of the course parameters along (I think) with timestamps
 9387: #     and version info.
 9388: 
 9389: sub get_courseresdata {
 9390:     my ($coursenum,$coursedomain)=@_;
 9391:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9392:     my $hashid=$coursenum.':'.$coursedomain;
 9393:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9394:     my %dumpreply;
 9395:     unless (defined($cached)) {
 9396: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9397: 	$result=\%dumpreply;
 9398: 	my ($tmp) = keys(%dumpreply);
 9399: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9400: 	    &do_cache_new('courseres',$hashid,$result,600);
 9401: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9402: 	    return $tmp;
 9403: 	} elsif ($tmp =~ /^(error)/) {
 9404: 	    $result=undef;
 9405: 	    &do_cache_new('courseres',$hashid,$result,600);
 9406: 	}
 9407:     }
 9408:     return $result;
 9409: }
 9410: 
 9411: sub devalidateuserresdata {
 9412:     my ($uname,$udom)=@_;
 9413:     my $hashid="$udom:$uname";
 9414:     &devalidate_cache_new('userres',$hashid);
 9415: }
 9416: 
 9417: sub get_userresdata {
 9418:     my ($uname,$udom)=@_;
 9419:     #most student don\'t have any data set, check if there is some data
 9420:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9421: 
 9422:     my $hashid="$udom:$uname";
 9423:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9424:     if (!defined($cached)) {
 9425: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9426: 	$result=\%resourcedata;
 9427: 	&do_cache_new('userres',$hashid,$result,600);
 9428:     }
 9429:     my ($tmp)=keys(%$result);
 9430:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9431: 	return $result;
 9432:     }
 9433:     #error 2 occurs when the .db doesn't exist
 9434:     if ($tmp!~/error: 2 /) {
 9435: 	&logthis("<font color=\"blue\">WARNING:".
 9436: 		 " Trying to get resource data for ".
 9437: 		 $uname." at ".$udom.": ".
 9438: 		 $tmp."</font>");
 9439:     } elsif ($tmp=~/error: 2 /) {
 9440: 	#&EXT_cache_set($udom,$uname);
 9441: 	&do_cache_new('userres',$hashid,undef,600);
 9442: 	undef($tmp); # not really an error so don't send it back
 9443:     }
 9444:     return $tmp;
 9445: }
 9446: #----------------------------------------------- resdata - return resource data
 9447: #  Purpose:
 9448: #    Return resource data for either users or for a course.
 9449: #  Parameters:
 9450: #     $name      - Course/user name.
 9451: #     $domain    - Name of the domain the user/course is registered on.
 9452: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9453: #     @which     - Array of names of resources desired.
 9454: #  Returns:
 9455: #     The value of the first reasource in @which that is found in the
 9456: #     resource hash.
 9457: #  Exceptional Conditions:
 9458: #     If the $type passed in is not valid (not the string 'course' or 
 9459: #     'user', an undefined  reference is returned.
 9460: #     If none of the resources are found, an undef is returned
 9461: sub resdata {
 9462:     my ($name,$domain,$type,@which)=@_;
 9463:     my $result;
 9464:     if ($type eq 'course') {
 9465: 	$result=&get_courseresdata($name,$domain);
 9466:     } elsif ($type eq 'user') {
 9467: 	$result=&get_userresdata($name,$domain);
 9468:     }
 9469:     if (!ref($result)) { return $result; }    
 9470:     foreach my $item (@which) {
 9471: 	if (defined($result->{$item->[0]})) {
 9472: 	    return [$result->{$item->[0]},$item->[1]];
 9473: 	}
 9474:     }
 9475:     return undef;
 9476: }
 9477: 
 9478: #
 9479: # EXT resource caching routines
 9480: #
 9481: 
 9482: sub clear_EXT_cache_status {
 9483:     &delenv('cache.EXT.');
 9484: }
 9485: 
 9486: sub EXT_cache_status {
 9487:     my ($target_domain,$target_user) = @_;
 9488:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9489:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9490:         # We know already the user has no data
 9491:         return 1;
 9492:     } else {
 9493:         return 0;
 9494:     }
 9495: }
 9496: 
 9497: sub EXT_cache_set {
 9498:     my ($target_domain,$target_user) = @_;
 9499:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9500:     #&appenv({$cachename => time});
 9501: }
 9502: 
 9503: # --------------------------------------------------------- Value of a Variable
 9504: sub EXT {
 9505: 
 9506:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9507:     unless ($varname) { return ''; }
 9508:     #get real user name/domain, courseid and symb
 9509:     my $courseid;
 9510:     my $publicuser;
 9511:     if ($symbparm) {
 9512: 	$symbparm=&get_symb_from_alias($symbparm);
 9513:     }
 9514:     if (!($uname && $udom)) {
 9515:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9516:       if (!$symbparm) {	$symbparm=$cursymb; }
 9517:     } else {
 9518: 	$courseid=$env{'request.course.id'};
 9519:     }
 9520:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9521:     my $rest;
 9522:     if (defined($therest[0])) {
 9523:        $rest=join('.',@therest);
 9524:     } else {
 9525:        $rest='';
 9526:     }
 9527: 
 9528:     my $qualifierrest=$qualifier;
 9529:     if ($rest) { $qualifierrest.='.'.$rest; }
 9530:     my $spacequalifierrest=$space;
 9531:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9532:     if ($realm eq 'user') {
 9533: # --------------------------------------------------------------- user.resource
 9534: 	if ($space eq 'resource') {
 9535: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9536: 		  || defined($Apache::lonhomework::parsing_a_task))
 9537: 		 &&
 9538: 		 ($symbparm eq &symbread()) ) {	
 9539: 		# if we are in the middle of processing the resource the
 9540: 		# get the value we are planning on committing
 9541:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9542:                     return $Apache::lonhomework::results{$qualifierrest};
 9543:                 } else {
 9544:                     return $Apache::lonhomework::history{$qualifierrest};
 9545:                 }
 9546: 	    } else {
 9547: 		my %restored;
 9548: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9549: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9550: 		} else {
 9551: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9552: 		}
 9553: 		return $restored{$qualifierrest};
 9554: 	    }
 9555: # ----------------------------------------------------------------- user.access
 9556:         } elsif ($space eq 'access') {
 9557: 	    # FIXME - not supporting calls for a specific user
 9558:             return &allowed($qualifier,$rest);
 9559: # ------------------------------------------ user.preferences, user.environment
 9560:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9561: 	    if (($uname eq $env{'user.name'}) &&
 9562: 		($udom eq $env{'user.domain'})) {
 9563: 		return $env{join('.',('environment',$qualifierrest))};
 9564: 	    } else {
 9565: 		my %returnhash;
 9566: 		if (!$publicuser) {
 9567: 		    %returnhash=&userenvironment($udom,$uname,
 9568: 						 $qualifierrest);
 9569: 		}
 9570: 		return $returnhash{$qualifierrest};
 9571: 	    }
 9572: # ----------------------------------------------------------------- user.course
 9573:         } elsif ($space eq 'course') {
 9574: 	    # FIXME - not supporting calls for a specific user
 9575:             return $env{join('.',('request.course',$qualifier))};
 9576: # ------------------------------------------------------------------- user.role
 9577:         } elsif ($space eq 'role') {
 9578: 	    # FIXME - not supporting calls for a specific user
 9579:             my ($role,$where)=split(/\./,$env{'request.role'});
 9580:             if ($qualifier eq 'value') {
 9581: 		return $role;
 9582:             } elsif ($qualifier eq 'extent') {
 9583:                 return $where;
 9584:             }
 9585: # ----------------------------------------------------------------- user.domain
 9586:         } elsif ($space eq 'domain') {
 9587:             return $udom;
 9588: # ------------------------------------------------------------------- user.name
 9589:         } elsif ($space eq 'name') {
 9590:             return $uname;
 9591: # ---------------------------------------------------- Any other user namespace
 9592:         } else {
 9593: 	    my %reply;
 9594: 	    if (!$publicuser) {
 9595: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9596: 	    }
 9597: 	    return $reply{$qualifierrest};
 9598:         }
 9599:     } elsif ($realm eq 'query') {
 9600: # ---------------------------------------------- pull stuff out of query string
 9601:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9602: 						[$spacequalifierrest]);
 9603: 	return $env{'form.'.$spacequalifierrest}; 
 9604:    } elsif ($realm eq 'request') {
 9605: # ------------------------------------------------------------- request.browser
 9606:         if ($space eq 'browser') {
 9607:             return $env{'browser.'.$qualifier};
 9608: # ------------------------------------------------------------ request.filename
 9609:         } else {
 9610:             return $env{'request.'.$spacequalifierrest};
 9611:         }
 9612:     } elsif ($realm eq 'course') {
 9613: # ---------------------------------------------------------- course.description
 9614:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9615:     } elsif ($realm eq 'resource') {
 9616: 
 9617: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9618: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9619: 	}
 9620: 
 9621: 	if ($space eq 'title') {
 9622: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9623: 	    return &gettitle($symbparm);
 9624: 	}
 9625: 	
 9626: 	if ($space eq 'map') {
 9627: 	    my ($map) = &decode_symb($symbparm);
 9628: 	    return &symbread($map);
 9629: 	}
 9630: 	if ($space eq 'filename') {
 9631: 	    if ($symbparm) {
 9632: 		return &clutter((&decode_symb($symbparm))[2]);
 9633: 	    }
 9634: 	    return &hreflocation('',$env{'request.filename'});
 9635: 	}
 9636: 
 9637: 	my ($section, $group, @groups);
 9638: 	my ($courselevelm,$courselevel);
 9639: 	if ($symbparm && defined($courseid) && 
 9640: 	    $courseid eq $env{'request.course.id'}) {
 9641: 
 9642: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9643: 
 9644: # ----------------------------------------------------- Cascading lookup scheme
 9645: 	    my $symbp=$symbparm;
 9646: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9647: 
 9648: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9649: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9650: 
 9651: 	    if (($env{'user.name'} eq $uname) &&
 9652: 		($env{'user.domain'} eq $udom)) {
 9653: 		$section=$env{'request.course.sec'};
 9654:                 @groups = split(/:/,$env{'request.course.groups'});  
 9655:                 @groups=&sort_course_groups($courseid,@groups); 
 9656: 	    } else {
 9657: 		if (! defined($usection)) {
 9658: 		    $section=&getsection($udom,$uname,$courseid);
 9659: 		} else {
 9660: 		    $section = $usection;
 9661: 		}
 9662:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9663: 	    }
 9664: 
 9665: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9666: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9667: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9668: 
 9669: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9670: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9671: 	    $courselevelm=$courseid.'.'.$mapparm;
 9672: 
 9673: # ----------------------------------------------------------- first, check user
 9674: 
 9675: 	    my $userreply=&resdata($uname,$udom,'user',
 9676: 				       ([$courselevelr,'resource'],
 9677: 					[$courselevelm,'map'     ],
 9678: 					[$courselevel, 'course'  ]));
 9679: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9680: 
 9681: # ------------------------------------------------ second, check some of course
 9682:             my $coursereply;
 9683:             if (@groups > 0) {
 9684:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9685:                                        $mapparm,$spacequalifierrest);
 9686:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9687:             }
 9688: 
 9689: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9690: 				  $env{'course.'.$courseid.'.domain'},
 9691: 				  'course',
 9692: 				  ([$seclevelr,   'resource'],
 9693: 				   [$seclevelm,   'map'     ],
 9694: 				   [$seclevel,    'course'  ],
 9695: 				   [$courselevelr,'resource']));
 9696: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9697: 
 9698: # ------------------------------------------------------ third, check map parms
 9699: 	    my %parmhash=();
 9700: 	    my $thisparm='';
 9701: 	    if (tie(%parmhash,'GDBM_File',
 9702: 		    $env{'request.course.fn'}.'_parms.db',
 9703: 		    &GDBM_READER(),0640)) {
 9704: 		$thisparm=$parmhash{$symbparm};
 9705: 		untie(%parmhash);
 9706: 	    }
 9707: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9708: 	}
 9709: # ------------------------------------------ fourth, look in resource metadata
 9710: 
 9711: 	$spacequalifierrest=~s/\./\_/;
 9712: 	my $filename;
 9713: 	if (!$symbparm) { $symbparm=&symbread(); }
 9714: 	if ($symbparm) {
 9715: 	    $filename=(&decode_symb($symbparm))[2];
 9716: 	} else {
 9717: 	    $filename=$env{'request.filename'};
 9718: 	}
 9719: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9720: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9721: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9722: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9723: 
 9724: # ---------------------------------------------- fourth, look in rest of course
 9725: 	if ($symbparm && defined($courseid) && 
 9726: 	    $courseid eq $env{'request.course.id'}) {
 9727: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9728: 				     $env{'course.'.$courseid.'.domain'},
 9729: 				     'course',
 9730: 				     ([$courselevelm,'map'   ],
 9731: 				      [$courselevel, 'course']));
 9732: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9733: 	}
 9734: # ------------------------------------------------------------------ Cascade up
 9735: 	unless ($space eq '0') {
 9736: 	    my @parts=split(/_/,$space);
 9737: 	    my $id=pop(@parts);
 9738: 	    my $part=join('_',@parts);
 9739: 	    if ($part eq '') { $part='0'; }
 9740: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9741: 				 $symbparm,$udom,$uname,$section,1);
 9742: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9743: 	}
 9744: 	if ($recurse) { return undef; }
 9745: 	my $pack_def=&packages_tab_default($filename,$varname);
 9746: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9747: # ---------------------------------------------------- Any other user namespace
 9748:     } elsif ($realm eq 'environment') {
 9749: # ----------------------------------------------------------------- environment
 9750: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9751: 	    return $env{'environment.'.$spacequalifierrest};
 9752: 	} else {
 9753: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9754: 		return '';
 9755: 	    }
 9756: 	    my %returnhash=&userenvironment($udom,$uname,
 9757: 					    $spacequalifierrest);
 9758: 	    return $returnhash{$spacequalifierrest};
 9759: 	}
 9760:     } elsif ($realm eq 'system') {
 9761: # ----------------------------------------------------------------- system.time
 9762: 	if ($space eq 'time') {
 9763: 	    return time;
 9764:         }
 9765:     } elsif ($realm eq 'server') {
 9766: # ----------------------------------------------------------------- system.time
 9767: 	if ($space eq 'name') {
 9768: 	    return $ENV{'SERVER_NAME'};
 9769:         }
 9770:     }
 9771:     return '';
 9772: }
 9773: 
 9774: sub get_reply {
 9775:     my ($reply_value) = @_;
 9776:     if (ref($reply_value) eq 'ARRAY') {
 9777:         if (wantarray) {
 9778: 	    return @$reply_value;
 9779:         }
 9780:         return $reply_value->[0];
 9781:     } else {
 9782:         return $reply_value;
 9783:     }
 9784: }
 9785: 
 9786: sub check_group_parms {
 9787:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9788:     my @groupitems = ();
 9789:     my $resultitem;
 9790:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9791:     foreach my $group (@{$groups}) {
 9792:         foreach my $level (@levels) {
 9793:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9794:              push(@groupitems,[$item,$level->[1]]);
 9795:         }
 9796:     }
 9797:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9798:                             $env{'course.'.$courseid.'.domain'},
 9799:                                      'course',@groupitems);
 9800:     return $coursereply;
 9801: }
 9802: 
 9803: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9804:     my ($courseid,@groups) = @_;
 9805:     @groups = sort(@groups);
 9806:     return @groups;
 9807: }
 9808: 
 9809: sub packages_tab_default {
 9810:     my ($uri,$varname)=@_;
 9811:     my (undef,$part,$name)=split(/\./,$varname);
 9812: 
 9813:     my (@extension,@specifics,$do_default);
 9814:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9815: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9816: 	if ($pack_type eq 'default') {
 9817: 	    $do_default=1;
 9818: 	} elsif ($pack_type eq 'extension') {
 9819: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9820: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9821: 	    # only look at packages defaults for packages that this id is
 9822: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9823: 	}
 9824:     }
 9825:     # first look for a package that matches the requested part id
 9826:     foreach my $package (@specifics) {
 9827: 	my (undef,$pack_type,$pack_part)=@{$package};
 9828: 	next if ($pack_part ne $part);
 9829: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9830: 	    return $packagetab{"$pack_type&$name&default"};
 9831: 	}
 9832:     }
 9833:     # look for any possible matching non extension_ package
 9834:     foreach my $package (@specifics) {
 9835: 	my (undef,$pack_type,$pack_part)=@{$package};
 9836: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9837: 	    return $packagetab{"$pack_type&$name&default"};
 9838: 	}
 9839: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9840: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9841: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9842: 	}
 9843:     }
 9844:     # look for any posible extension_ match
 9845:     foreach my $package (@extension) {
 9846: 	my ($package,$pack_type)=@{$package};
 9847: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9848: 	    return $packagetab{"$pack_type&$name&default"};
 9849: 	}
 9850: 	if (defined($packagetab{$package."&$name&default"})) {
 9851: 	    return $packagetab{$package."&$name&default"};
 9852: 	}
 9853:     }
 9854:     # look for a global default setting
 9855:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9856: 	return $packagetab{"default&$name&default"};
 9857:     }
 9858:     return undef;
 9859: }
 9860: 
 9861: sub add_prefix_and_part {
 9862:     my ($prefix,$part)=@_;
 9863:     my $keyroot;
 9864:     if (defined($prefix) && $prefix !~ /^__/) {
 9865: 	# prefix that has a part already
 9866: 	$keyroot=$prefix;
 9867:     } elsif (defined($prefix)) {
 9868: 	# prefix that is missing a part
 9869: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9870:     } else {
 9871: 	# no prefix at all
 9872: 	if (defined($part)) { $keyroot='_'.$part; }
 9873:     }
 9874:     return $keyroot;
 9875: }
 9876: 
 9877: # ---------------------------------------------------------------- Get metadata
 9878: 
 9879: my %metaentry;
 9880: my %importedpartids;
 9881: sub metadata {
 9882:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9883:     $uri=&declutter($uri);
 9884:     # if it is a non metadata possible uri return quickly
 9885:     if (($uri eq '') || 
 9886: 	(($uri =~ m|^/*adm/|) && 
 9887: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9888:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9889: 	return undef;
 9890:     }
 9891:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9892: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9893: 	return undef;
 9894:     }
 9895:     my $filename=$uri;
 9896:     $uri=~s/\.meta$//;
 9897: #
 9898: # Is the metadata already cached?
 9899: # Look at timestamp of caching
 9900: # Everything is cached by the main uri, libraries are never directly cached
 9901: #
 9902:     if (!defined($liburi)) {
 9903: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9904: 	if (defined($cached)) { return $result->{':'.$what}; }
 9905:     }
 9906:     {
 9907: # Imported parts would go here
 9908:         my %importedids=();
 9909:         my @origfileimportpartids=();
 9910:         my $importedparts=0;
 9911: #
 9912: # Is this a recursive call for a library?
 9913: #
 9914: #	if (! exists($metacache{$uri})) {
 9915: #	    $metacache{$uri}={};
 9916: #	}
 9917: 	my $cachetime = 60*60;
 9918:         if ($liburi) {
 9919: 	    $liburi=&declutter($liburi);
 9920:             $filename=$liburi;
 9921:         } else {
 9922: 	    &devalidate_cache_new('meta',$uri);
 9923: 	    undef(%metaentry);
 9924: 	}
 9925:         my %metathesekeys=();
 9926:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9927: 	my $metastring;
 9928: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9929: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9930: 	    $metastring = 
 9931: 		&Apache::lonnet::ssi_body($which,
 9932: 					  ('grade_target' => 'meta'));
 9933: 	    $cachetime = 1; # only want this cached in the child not long term
 9934: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9935:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9936: 	    my $file=&filelocation('',&clutter($filename));
 9937: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9938: 	    $metastring=&getfile($file);
 9939: 	}
 9940:         my $parser=HTML::LCParser->new(\$metastring);
 9941:         my $token;
 9942:         undef %metathesekeys;
 9943:         while ($token=$parser->get_token) {
 9944: 	    if ($token->[0] eq 'S') {
 9945: 		if (defined($token->[2]->{'package'})) {
 9946: #
 9947: # This is a package - get package info
 9948: #
 9949: 		    my $package=$token->[2]->{'package'};
 9950: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9951: 		    if (defined($token->[2]->{'id'})) { 
 9952: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9953: 		    }
 9954: 		    if ($metaentry{':packages'}) {
 9955: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9956: 		    } else {
 9957: 			$metaentry{':packages'}=$package.$keyroot;
 9958: 		    }
 9959: 		    foreach my $pack_entry (keys(%packagetab)) {
 9960: 			my $part=$keyroot;
 9961: 			$part=~s/^\_//;
 9962: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9963: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9964: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9965: 			    # ignore package.tab specified default values
 9966:                             # here &package_tab_default() will fetch those
 9967: 			    if ($subp eq 'default') { next; }
 9968: 			    my $value=$packagetab{$pack_entry};
 9969: 			    my $unikey;
 9970: 			    if ($pack =~ /_0$/) {
 9971: 				$unikey='parameter_0_'.$name;
 9972: 				$part=0;
 9973: 			    } else {
 9974: 				$unikey='parameter'.$keyroot.'_'.$name;
 9975: 			    }
 9976: 			    if ($subp eq 'display') {
 9977: 				$value.=' [Part: '.$part.']';
 9978: 			    }
 9979: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9980: 			    $metathesekeys{$unikey}=1;
 9981: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9982: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9983: 			    }
 9984: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9985: 				$metaentry{':'.$unikey}=
 9986: 				    $metaentry{':'.$unikey.'.default'};
 9987: 			    }
 9988: 			}
 9989: 		    }
 9990: 		} else {
 9991: #
 9992: # This is not a package - some other kind of start tag
 9993: #
 9994: 		    my $entry=$token->[1];
 9995: 		    my $unikey='';
 9996: 
 9997: 		    if ($entry eq 'import') {
 9998: #
 9999: # Importing a library here
10000: #
10001:                         my $location=$parser->get_text('/import');
10002:                         my $dir=$filename;
10003:                         $dir=~s|[^/]*$||;
10004:                         $location=&filelocation($dir,$location);
10005:                        
10006:                         my $importmode=$token->[2]->{'importmode'};
10007:                         if ($importmode eq 'problem') {
10008: # Import as problem/response
10009:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10010:                         } elsif ($importmode eq 'part') {
10011: # Import as part(s)
10012:                            $importedparts=1;
10013: # We need to get the original file and the imported file to get the part order correct
10014: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10015: # Load and inspect original file
10016:                            if ($#origfileimportpartids<0) {
10017:                               undef(%importedpartids);
10018:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10019:                               my $origfile=&getfile($origfilelocation);
10020:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10021:                            }
10022: 
10023: # Load and inspect imported file
10024:                            my $impfile=&getfile($location);
10025:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10026:                            if ($#impfilepartids>=0) {
10027: # This problem had parts
10028:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10029:                            } else {
10030: # Importing by turning a single problem into a problem part
10031: # It gets the import-tags ID as part-ID
10032:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10033:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10034:                            }
10035:                         } else {
10036: # Normal import
10037:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10038:                            if (defined($token->[2]->{'id'})) {
10039:                               $unikey.='_'.$token->[2]->{'id'};
10040:                            }
10041:                         }
10042: 
10043: 			if ($depthcount<20) {
10044: 			    my $metadata = 
10045: 				&metadata($uri,'keys', $location,$unikey,
10046: 					  $depthcount+1);
10047: 			    foreach my $meta (split(',',$metadata)) {
10048: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10049: 				$metathesekeys{$meta}=1;
10050: 			    }
10051: 			
10052:                         }
10053: 		    } else {
10054: #
10055: # Not importing, some other kind of non-package, non-library start tag
10056: # 
10057:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10058:                         if (defined($token->[2]->{'id'})) {
10059:                             $unikey.='_'.$token->[2]->{'id'};
10060:                         }
10061: 			if (defined($token->[2]->{'name'})) { 
10062: 			    $unikey.='_'.$token->[2]->{'name'}; 
10063: 			}
10064: 			$metathesekeys{$unikey}=1;
10065: 			foreach my $param (@{$token->[3]}) {
10066: 			    $metaentry{':'.$unikey.'.'.$param} =
10067: 				$token->[2]->{$param};
10068: 			}
10069: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10070: 			my $default=$metaentry{':'.$unikey.'.default'};
10071: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10072: 		 # only ws inside the tag, and not in default, so use default
10073: 		 # as value
10074: 			    $metaentry{':'.$unikey}=$default;
10075: 			} elsif ( $internaltext =~ /\S/ ) {
10076: 		  # something interesting inside the tag
10077: 			    $metaentry{':'.$unikey}=$internaltext;
10078: 			} else {
10079: 		  # no interesting values, don't set a default
10080: 			}
10081: # end of not-a-package not-a-library import
10082: 		    }
10083: # end of not-a-package start tag
10084: 		}
10085: # the next is the end of "start tag"
10086: 	    }
10087: 	}
10088: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10089: 	$extension = lc($extension);
10090: 	if ($extension eq 'htm') { $extension='html'; }
10091: 
10092: 	foreach my $key (keys(%packagetab)) {
10093: 	    #no specific packages #how's our extension
10094: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10095: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10096: 					 \%metathesekeys);
10097: 	}
10098: 
10099: 	if (!exists($metaentry{':packages'})
10100: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10101: 	    foreach my $key (keys(%packagetab)) {
10102: 		#no specific packages well let's get default then
10103: 		if ($key!~/^default&/) { next; }
10104: 		&metadata_create_package_def($uri,$key,'default',
10105: 					     \%metathesekeys);
10106: 	    }
10107: 	}
10108: # are there custom rights to evaluate
10109: 	if ($metaentry{':copyright'} eq 'custom') {
10110: 
10111:     #
10112:     # Importing a rights file here
10113:     #
10114: 	    unless ($depthcount) {
10115: 		my $location=$metaentry{':customdistributionfile'};
10116: 		my $dir=$filename;
10117: 		$dir=~s|[^/]*$||;
10118: 		$location=&filelocation($dir,$location);
10119: 		my $rights_metadata =
10120: 		    &metadata($uri,'keys',$location,'_rights',
10121: 			      $depthcount+1);
10122: 		foreach my $rights (split(',',$rights_metadata)) {
10123: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10124: 		    $metathesekeys{$rights}=1;
10125: 		}
10126: 	    }
10127: 	}
10128: 	# uniqifiy package listing
10129: 	my %seen;
10130: 	my @uniq_packages =
10131: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10132: 	$metaentry{':packages'} = join(',',@uniq_packages);
10133: 
10134:         if ($importedparts) {
10135: # We had imported parts and need to rebuild partorder
10136:            $metaentry{':partorder'}='';
10137:            $metathesekeys{'partorder'}=1;
10138:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10139:                if ($origfileimportpartids[$index] eq 'part') {
10140: # original part, part of the problem
10141:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10142:                } else {
10143: # we have imported parts at this position
10144:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10145:                }
10146:            }
10147:            $metaentry{':partorder'}=~s/^\,//;
10148:         }
10149: 
10150: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10151: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10152: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10153: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10154: # this is the end of "was not already recently cached
10155:     }
10156:     return $metaentry{':'.$what};
10157: }
10158: 
10159: sub metadata_create_package_def {
10160:     my ($uri,$key,$package,$metathesekeys)=@_;
10161:     my ($pack,$name,$subp)=split(/\&/,$key);
10162:     if ($subp eq 'default') { next; }
10163:     
10164:     if (defined($metaentry{':packages'})) {
10165: 	$metaentry{':packages'}.=','.$package;
10166:     } else {
10167: 	$metaentry{':packages'}=$package;
10168:     }
10169:     my $value=$packagetab{$key};
10170:     my $unikey;
10171:     $unikey='parameter_0_'.$name;
10172:     $metaentry{':'.$unikey.'.part'}=0;
10173:     $$metathesekeys{$unikey}=1;
10174:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10175: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10176:     }
10177:     if (defined($metaentry{':'.$unikey.'.default'})) {
10178: 	$metaentry{':'.$unikey}=
10179: 	    $metaentry{':'.$unikey.'.default'};
10180:     }
10181: }
10182: 
10183: sub metadata_generate_part0 {
10184:     my ($metadata,$metacache,$uri) = @_;
10185:     my %allnames;
10186:     foreach my $metakey (keys(%$metadata)) {
10187: 	if ($metakey=~/^parameter\_(.*)/) {
10188: 	  my $part=$$metacache{':'.$metakey.'.part'};
10189: 	  my $name=$$metacache{':'.$metakey.'.name'};
10190: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10191: 	    $allnames{$name}=$part;
10192: 	  }
10193: 	}
10194:     }
10195:     foreach my $name (keys(%allnames)) {
10196:       $$metadata{"parameter_0_$name"}=1;
10197:       my $key=":parameter_0_$name";
10198:       $$metacache{"$key.part"}='0';
10199:       $$metacache{"$key.name"}=$name;
10200:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10201: 					   $allnames{$name}.'_'.$name.
10202: 					   '.type'};
10203:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10204: 			     '.display'};
10205:       my $expr='[Part: '.$allnames{$name}.']';
10206:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10207:       $$metacache{"$key.display"}=$olddis;
10208:     }
10209: }
10210: 
10211: # ------------------------------------------------------ Devalidate title cache
10212: 
10213: sub devalidate_title_cache {
10214:     my ($url)=@_;
10215:     if (!$env{'request.course.id'}) { return; }
10216:     my $symb=&symbread($url);
10217:     if (!$symb) { return; }
10218:     my $key=$env{'request.course.id'}."\0".$symb;
10219:     &devalidate_cache_new('title',$key);
10220: }
10221: 
10222: # ------------------------------------------------- Get the title of a course
10223: 
10224: sub current_course_title {
10225:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10226: }
10227: # ------------------------------------------------- Get the title of a resource
10228: 
10229: sub gettitle {
10230:     my $urlsymb=shift;
10231:     my $symb=&symbread($urlsymb);
10232:     if ($symb) {
10233: 	my $key=$env{'request.course.id'}."\0".$symb;
10234: 	my ($result,$cached)=&is_cached_new('title',$key);
10235: 	if (defined($cached)) { 
10236: 	    return $result;
10237: 	}
10238: 	my ($map,$resid,$url)=&decode_symb($symb);
10239: 	my $title='';
10240: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10241: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10242: 	} else {
10243: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10244: 		    &GDBM_READER(),0640)) {
10245: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10246: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10247: 		untie(%bighash);
10248: 	    }
10249: 	}
10250: 	$title=~s/\&colon\;/\:/gs;
10251: 	if ($title) {
10252: # Remember both $symb and $title for dynamic metadata
10253:             $accesshash{$symb.'___crstitle'}=$title;
10254:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10255: # Cache this title and then return it
10256: 	    return &do_cache_new('title',$key,$title,600);
10257: 	}
10258: 	$urlsymb=$url;
10259:     }
10260:     my $title=&metadata($urlsymb,'title');
10261:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10262:     return $title;
10263: }
10264: 
10265: sub get_slot {
10266:     my ($which,$cnum,$cdom)=@_;
10267:     if (!$cnum || !$cdom) {
10268: 	(undef,my $courseid)=&whichuser();
10269: 	$cdom=$env{'course.'.$courseid.'.domain'};
10270: 	$cnum=$env{'course.'.$courseid.'.num'};
10271:     }
10272:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10273:     my %slotinfo;
10274:     if (exists($remembered{$key})) {
10275: 	$slotinfo{$which} = $remembered{$key};
10276:     } else {
10277: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10278: 	&Apache::lonhomework::showhash(%slotinfo);
10279: 	my ($tmp)=keys(%slotinfo);
10280: 	if ($tmp=~/^error:/) { return (); }
10281: 	$remembered{$key} = $slotinfo{$which};
10282:     }
10283:     if (ref($slotinfo{$which}) eq 'HASH') {
10284: 	return %{$slotinfo{$which}};
10285:     }
10286:     return $slotinfo{$which};
10287: }
10288: 
10289: sub get_reservable_slots {
10290:     my ($cnum,$cdom,$uname,$udom) = @_;
10291:     my $now = time;
10292:     my $reservable_info;
10293:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10294:     if (exists($remembered{$key})) {
10295:         $reservable_info = $remembered{$key};
10296:     } else {
10297:         my %resv;
10298:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10299:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10300:         $reservable_info = \%resv;
10301:         $remembered{$key} = $reservable_info;
10302:     }
10303:     return $reservable_info;
10304: }
10305: 
10306: sub get_course_slots {
10307:     my ($cnum,$cdom) = @_;
10308:     my $hashid=$cnum.':'.$cdom;
10309:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10310:     if (defined($cached)) {
10311:         if (ref($result) eq 'HASH') {
10312:             return %{$result};
10313:         }
10314:     } else {
10315:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10316:         my ($tmp) = keys(%slots);
10317:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10318:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10319:             return %slots;
10320:         }
10321:     }
10322:     return;
10323: }
10324: 
10325: sub devalidate_slots_cache {
10326:     my ($cnum,$cdom)=@_;
10327:     my $hashid=$cnum.':'.$cdom;
10328:     &devalidate_cache_new('allslots',$hashid);
10329: }
10330: 
10331: sub get_coursechange {
10332:     my ($cdom,$cnum) = @_;
10333:     if ($cdom eq '' || $cnum eq '') {
10334:         return unless ($env{'request.course.id'});
10335:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10336:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10337:     }
10338:     my $hashid=$cdom.'_'.$cnum;
10339:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10340:     if ((defined($cached)) && ($change ne '')) {
10341:         return $change;
10342:     } else {
10343:         my %crshash;
10344:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10345:         if ($crshash{'internal.contentchange'} eq '') {
10346:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10347:             if ($change eq '') {
10348:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10349:                 $change = $crshash{'internal.created'};
10350:             }
10351:         } else {
10352:             $change = $crshash{'internal.contentchange'};
10353:         }
10354:         my $cachetime = 600;
10355:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10356:     }
10357:     return $change;
10358: }
10359: 
10360: sub devalidate_coursechange_cache {
10361:     my ($cnum,$cdom)=@_;
10362:     my $hashid=$cnum.':'.$cdom;
10363:     &devalidate_cache_new('crschange',$hashid);
10364: }
10365: 
10366: # ------------------------------------------------- Update symbolic store links
10367: 
10368: sub symblist {
10369:     my ($mapname,%newhash)=@_;
10370:     $mapname=&deversion(&declutter($mapname));
10371:     my %hash;
10372:     if (($env{'request.course.fn'}) && (%newhash)) {
10373:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10374:                       &GDBM_WRCREAT(),0640)) {
10375: 	    foreach my $url (keys(%newhash)) {
10376: 		next if ($url eq 'last_known'
10377: 			 && $env{'form.no_update_last_known'});
10378: 		$hash{declutter($url)}=&encode_symb($mapname,
10379: 						    $newhash{$url}->[1],
10380: 						    $newhash{$url}->[0]);
10381:             }
10382:             if (untie(%hash)) {
10383: 		return 'ok';
10384:             }
10385:         }
10386:     }
10387:     return 'error';
10388: }
10389: 
10390: # --------------------------------------------------------------- Verify a symb
10391: 
10392: sub symbverify {
10393:     my ($symb,$thisurl,$encstate)=@_;
10394:     my $thisfn=$thisurl;
10395:     $thisfn=&declutter($thisfn);
10396: # direct jump to resource in page or to a sequence - will construct own symbs
10397:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10398: # check URL part
10399:     my ($map,$resid,$url)=&decode_symb($symb);
10400: 
10401:     unless ($url eq $thisfn) { return 0; }
10402: 
10403:     $symb=&symbclean($symb);
10404:     $thisurl=&deversion($thisurl);
10405:     $thisfn=&deversion($thisfn);
10406: 
10407:     my %bighash;
10408:     my $okay=0;
10409: 
10410:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10411:                             &GDBM_READER(),0640)) {
10412:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10413:             $thisurl =~ s/\?.+$//;
10414:         }
10415:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
10416:         unless ($ids) {
10417:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10418:             $ids=$bighash{$idkey};
10419:         }
10420:         if ($ids) {
10421: # ------------------------------------------------------------------- Has ID(s)
10422: 	    foreach my $id (split(/\,/,$ids)) {
10423: 	       my ($mapid,$resid)=split(/\./,$id);
10424:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10425:                    $symb =~ s/\?.+$//;
10426:                }
10427:                if (
10428:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10429:    eq $symb) {
10430:                    if (ref($encstate)) {
10431:                        $$encstate = $bighash{'encrypted_'.$id};
10432:                    }
10433: 		   if (($env{'request.role.adv'}) ||
10434: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10435:                        ($thisurl eq '/adm/navmaps')) {
10436: 		       $okay=1;
10437: 		   }
10438: 	       }
10439: 	   }
10440:         }
10441: 	untie(%bighash);
10442:     }
10443:     return $okay;
10444: }
10445: 
10446: # --------------------------------------------------------------- Clean-up symb
10447: 
10448: sub symbclean {
10449:     my $symb=shift;
10450:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10451: # remove version from map
10452:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10453: 
10454: # remove version from URL
10455:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10456: 
10457: # remove wrapper
10458: 
10459:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10460:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10461:     return $symb;
10462: }
10463: 
10464: # ---------------------------------------------- Split symb to find map and url
10465: 
10466: sub encode_symb {
10467:     my ($map,$resid,$url)=@_;
10468:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10469: }
10470: 
10471: sub decode_symb {
10472:     my $symb=shift;
10473:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10474:     my ($map,$resid,$url)=split(/___/,$symb);
10475:     return (&fixversion($map),$resid,&fixversion($url));
10476: }
10477: 
10478: sub fixversion {
10479:     my $fn=shift;
10480:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10481:     my %bighash;
10482:     my $uri=&clutter($fn);
10483:     my $key=$env{'request.course.id'}.'_'.$uri;
10484: # is this cached?
10485:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10486:     if (defined($cached)) { return $result; }
10487: # unfortunately not cached, or expired
10488:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10489: 	    &GDBM_READER(),0640)) {
10490:  	if ($bighash{'version_'.$uri}) {
10491:  	    my $version=$bighash{'version_'.$uri};
10492:  	    unless (($version eq 'mostrecent') || 
10493: 		    ($version==&getversion($uri))) {
10494:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10495:  	    }
10496:  	}
10497:  	untie %bighash;
10498:     }
10499:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10500: }
10501: 
10502: sub deversion {
10503:     my $url=shift;
10504:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10505:     return $url;
10506: }
10507: 
10508: # ------------------------------------------------------ Return symb list entry
10509: 
10510: sub symbread {
10511:     my ($thisfn,$donotrecurse)=@_;
10512:     my $cache_str='request.symbread.cached.'.$thisfn;
10513:     if (defined($env{$cache_str})) {
10514:         if (($thisfn) || ($env{$cache_str} ne '')) {
10515:             return $env{$cache_str};
10516:         }
10517:     }
10518: # no filename provided? try from environment
10519:     unless ($thisfn) {
10520:         if ($env{'request.symb'}) {
10521: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10522: 	}
10523: 	$thisfn=$env{'request.filename'};
10524:     }
10525:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10526: # is that filename actually a symb? Verify, clean, and return
10527:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10528: 	if (&symbverify($thisfn,$1)) {
10529: 	    return $env{$cache_str}=&symbclean($thisfn);
10530: 	}
10531:     }
10532:     $thisfn=declutter($thisfn);
10533:     my %hash;
10534:     my %bighash;
10535:     my $syval='';
10536:     if (($env{'request.course.fn'}) && ($thisfn)) {
10537:         my $targetfn = $thisfn;
10538:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10539:             $targetfn = 'adm/wrapper/'.$thisfn;
10540:         }
10541: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10542: 	    $targetfn=$1;
10543: 	}
10544:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10545:                       &GDBM_READER(),0640)) {
10546: 	    $syval=$hash{$targetfn};
10547:             untie(%hash);
10548:         }
10549: # ---------------------------------------------------------- There was an entry
10550:         if ($syval) {
10551: 	    #unless ($syval=~/\_\d+$/) {
10552: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10553: 		    #&appenv({'request.ambiguous' => $thisfn});
10554: 		    #return $env{$cache_str}='';
10555: 		#}    
10556: 		#$syval.=$1;
10557: 	    #}
10558:         } else {
10559: # ------------------------------------------------------- Was not in symb table
10560:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10561:                             &GDBM_READER(),0640)) {
10562: # ---------------------------------------------- Get ID(s) for current resource
10563:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10564:               unless ($ids) { 
10565:                  $ids=$bighash{'ids_/'.$thisfn};
10566:               }
10567:               unless ($ids) {
10568: # alias?
10569: 		  $ids=$bighash{'mapalias_'.$thisfn};
10570:               }
10571:               if ($ids) {
10572: # ------------------------------------------------------------------- Has ID(s)
10573:                  my @possibilities=split(/\,/,$ids);
10574:                  if ($#possibilities==0) {
10575: # ----------------------------------------------- There is only one possibility
10576: 		     my ($mapid,$resid)=split(/\./,$ids);
10577: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10578: 						    $resid,$thisfn);
10579:                  } elsif (!$donotrecurse) {
10580: # ------------------------------------------ There is more than one possibility
10581:                      my $realpossible=0;
10582:                      foreach my $id (@possibilities) {
10583: 			 my $file=$bighash{'src_'.$id};
10584:                          if (&allowed('bre',$file)) {
10585:          		    my ($mapid,$resid)=split(/\./,$id);
10586:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10587: 				$realpossible++;
10588:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10589: 						    $resid,$thisfn);
10590:                             }
10591: 			 }
10592:                      }
10593: 		     if ($realpossible!=1) { $syval=''; }
10594:                  } else {
10595:                      $syval='';
10596:                  }
10597: 	      }
10598:               untie(%bighash)
10599:            }
10600:         }
10601:         if ($syval) {
10602: 	    return $env{$cache_str}=$syval;
10603:         }
10604:     }
10605:     &appenv({'request.ambiguous' => $thisfn});
10606:     return $env{$cache_str}='';
10607: }
10608: 
10609: # ---------------------------------------------------------- Return random seed
10610: 
10611: sub numval {
10612:     my $txt=shift;
10613:     $txt=~tr/A-J/0-9/;
10614:     $txt=~tr/a-j/0-9/;
10615:     $txt=~tr/K-T/0-9/;
10616:     $txt=~tr/k-t/0-9/;
10617:     $txt=~tr/U-Z/0-5/;
10618:     $txt=~tr/u-z/0-5/;
10619:     $txt=~s/\D//g;
10620:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10621:     return int($txt);
10622: }
10623: 
10624: sub numval2 {
10625:     my $txt=shift;
10626:     $txt=~tr/A-J/0-9/;
10627:     $txt=~tr/a-j/0-9/;
10628:     $txt=~tr/K-T/0-9/;
10629:     $txt=~tr/k-t/0-9/;
10630:     $txt=~tr/U-Z/0-5/;
10631:     $txt=~tr/u-z/0-5/;
10632:     $txt=~s/\D//g;
10633:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10634:     my $total;
10635:     foreach my $val (@txts) { $total+=$val; }
10636:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10637:     return int($total);
10638: }
10639: 
10640: sub numval3 {
10641:     use integer;
10642:     my $txt=shift;
10643:     $txt=~tr/A-J/0-9/;
10644:     $txt=~tr/a-j/0-9/;
10645:     $txt=~tr/K-T/0-9/;
10646:     $txt=~tr/k-t/0-9/;
10647:     $txt=~tr/U-Z/0-5/;
10648:     $txt=~tr/u-z/0-5/;
10649:     $txt=~s/\D//g;
10650:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10651:     my $total;
10652:     foreach my $val (@txts) { $total+=$val; }
10653:     if ($_64bit) { $total=(($total<<32)>>32); }
10654:     return $total;
10655: }
10656: 
10657: sub digest {
10658:     my ($data)=@_;
10659:     my $digest=&Digest::MD5::md5($data);
10660:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10661:     my ($e,$f);
10662:     {
10663:         use integer;
10664:         $e=($a+$b);
10665:         $f=($c+$d);
10666:         if ($_64bit) {
10667:             $e=(($e<<32)>>32);
10668:             $f=(($f<<32)>>32);
10669:         }
10670:     }
10671:     if (wantarray) {
10672: 	return ($e,$f);
10673:     } else {
10674: 	my $g;
10675: 	{
10676: 	    use integer;
10677: 	    $g=($e+$f);
10678: 	    if ($_64bit) {
10679: 		$g=(($g<<32)>>32);
10680: 	    }
10681: 	}
10682: 	return $g;
10683:     }
10684: }
10685: 
10686: sub latest_rnd_algorithm_id {
10687:     return '64bit5';
10688: }
10689: 
10690: sub get_rand_alg {
10691:     my ($courseid)=@_;
10692:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10693:     if ($courseid) {
10694: 	return $env{"course.$courseid.rndseed"};
10695:     }
10696:     return &latest_rnd_algorithm_id();
10697: }
10698: 
10699: sub validCODE {
10700:     my ($CODE)=@_;
10701:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10702:     return 0;
10703: }
10704: 
10705: sub getCODE {
10706:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10707:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10708: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10709: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10710: 	return $Apache::lonhomework::history{'resource.CODE'};
10711:     }
10712:     return undef;
10713: }
10714: #
10715: #  Determines the random seed for a specific context:
10716: #
10717: # parameters:
10718: #   symb      - in course context the symb for the seed.
10719: #   course_id - The course id of the form domain_coursenum.
10720: #   domain    - Domain for the user.
10721: #   course    - Course for the user.
10722: #   cenv      - environment of the course.
10723: #
10724: # NOTE:
10725: #   All parameters are picked out of the environment if missing
10726: #   or not defined.
10727: #   If a symb cannot be determined the current time is used instead.
10728: #
10729: #  For a given well defined symb, courside, domain, username,
10730: #  and course environment, the seed is reproducible.
10731: #
10732: sub rndseed {
10733:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10734:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10735:     if (!defined($symb)) {
10736: 	unless ($symb=$wsymb) { return time; }
10737:     }
10738:     if (!defined $courseid) { 
10739: 	$courseid=$wcourseid; 
10740:     }
10741:     if (!defined $domain) { $domain=$wdomain; }
10742:     if (!defined $username) { $username=$wusername }
10743: 
10744:     my $which;
10745:     if (defined($cenv->{'rndseed'})) {
10746: 	$which = $cenv->{'rndseed'};
10747:     } else {
10748: 	$which =&get_rand_alg($courseid);
10749:     }
10750:     if (defined(&getCODE())) {
10751: 
10752: 	if ($which eq '64bit5') {
10753: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10754: 	} elsif ($which eq '64bit4') {
10755: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10756: 	} else {
10757: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10758: 	}
10759:     } elsif ($which eq '64bit5') {
10760: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10761:     } elsif ($which eq '64bit4') {
10762: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10763:     } elsif ($which eq '64bit3') {
10764: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10765:     } elsif ($which eq '64bit2') {
10766: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10767:     } elsif ($which eq '64bit') {
10768: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10769:     }
10770:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10771: }
10772: 
10773: sub rndseed_32bit {
10774:     my ($symb,$courseid,$domain,$username)=@_;
10775:     {
10776: 	use integer;
10777: 	my $symbchck=unpack("%32C*",$symb) << 27;
10778: 	my $symbseed=numval($symb) << 22;
10779: 	my $namechck=unpack("%32C*",$username) << 17;
10780: 	my $nameseed=numval($username) << 12;
10781: 	my $domainseed=unpack("%32C*",$domain) << 7;
10782: 	my $courseseed=unpack("%32C*",$courseid);
10783: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10784: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10785: 	#&logthis("rndseed :$num:$symb");
10786: 	if ($_64bit) { $num=(($num<<32)>>32); }
10787: 	return $num;
10788:     }
10789: }
10790: 
10791: sub rndseed_64bit {
10792:     my ($symb,$courseid,$domain,$username)=@_;
10793:     {
10794: 	use integer;
10795: 	my $symbchck=unpack("%32S*",$symb) << 21;
10796: 	my $symbseed=numval($symb) << 10;
10797: 	my $namechck=unpack("%32S*",$username);
10798: 	
10799: 	my $nameseed=numval($username) << 21;
10800: 	my $domainseed=unpack("%32S*",$domain) << 10;
10801: 	my $courseseed=unpack("%32S*",$courseid);
10802: 	
10803: 	my $num1=$symbchck+$symbseed+$namechck;
10804: 	my $num2=$nameseed+$domainseed+$courseseed;
10805: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10806: 	#&logthis("rndseed :$num:$symb");
10807: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10808: 	return "$num1,$num2";
10809:     }
10810: }
10811: 
10812: sub rndseed_64bit2 {
10813:     my ($symb,$courseid,$domain,$username)=@_;
10814:     {
10815: 	use integer;
10816: 	# strings need to be an even # of cahracters long, it it is odd the
10817:         # last characters gets thrown away
10818: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10819: 	my $symbseed=numval($symb) << 10;
10820: 	my $namechck=unpack("%32S*",$username.' ');
10821: 	
10822: 	my $nameseed=numval($username) << 21;
10823: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10824: 	my $courseseed=unpack("%32S*",$courseid.' ');
10825: 	
10826: 	my $num1=$symbchck+$symbseed+$namechck;
10827: 	my $num2=$nameseed+$domainseed+$courseseed;
10828: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10829: 	#&logthis("rndseed :$num:$symb");
10830: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10831: 	return "$num1,$num2";
10832:     }
10833: }
10834: 
10835: sub rndseed_64bit3 {
10836:     my ($symb,$courseid,$domain,$username)=@_;
10837:     {
10838: 	use integer;
10839: 	# strings need to be an even # of cahracters long, it it is odd the
10840:         # last characters gets thrown away
10841: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10842: 	my $symbseed=numval2($symb) << 10;
10843: 	my $namechck=unpack("%32S*",$username.' ');
10844: 	
10845: 	my $nameseed=numval2($username) << 21;
10846: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10847: 	my $courseseed=unpack("%32S*",$courseid.' ');
10848: 	
10849: 	my $num1=$symbchck+$symbseed+$namechck;
10850: 	my $num2=$nameseed+$domainseed+$courseseed;
10851: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10852: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10853: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10854: 	
10855: 	return "$num1:$num2";
10856:     }
10857: }
10858: 
10859: sub rndseed_64bit4 {
10860:     my ($symb,$courseid,$domain,$username)=@_;
10861:     {
10862: 	use integer;
10863: 	# strings need to be an even # of cahracters long, it it is odd the
10864:         # last characters gets thrown away
10865: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10866: 	my $symbseed=numval3($symb) << 10;
10867: 	my $namechck=unpack("%32S*",$username.' ');
10868: 	
10869: 	my $nameseed=numval3($username) << 21;
10870: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10871: 	my $courseseed=unpack("%32S*",$courseid.' ');
10872: 	
10873: 	my $num1=$symbchck+$symbseed+$namechck;
10874: 	my $num2=$nameseed+$domainseed+$courseseed;
10875: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10876: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10877: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10878: 	
10879: 	return "$num1:$num2";
10880:     }
10881: }
10882: 
10883: sub rndseed_64bit5 {
10884:     my ($symb,$courseid,$domain,$username)=@_;
10885:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10886:     return "$num1:$num2";
10887: }
10888: 
10889: sub rndseed_CODE_64bit {
10890:     my ($symb,$courseid,$domain,$username)=@_;
10891:     {
10892: 	use integer;
10893: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10894: 	my $symbseed=numval2($symb);
10895: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10896: 	my $CODEseed=numval(&getCODE());
10897: 	my $courseseed=unpack("%32S*",$courseid.' ');
10898: 	my $num1=$symbseed+$CODEchck;
10899: 	my $num2=$CODEseed+$courseseed+$symbchck;
10900: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10901: 	#&logthis("rndseed :$num1:$num2:$symb");
10902: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10903: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10904: 	return "$num1:$num2";
10905:     }
10906: }
10907: 
10908: sub rndseed_CODE_64bit4 {
10909:     my ($symb,$courseid,$domain,$username)=@_;
10910:     {
10911: 	use integer;
10912: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10913: 	my $symbseed=numval3($symb);
10914: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10915: 	my $CODEseed=numval3(&getCODE());
10916: 	my $courseseed=unpack("%32S*",$courseid.' ');
10917: 	my $num1=$symbseed+$CODEchck;
10918: 	my $num2=$CODEseed+$courseseed+$symbchck;
10919: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10920: 	#&logthis("rndseed :$num1:$num2:$symb");
10921: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10922: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10923: 	return "$num1:$num2";
10924:     }
10925: }
10926: 
10927: sub rndseed_CODE_64bit5 {
10928:     my ($symb,$courseid,$domain,$username)=@_;
10929:     my $code = &getCODE();
10930:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10931:     return "$num1:$num2";
10932: }
10933: 
10934: sub setup_random_from_rndseed {
10935:     my ($rndseed)=@_;
10936:     if ($rndseed =~/([,:])/) {
10937: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10938: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10939:     } else {
10940: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10941:     }
10942: }
10943: 
10944: sub latest_receipt_algorithm_id {
10945:     return 'receipt3';
10946: }
10947: 
10948: sub recunique {
10949:     my $fucourseid=shift;
10950:     my $unique;
10951:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10952: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10953: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10954:     } else {
10955: 	$unique=$perlvar{'lonReceipt'};
10956:     }
10957:     return unpack("%32C*",$unique);
10958: }
10959: 
10960: sub recprefix {
10961:     my $fucourseid=shift;
10962:     my $prefix;
10963:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10964: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10965: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10966:     } else {
10967: 	$prefix=$perlvar{'lonHostID'};
10968:     }
10969:     return unpack("%32C*",$prefix);
10970: }
10971: 
10972: sub ireceipt {
10973:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10974: 
10975:     my $return =&recprefix($fucourseid).'-';
10976: 
10977:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10978: 	$env{'request.state'} eq 'construct') {
10979: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10980: 	return $return;
10981:     }
10982: 
10983:     my $cuname=unpack("%32C*",$funame);
10984:     my $cudom=unpack("%32C*",$fudom);
10985:     my $cucourseid=unpack("%32C*",$fucourseid);
10986:     my $cusymb=unpack("%32C*",$fusymb);
10987:     my $cunique=&recunique($fucourseid);
10988:     my $cpart=unpack("%32S*",$part);
10989:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10990: 
10991: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10992: 			       
10993: 	$return.= ($cunique%$cuname+
10994: 		   $cunique%$cudom+
10995: 		   $cusymb%$cuname+
10996: 		   $cusymb%$cudom+
10997: 		   $cucourseid%$cuname+
10998: 		   $cucourseid%$cudom+
10999: 		   $cpart%$cuname+
11000: 		   $cpart%$cudom);
11001:     } else {
11002: 	$return.= ($cunique%$cuname+
11003: 		   $cunique%$cudom+
11004: 		   $cusymb%$cuname+
11005: 		   $cusymb%$cudom+
11006: 		   $cucourseid%$cuname+
11007: 		   $cucourseid%$cudom);
11008:     }
11009:     return $return;
11010: }
11011: 
11012: sub receipt {
11013:     my ($part)=@_;
11014:     my ($symb,$courseid,$domain,$name) = &whichuser();
11015:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11016: }
11017: 
11018: sub whichuser {
11019:     my ($passedsymb)=@_;
11020:     my ($symb,$courseid,$domain,$name,$publicuser);
11021:     if (defined($env{'form.grade_symb'})) {
11022: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11023: 	my $allowed=&allowed('vgr',$tmp_courseid);
11024: 	if (!$allowed &&
11025: 	    exists($env{'request.course.sec'}) &&
11026: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11027: 	    $allowed=&allowed('vgr',$tmp_courseid.
11028: 			      '/'.$env{'request.course.sec'});
11029: 	}
11030: 	if ($allowed) {
11031: 	    ($symb)=&get_env_multiple('form.grade_symb');
11032: 	    $courseid=$tmp_courseid;
11033: 	    ($domain)=&get_env_multiple('form.grade_domain');
11034: 	    ($name)=&get_env_multiple('form.grade_username');
11035: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11036: 	}
11037:     }
11038:     if (!$passedsymb) {
11039: 	$symb=&symbread();
11040:     } else {
11041: 	$symb=$passedsymb;
11042:     }
11043:     $courseid=$env{'request.course.id'};
11044:     $domain=$env{'user.domain'};
11045:     $name=$env{'user.name'};
11046:     if ($name eq 'public' && $domain eq 'public') {
11047: 	if (!defined($env{'form.username'})) {
11048: 	    $env{'form.username'}.=time.rand(10000000);
11049: 	}
11050: 	$name.=$env{'form.username'};
11051:     }
11052:     return ($symb,$courseid,$domain,$name,$publicuser);
11053: 
11054: }
11055: 
11056: # ------------------------------------------------------------ Serves up a file
11057: # returns either the contents of the file or 
11058: # -1 if the file doesn't exist
11059: #
11060: # if the target is a file that was uploaded via DOCS, 
11061: # a check will be made to see if a current copy exists on the local server,
11062: # if it does this will be served, otherwise a copy will be retrieved from
11063: # the home server for the course and stored in /home/httpd/html/userfiles on
11064: # the local server.   
11065: 
11066: sub getfile {
11067:     my ($file) = @_;
11068:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11069:     &repcopy($file);
11070:     return &readfile($file);
11071: }
11072: 
11073: sub repcopy_userfile {
11074:     my ($file)=@_;
11075:     my $londocroot = $perlvar{'lonDocRoot'};
11076:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11077:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11078:     my ($cdom,$cnum,$filename) = 
11079: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11080:     my $uri="/uploaded/$cdom/$cnum/$filename";
11081:     if (-e "$file") {
11082: # we already have a local copy, check it out
11083: 	my @fileinfo = stat($file);
11084: 	my $rtncode;
11085: 	my $info;
11086: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11087: 	if ($lwpresp ne 'ok') {
11088: # there is no such file anymore, even though we had a local copy
11089: 	    if ($rtncode eq '404') {
11090: 		unlink($file);
11091: 	    }
11092: 	    return -1;
11093: 	}
11094: 	if ($info < $fileinfo[9]) {
11095: # nice, the file we have is up-to-date, just say okay
11096: 	    return 'ok';
11097: 	} else {
11098: # the file is outdated, get rid of it
11099: 	    unlink($file);
11100: 	}
11101:     }
11102: # one way or the other, at this point, we don't have the file
11103: # construct the correct path for the file
11104:     my @parts = ($cdom,$cnum); 
11105:     if ($filename =~ m|^(.+)/[^/]+$|) {
11106: 	push @parts, split(/\//,$1);
11107:     }
11108:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11109:     foreach my $part (@parts) {
11110: 	$path .= '/'.$part;
11111: 	if (!-e $path) {
11112: 	    mkdir($path,0770);
11113: 	}
11114:     }
11115: # now the path exists for sure
11116: # get a user agent
11117:     my $ua=new LWP::UserAgent;
11118:     my $transferfile=$file.'.in.transfer';
11119: # FIXME: this should flock
11120:     if (-e $transferfile) { return 'ok'; }
11121:     my $request;
11122:     $uri=~s/^\///;
11123:     my $homeserver = &homeserver($cnum,$cdom);
11124:     my $protocol = $protocol{$homeserver};
11125:     $protocol = 'http' if ($protocol ne 'https');
11126:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11127:     my $response=$ua->request($request,$transferfile);
11128: # did it work?
11129:     if ($response->is_error()) {
11130: 	unlink($transferfile);
11131: 	&logthis("Userfile repcopy failed for $uri");
11132: 	return -1;
11133:     }
11134: # worked, rename the transfer file
11135:     rename($transferfile,$file);
11136:     return 'ok';
11137: }
11138: 
11139: sub tokenwrapper {
11140:     my $uri=shift;
11141:     $uri=~s|^https?\://([^/]+)||;
11142:     $uri=~s|^/||;
11143:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11144:     my $token=$1;
11145:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11146:     if ($udom && $uname && $file) {
11147: 	$file=~s|(\?\.*)*$||;
11148:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11149:         my $homeserver = &homeserver($uname,$udom);
11150:         my $protocol = $protocol{$homeserver};
11151:         $protocol = 'http' if ($protocol ne 'https');
11152:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11153:                (($uri=~/\?/)?'&':'?').'token='.$token.
11154:                                '&tokenissued='.$perlvar{'lonHostID'};
11155:     } else {
11156:         return '/adm/notfound.html';
11157:     }
11158: }
11159: 
11160: # call with reqtype HEAD: get last modification time
11161: # call with reqtype GET: get the file contents
11162: # Do not call this with reqtype GET for large files! It loads everything into memory
11163: #
11164: sub getuploaded {
11165:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11166:     $uri=~s/^\///;
11167:     my $homeserver = &homeserver($cnum,$cdom);
11168:     my $protocol = $protocol{$homeserver};
11169:     $protocol = 'http' if ($protocol ne 'https');
11170:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11171:     my $ua=new LWP::UserAgent;
11172:     my $request=new HTTP::Request($reqtype,$uri);
11173:     my $response=$ua->request($request);
11174:     $$rtncode = $response->code;
11175:     if (! $response->is_success()) {
11176: 	return 'failed';
11177:     }      
11178:     if ($reqtype eq 'HEAD') {
11179: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11180:     } elsif ($reqtype eq 'GET') {
11181: 	$$info = $response->content;
11182:     }
11183:     return 'ok';
11184: }
11185: 
11186: sub readfile {
11187:     my $file = shift;
11188:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11189:     my $fh;
11190:     open($fh,"<$file");
11191:     my $a='';
11192:     while (my $line = <$fh>) { $a .= $line; }
11193:     return $a;
11194: }
11195: 
11196: sub filelocation {
11197:     my ($dir,$file) = @_;
11198:     my $location;
11199:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11200: 
11201:     if ($file =~ m-^/adm/-) {
11202: 	$file=~s-^/adm/wrapper/-/-;
11203: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11204:     }
11205: 
11206:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11207:         $location = $file;
11208:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11209:         my ($udom,$uname,$filename)=
11210:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11211:         my $home=&homeserver($uname,$udom);
11212:         my $is_me=0;
11213:         my @ids=&current_machine_ids();
11214:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11215:         if ($is_me) {
11216:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11217:         } else {
11218:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11219:   	      $udom.'/'.$uname.'/'.$filename;
11220:         }
11221:     } elsif ($file =~ m-^/adm/-) {
11222: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11223:     } else {
11224:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11225:         $file=~s:^/(res|priv)/:/:;
11226:         my $space=$1;
11227:         if ( !( $file =~ m:^/:) ) {
11228:             $location = $dir. '/'.$file;
11229:         } else {
11230:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11231:         }
11232:     }
11233:     $location=~s://+:/:g; # remove duplicate /
11234:     while ($location=~m{/\.\./}) {
11235: 	if ($location =~ m{/[^/]+/\.\./}) {
11236: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11237: 	} else {
11238: 	    $location=~ s{/\.\./}{/}g;
11239: 	}
11240:     } #remove dir/..
11241:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11242:     return $location;
11243: }
11244: 
11245: sub hreflocation {
11246:     my ($dir,$file)=@_;
11247:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11248: 	$file=filelocation($dir,$file);
11249:     } elsif ($file=~m-^/adm/-) {
11250: 	$file=~s-^/adm/wrapper/-/-;
11251: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11252:     }
11253:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11254: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11255:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11256: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11257: 	        {/uploaded/$1/$2/}x;
11258:     }
11259:     if ($file=~ m{^/userfiles/}) {
11260: 	$file =~ s{^/userfiles/}{/uploaded/};
11261:     }
11262:     return $file;
11263: }
11264: 
11265: 
11266: 
11267: 
11268: 
11269: sub current_machine_domains {
11270:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11271: }
11272: 
11273: sub machine_domains {
11274:     my ($hostname) = @_;
11275:     my @domains;
11276:     my %hostname = &all_hostnames();
11277:     while( my($id, $name) = each(%hostname)) {
11278: #	&logthis("-$id-$name-$hostname-");
11279: 	if ($hostname eq $name) {
11280: 	    push(@domains,&host_domain($id));
11281: 	}
11282:     }
11283:     return @domains;
11284: }
11285: 
11286: sub current_machine_ids {
11287:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11288: }
11289: 
11290: sub machine_ids {
11291:     my ($hostname) = @_;
11292:     $hostname ||= &hostname($perlvar{'lonHostID'});
11293:     my @ids;
11294:     my %name_to_host = &all_names();
11295:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11296: 	return @{ $name_to_host{$hostname} };
11297:     }
11298:     return;
11299: }
11300: 
11301: sub additional_machine_domains {
11302:     my @domains;
11303:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11304:     while( my $line = <$fh>) {
11305:         $line =~ s/\s//g;
11306:         push(@domains,$line);
11307:     }
11308:     return @domains;
11309: }
11310: 
11311: sub default_login_domain {
11312:     my $domain = $perlvar{'lonDefDomain'};
11313:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11314:     foreach my $posdom (&current_machine_domains(),
11315:                         &additional_machine_domains()) {
11316:         if (lc($posdom) eq lc($testdomain)) {
11317:             $domain=$posdom;
11318:             last;
11319:         }
11320:     }
11321:     return $domain;
11322: }
11323: 
11324: # ------------------------------------------------------------- Declutters URLs
11325: 
11326: sub declutter {
11327:     my $thisfn=shift;
11328:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11329:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11330:     $thisfn=~s/^\///;
11331:     $thisfn=~s|^adm/wrapper/||;
11332:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11333:     $thisfn=~s/^res\///;
11334:     $thisfn=~s/^priv\///;
11335:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11336:         $thisfn=~s/\?.+$//;
11337:     }
11338:     return $thisfn;
11339: }
11340: 
11341: # ------------------------------------------------------------- Clutter up URLs
11342: 
11343: sub clutter {
11344:     my $thisfn='/'.&declutter(shift);
11345:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11346: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11347:        $thisfn='/res'.$thisfn; 
11348:     }
11349:     if ($thisfn !~m|^/adm|) {
11350: 	if ($thisfn =~ m|^/ext/|) {
11351: 	    $thisfn='/adm/wrapper'.$thisfn;
11352: 	} else {
11353: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11354: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11355: 	    if ($embstyle eq 'ssi'
11356: 		|| ($embstyle eq 'hdn')
11357: 		|| ($embstyle eq 'rat')
11358: 		|| ($embstyle eq 'prv')
11359: 		|| ($embstyle eq 'ign')) {
11360: 		#do nothing with these
11361: 	    } elsif (($embstyle eq 'img') 
11362: 		|| ($embstyle eq 'emb')
11363: 		|| ($embstyle eq 'wrp')) {
11364: 		$thisfn='/adm/wrapper'.$thisfn;
11365: 	    } elsif ($embstyle eq 'unk'
11366: 		     && $thisfn!~/\.(sequence|page)$/) {
11367: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11368: 	    } else {
11369: #		&logthis("Got a blank emb style");
11370: 	    }
11371: 	}
11372:     }
11373:     return $thisfn;
11374: }
11375: 
11376: sub clutter_with_no_wrapper {
11377:     my $uri = &clutter(shift);
11378:     if ($uri =~ m-^/adm/-) {
11379: 	$uri =~ s-^/adm/wrapper/-/-;
11380: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11381:     }
11382:     return $uri;
11383: }
11384: 
11385: sub freeze_escape {
11386:     my ($value)=@_;
11387:     if (ref($value)) {
11388: 	$value=&nfreeze($value);
11389: 	return '__FROZEN__'.&escape($value);
11390:     }
11391:     return &escape($value);
11392: }
11393: 
11394: 
11395: sub thaw_unescape {
11396:     my ($value)=@_;
11397:     if ($value =~ /^__FROZEN__/) {
11398: 	substr($value,0,10,undef);
11399: 	$value=&unescape($value);
11400: 	return &thaw($value);
11401:     }
11402:     return &unescape($value);
11403: }
11404: 
11405: sub correct_line_ends {
11406:     my ($result)=@_;
11407:     $$result =~s/\r\n/\n/mg;
11408:     $$result =~s/\r/\n/mg;
11409: }
11410: # ================================================================ Main Program
11411: 
11412: sub goodbye {
11413:    &logthis("Starting Shut down");
11414: #not converted to using infrastruture and probably shouldn't be
11415:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11416: #converted
11417: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11418:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11419: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11420: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11421: #1.1 only
11422: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11423: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11424: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11425: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11426:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11427:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11428:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11429:    &flushcourselogs();
11430:    &logthis("Shutting down");
11431: }
11432: 
11433: sub get_dns {
11434:     my ($url,$func,$ignore_cache) = @_;
11435:     if (!$ignore_cache) {
11436: 	my ($content,$cached)=
11437: 	    &Apache::lonnet::is_cached_new('dns',$url);
11438: 	if ($cached) {
11439: 	    &$func($content);
11440: 	    return;
11441: 	}
11442:     }
11443: 
11444:     my %alldns;
11445:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11446:     foreach my $dns (<$config>) {
11447: 	next if ($dns !~ /^\^(\S*)/x);
11448:         my $line = $1;
11449:         my ($host,$protocol) = split(/:/,$line);
11450:         if ($protocol ne 'https') {
11451:             $protocol = 'http';
11452:         }
11453: 	$alldns{$host} = $protocol;
11454:     }
11455:     while (%alldns) {
11456: 	my ($dns) = keys(%alldns);
11457: 	my $ua=new LWP::UserAgent;
11458:         $ua->timeout(30);
11459: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11460: 	my $response=$ua->request($request);
11461:         delete($alldns{$dns});
11462: 	next if ($response->is_error());
11463: 	my @content = split("\n",$response->content);
11464: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11465: 	&$func(\@content);
11466: 	return;
11467:     }
11468:     close($config);
11469:     my $which = (split('/',$url))[3];
11470:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11471:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11472:     my @content = <$config>;
11473:     &$func(\@content);
11474:     return;
11475: }
11476: # ------------------------------------------------------------ Read domain file
11477: {
11478:     my $loaded;
11479:     my %domain;
11480: 
11481:     sub parse_domain_tab {
11482: 	my ($lines) = @_;
11483: 	foreach my $line (@$lines) {
11484: 	    next if ($line =~ /^(\#|\s*$ )/x);
11485: 
11486: 	    chomp($line);
11487: 	    my ($name,@elements) = split(/:/,$line,9);
11488: 	    my %this_domain;
11489: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11490: 			       'lang_def', 'city', 'longi', 'lati',
11491: 			       'primary') {
11492: 		$this_domain{$field} = shift(@elements);
11493: 	    }
11494: 	    $domain{$name} = \%this_domain;
11495: 	}
11496:     }
11497: 
11498:     sub reset_domain_info {
11499: 	undef($loaded);
11500: 	undef(%domain);
11501:     }
11502: 
11503:     sub load_domain_tab {
11504: 	my ($ignore_cache) = @_;
11505: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11506: 	my $fh;
11507: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11508: 	    my @lines = <$fh>;
11509: 	    &parse_domain_tab(\@lines);
11510: 	}
11511: 	close($fh);
11512: 	$loaded = 1;
11513:     }
11514: 
11515:     sub domain {
11516: 	&load_domain_tab() if (!$loaded);
11517: 
11518: 	my ($name,$what) = @_;
11519: 	return if ( !exists($domain{$name}) );
11520: 
11521: 	if (!$what) {
11522: 	    return $domain{$name}{'description'};
11523: 	}
11524: 	return $domain{$name}{$what};
11525:     }
11526: 
11527:     sub domain_info {
11528:         &load_domain_tab() if (!$loaded);
11529:         return %domain;
11530:     }
11531: 
11532: }
11533: 
11534: 
11535: # ------------------------------------------------------------- Read hosts file
11536: {
11537:     my %hostname;
11538:     my %hostdom;
11539:     my %libserv;
11540:     my $loaded;
11541:     my %name_to_host;
11542:     my %internetdom;
11543:     my %LC_dns_serv;
11544: 
11545:     sub parse_hosts_tab {
11546: 	my ($file) = @_;
11547: 	foreach my $configline (@$file) {
11548: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11549:             chomp($configline);
11550: 	    if ($configline =~ /^\^/) {
11551:                 if ($configline =~ /^\^([\w.\-]+)/) {
11552:                     $LC_dns_serv{$1} = 1;
11553:                 }
11554:                 next;
11555:             }
11556: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11557: 	    $name=~s/\s//g;
11558: 	    if ($id && $domain && $role && $name) {
11559: 		$hostname{$id}=$name;
11560: 		push(@{$name_to_host{$name}}, $id);
11561: 		$hostdom{$id}=$domain;
11562: 		if ($role eq 'library') { $libserv{$id}=$name; }
11563:                 if (defined($protocol)) {
11564:                     if ($protocol eq 'https') {
11565:                         $protocol{$id} = $protocol;
11566:                     } else {
11567:                         $protocol{$id} = 'http'; 
11568:                     }
11569:                 } else {
11570:                     $protocol{$id} = 'http';
11571:                 }
11572:                 if (defined($intdom)) {
11573:                     $internetdom{$id} = $intdom;
11574:                 }
11575: 	    }
11576: 	}
11577:     }
11578:     
11579:     sub reset_hosts_info {
11580: 	&purge_remembered();
11581: 	&reset_domain_info();
11582: 	&reset_hosts_ip_info();
11583: 	undef(%name_to_host);
11584: 	undef(%hostname);
11585: 	undef(%hostdom);
11586: 	undef(%libserv);
11587: 	undef($loaded);
11588:     }
11589: 
11590:     sub load_hosts_tab {
11591: 	my ($ignore_cache) = @_;
11592: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11593: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11594: 	my @config = <$config>;
11595: 	&parse_hosts_tab(\@config);
11596: 	close($config);
11597: 	$loaded=1;
11598:     }
11599: 
11600:     sub hostname {
11601: 	&load_hosts_tab() if (!$loaded);
11602: 
11603: 	my ($lonid) = @_;
11604: 	return $hostname{$lonid};
11605:     }
11606: 
11607:     sub all_hostnames {
11608: 	&load_hosts_tab() if (!$loaded);
11609: 
11610: 	return %hostname;
11611:     }
11612: 
11613:     sub all_names {
11614: 	&load_hosts_tab() if (!$loaded);
11615: 
11616: 	return %name_to_host;
11617:     }
11618: 
11619:     sub all_host_domain {
11620:         &load_hosts_tab() if (!$loaded);
11621:         return %hostdom;
11622:     }
11623: 
11624:     sub is_library {
11625: 	&load_hosts_tab() if (!$loaded);
11626: 
11627: 	return exists($libserv{$_[0]});
11628:     }
11629: 
11630:     sub all_library {
11631: 	&load_hosts_tab() if (!$loaded);
11632: 
11633: 	return %libserv;
11634:     }
11635: 
11636:     sub unique_library {
11637: 	#2x reverse removes all hostnames that appear more than once
11638:         my %unique = reverse &all_library();
11639:         return reverse %unique;
11640:     }
11641: 
11642:     sub get_servers {
11643: 	&load_hosts_tab() if (!$loaded);
11644: 
11645: 	my ($domain,$type) = @_;
11646: 	my %possible_hosts = ($type eq 'library') ? %libserv
11647: 	                                          : %hostname;
11648: 	my %result;
11649: 	if (ref($domain) eq 'ARRAY') {
11650: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11651: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11652: 		    $result{$host} = $hostname;
11653: 		}
11654: 	    }
11655: 	} else {
11656: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11657: 		if ($hostdom{$host} eq $domain) {
11658: 		    $result{$host} = $hostname;
11659: 		}
11660: 	    }
11661: 	}
11662: 	return %result;
11663:     }
11664: 
11665:     sub get_unique_servers {
11666:         my %unique = reverse &get_servers(@_);
11667: 	return reverse %unique;
11668:     }
11669: 
11670:     sub host_domain {
11671: 	&load_hosts_tab() if (!$loaded);
11672: 
11673: 	my ($lonid) = @_;
11674: 	return $hostdom{$lonid};
11675:     }
11676: 
11677:     sub all_domains {
11678: 	&load_hosts_tab() if (!$loaded);
11679: 
11680: 	my %seen;
11681: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11682: 	return @uniq;
11683:     }
11684: 
11685:     sub internet_dom {
11686:         &load_hosts_tab() if (!$loaded);
11687: 
11688:         my ($lonid) = @_;
11689:         return $internetdom{$lonid};
11690:     }
11691: 
11692:     sub is_LC_dns {
11693:         &load_hosts_tab() if (!$loaded);
11694: 
11695:         my ($hostname) = @_;
11696:         return exists($LC_dns_serv{$hostname});
11697:     }
11698: 
11699: }
11700: 
11701: { 
11702:     my %iphost;
11703:     my %name_to_ip;
11704:     my %lonid_to_ip;
11705: 
11706:     sub get_hosts_from_ip {
11707: 	my ($ip) = @_;
11708: 	my %iphosts = &get_iphost();
11709: 	if (ref($iphosts{$ip})) {
11710: 	    return @{$iphosts{$ip}};
11711: 	}
11712: 	return;
11713:     }
11714:     
11715:     sub reset_hosts_ip_info {
11716: 	undef(%iphost);
11717: 	undef(%name_to_ip);
11718: 	undef(%lonid_to_ip);
11719:     }
11720: 
11721:     sub get_host_ip {
11722: 	my ($lonid) = @_;
11723: 	if (exists($lonid_to_ip{$lonid})) {
11724: 	    return $lonid_to_ip{$lonid};
11725: 	}
11726: 	my $name=&hostname($lonid);
11727:    	my $ip = gethostbyname($name);
11728: 	return if (!$ip || length($ip) ne 4);
11729: 	$ip=inet_ntoa($ip);
11730: 	$name_to_ip{$name}   = $ip;
11731: 	$lonid_to_ip{$lonid} = $ip;
11732: 	return $ip;
11733:     }
11734:     
11735:     sub get_iphost {
11736: 	my ($ignore_cache) = @_;
11737: 
11738: 	if (!$ignore_cache) {
11739: 	    if (%iphost) {
11740: 		return %iphost;
11741: 	    }
11742: 	    my ($ip_info,$cached)=
11743: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11744: 	    if ($cached) {
11745: 		%iphost      = %{$ip_info->[0]};
11746: 		%name_to_ip  = %{$ip_info->[1]};
11747: 		%lonid_to_ip = %{$ip_info->[2]};
11748: 		return %iphost;
11749: 	    }
11750: 	}
11751: 
11752: 	# get yesterday's info for fallback
11753: 	my %old_name_to_ip;
11754: 	my ($ip_info,$cached)=
11755: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11756: 	if ($cached) {
11757: 	    %old_name_to_ip = %{$ip_info->[1]};
11758: 	}
11759: 
11760: 	my %name_to_host = &all_names();
11761: 	foreach my $name (keys(%name_to_host)) {
11762: 	    my $ip;
11763: 	    if (!exists($name_to_ip{$name})) {
11764: 		$ip = gethostbyname($name);
11765: 		if (!$ip || length($ip) ne 4) {
11766: 		    if (defined($old_name_to_ip{$name})) {
11767: 			$ip = $old_name_to_ip{$name};
11768: 			&logthis("Can't find $name defaulting to old $ip");
11769: 		    } else {
11770: 			&logthis("Name $name no IP found");
11771: 			next;
11772: 		    }
11773: 		} else {
11774: 		    $ip=inet_ntoa($ip);
11775: 		}
11776: 		$name_to_ip{$name} = $ip;
11777: 	    } else {
11778: 		$ip = $name_to_ip{$name};
11779: 	    }
11780: 	    foreach my $id (@{ $name_to_host{$name} }) {
11781: 		$lonid_to_ip{$id} = $ip;
11782: 	    }
11783: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11784: 	}
11785: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11786: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11787: 				      48*60*60);
11788: 
11789: 	return %iphost;
11790:     }
11791: 
11792:     #
11793:     #  Given a DNS returns the loncapa host name for that DNS 
11794:     # 
11795:     sub host_from_dns {
11796:         my ($dns) = @_;
11797:         my @hosts;
11798:         my $ip;
11799: 
11800:         if (exists($name_to_ip{$dns})) {
11801:             $ip = $name_to_ip{$dns};
11802:         }
11803:         if (!$ip) {
11804:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11805:             if (length($ip) == 4) { 
11806: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11807:             }
11808:         }
11809:         if ($ip) {
11810: 	    @hosts = get_hosts_from_ip($ip);
11811: 	    return $hosts[0];
11812:         }
11813:         return undef;
11814:     }
11815: 
11816:     sub get_internet_names {
11817:         my ($lonid) = @_;
11818:         return if ($lonid eq '');
11819:         my ($idnref,$cached)=
11820:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11821:         if ($cached) {
11822:             return $idnref;
11823:         }
11824:         my $ip = &get_host_ip($lonid);
11825:         my @hosts = &get_hosts_from_ip($ip);
11826:         my %iphost = &get_iphost();
11827:         my (@idns,%seen);
11828:         foreach my $id (@hosts) {
11829:             my $dom = &host_domain($id);
11830:             my $prim_id = &domain($dom,'primary');
11831:             my $prim_ip = &get_host_ip($prim_id);
11832:             next if ($seen{$prim_ip});
11833:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11834:                 foreach my $id (@{$iphost{$prim_ip}}) {
11835:                     my $intdom = &internet_dom($id);
11836:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11837:                         push(@idns,$intdom);
11838:                     }
11839:                 }
11840:             }
11841:             $seen{$prim_ip} = 1;
11842:         }
11843:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11844:     }
11845: 
11846: }
11847: 
11848: sub all_loncaparevs {
11849:     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);
11850: }
11851: 
11852: BEGIN {
11853: 
11854: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11855:     unless ($readit) {
11856: {
11857:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11858:     %perlvar = (%perlvar,%{$configvars});
11859: }
11860: 
11861: 
11862: # ------------------------------------------------------ Read spare server file
11863: {
11864:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11865: 
11866:     while (my $configline=<$config>) {
11867:        chomp($configline);
11868:        if ($configline) {
11869: 	   my ($host,$type) = split(':',$configline,2);
11870: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11871: 	   push(@{ $spareid{$type} }, $host);
11872:        }
11873:     }
11874:     close($config);
11875: }
11876: # ------------------------------------------------------------ Read permissions
11877: {
11878:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11879: 
11880:     while (my $configline=<$config>) {
11881: 	chomp($configline);
11882: 	if ($configline) {
11883: 	    my ($role,$perm)=split(/ /,$configline);
11884: 	    if ($perm ne '') { $pr{$role}=$perm; }
11885: 	}
11886:     }
11887:     close($config);
11888: }
11889: 
11890: # -------------------------------------------- Read plain texts for permissions
11891: {
11892:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11893: 
11894:     while (my $configline=<$config>) {
11895: 	chomp($configline);
11896: 	if ($configline) {
11897: 	    my ($short,@plain)=split(/:/,$configline);
11898:             %{$prp{$short}} = ();
11899: 	    if (@plain > 0) {
11900:                 $prp{$short}{'std'} = $plain[0];
11901:                 for (my $i=1; $i<@plain; $i++) {
11902:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11903:                 }
11904:             }
11905: 	}
11906:     }
11907:     close($config);
11908: }
11909: 
11910: # ---------------------------------------------------------- Read package table
11911: {
11912:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11913: 
11914:     while (my $configline=<$config>) {
11915: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11916: 	chomp($configline);
11917: 	my ($short,$plain)=split(/:/,$configline);
11918: 	my ($pack,$name)=split(/\&/,$short);
11919: 	if ($plain ne '') {
11920: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11921: 	    $packagetab{$short}=$plain; 
11922: 	}
11923:     }
11924:     close($config);
11925: }
11926: 
11927: # ---------------------------------------------------------- Read loncaparev table
11928: {
11929:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11930:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11931:             while (my $configline=<$config>) {
11932:                 chomp($configline);
11933:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11934:                 $loncaparevs{$hostid}=$loncaparev;
11935:             }
11936:             close($config);
11937:         }
11938:     }
11939: }
11940: 
11941: # ---------------------------------------------------------- Read serverhostID table
11942: {
11943:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11944:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11945:             while (my $configline=<$config>) {
11946:                 chomp($configline);
11947:                 my ($name,$id)=split(/:/,$configline);
11948:                 $serverhomeIDs{$name}=$id;
11949:             }
11950:             close($config);
11951:         }
11952:     }
11953: }
11954: 
11955: {
11956:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11957:     if (-e $file) {
11958:         my $parser = HTML::LCParser->new($file);
11959:         while (my $token = $parser->get_token()) {
11960:             if ($token->[0] eq 'S') {
11961:                 my $item = $token->[1];
11962:                 my $name = $token->[2]{'name'};
11963:                 my $value = $token->[2]{'value'};
11964:                 if ($item ne '' && $name ne '' && $value ne '') {
11965:                     my $release = $parser->get_text();
11966:                     $release =~ s/(^\s*|\s*$ )//gx;
11967:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11968:                 }
11969:             }
11970:         }
11971:     }
11972: }
11973: 
11974: # ---------------------------------------------------------- Read managers table
11975: {
11976:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11977:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11978:             while (my $configline=<$config>) {
11979:                 chomp($configline);
11980:                 next if ($configline =~ /^\#/);
11981:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11982:                     $managerstab{$configline} = 1;
11983:                 }
11984:             }
11985:             close($config);
11986:         }
11987:     }
11988: }
11989: 
11990: # ------------- set up temporary directory
11991: {
11992:     $tmpdir = LONCAPA::tempdir();
11993: 
11994: }
11995: 
11996: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11997: 				'compress_threshold'=> 20_000,
11998:  			        });
11999: 
12000: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12001: $dumpcount=0;
12002: $locknum=0;
12003: 
12004: &logtouch();
12005: &logthis('<font color="yellow">INFO: Read configuration</font>');
12006: $readit=1;
12007:     {
12008: 	use integer;
12009: 	my $test=(2**32)+1;
12010: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12011: 	&logthis(" Detected 64bit platform ($_64bit)");
12012:     }
12013: }
12014: }
12015: 
12016: 1;
12017: __END__
12018: 
12019: =pod
12020: 
12021: =head1 NAME
12022: 
12023: Apache::lonnet - Subroutines to ask questions about things in the network.
12024: 
12025: =head1 SYNOPSIS
12026: 
12027: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12028: 
12029:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12030: 
12031: Common parameters:
12032: 
12033: =over 4
12034: 
12035: =item *
12036: 
12037: $uname : an internal username (if $cname expecting a course Id specifically)
12038: 
12039: =item *
12040: 
12041: $udom : a domain (if $cdom expecting a course's domain specifically)
12042: 
12043: =item *
12044: 
12045: $symb : a resource instance identifier
12046: 
12047: =item *
12048: 
12049: $namespace : the name of a .db file that contains the data needed or
12050: being set.
12051: 
12052: =back
12053: 
12054: =head1 OVERVIEW
12055: 
12056: lonnet provides subroutines which interact with the
12057: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12058: about classes, users, and resources.
12059: 
12060: For many of these objects you can also use this to store data about
12061: them or modify them in various ways.
12062: 
12063: =head2 Symbs
12064: 
12065: To identify a specific instance of a resource, LON-CAPA uses symbols
12066: or "symbs"X<symb>. These identifiers are built from the URL of the
12067: map, the resource number of the resource in the map, and the URL of
12068: the resource itself. The latter is somewhat redundant, but might help
12069: if maps change.
12070: 
12071: An example is
12072: 
12073:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12074: 
12075: The respective map entry is
12076: 
12077:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12078:   title="Problem 2">
12079:  </resource>
12080: 
12081: Symbs are used by the random number generator, as well as to store and
12082: restore data specific to a certain instance of for example a problem.
12083: 
12084: =head2 Storing And Retrieving Data
12085: 
12086: X<store()>X<cstore()>X<restore()>Three of the most important functions
12087: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12088: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12089: is is the non-critical message twin of cstore. These functions are for
12090: handlers to store a perl hash to a user's permanent data space in an
12091: easy manner, and to retrieve it again on another call. It is expected
12092: that a handler would use this once at the beginning to retrieve data,
12093: and then again once at the end to send only the new data back.
12094: 
12095: The data is stored in the user's data directory on the user's
12096: homeserver under the ID of the course.
12097: 
12098: The hash that is returned by restore will have all of the previous
12099: value for all of the elements of the hash.
12100: 
12101: Example:
12102: 
12103:  #creating a hash
12104:  my %hash;
12105:  $hash{'foo'}='bar';
12106: 
12107:  #storing it
12108:  &Apache::lonnet::cstore(\%hash);
12109: 
12110:  #changing a value
12111:  $hash{'foo'}='notbar';
12112: 
12113:  #adding a new value
12114:  $hash{'bar'}='foo';
12115:  &Apache::lonnet::cstore(\%hash);
12116: 
12117:  #retrieving the hash
12118:  my %history=&Apache::lonnet::restore();
12119: 
12120:  #print the hash
12121:  foreach my $key (sort(keys(%history))) {
12122:    print("\%history{$key} = $history{$key}");
12123:  }
12124: 
12125: Will print out:
12126: 
12127:  %history{1:foo} = bar
12128:  %history{1:keys} = foo:timestamp
12129:  %history{1:timestamp} = 990455579
12130:  %history{2:bar} = foo
12131:  %history{2:foo} = notbar
12132:  %history{2:keys} = foo:bar:timestamp
12133:  %history{2:timestamp} = 990455580
12134:  %history{bar} = foo
12135:  %history{foo} = notbar
12136:  %history{timestamp} = 990455580
12137:  %history{version} = 2
12138: 
12139: Note that the special hash entries C<keys>, C<version> and
12140: C<timestamp> were added to the hash. C<version> will be equal to the
12141: total number of versions of the data that have been stored. The
12142: C<timestamp> attribute will be the UNIX time the hash was
12143: stored. C<keys> is available in every historical section to list which
12144: keys were added or changed at a specific historical revision of a
12145: hash.
12146: 
12147: B<Warning>: do not store the hash that restore returns directly. This
12148: will cause a mess since it will restore the historical keys as if the
12149: were new keys. I.E. 1:foo will become 1:1:foo etc.
12150: 
12151: Calling convention:
12152: 
12153:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12154:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12155: 
12156: For more detailed information, see lonnet specific documentation.
12157: 
12158: =head1 RETURN MESSAGES
12159: 
12160: =over 4
12161: 
12162: =item * B<con_lost>: unable to contact remote host
12163: 
12164: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12165: when the connection is brought back up
12166: 
12167: =item * B<con_failed>: unable to contact remote host and unable to save message
12168: for later delivery
12169: 
12170: =item * B<error:>: an error a occurred, a description of the error follows the :
12171: 
12172: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12173: that was requested
12174: 
12175: =back
12176: 
12177: =head1 PUBLIC SUBROUTINES
12178: 
12179: =head2 Session Environment Functions
12180: 
12181: =over 4
12182: 
12183: =item * 
12184: X<appenv()>
12185: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12186: the user envirnoment file, and will be restored for each access this
12187: user makes during this session, also modifies the %env for the current
12188: process. Optional rolesarrayref - if defined contains a reference to an array
12189: of roles which are exempt from the restriction on modifying user.role entries 
12190: in the user's environment.db and in %env.    
12191: 
12192: =item *
12193: X<delenv()>
12194: B<delenv($delthis,$regexp)>: removes all items from the session
12195: environment file that begin with $delthis. If the 
12196: optional second arg - $regexp - is true, $delthis is treated as a 
12197: regular expression, otherwise \Q$delthis\E is used. 
12198: The values are also deleted from the current processes %env.
12199: 
12200: =item * get_env_multiple($name) 
12201: 
12202: gets $name from the %env hash, it seemlessly handles the cases where multiple
12203: values may be defined and end up as an array ref.
12204: 
12205: returns an array of values
12206: 
12207: =back
12208: 
12209: =head2 User Information
12210: 
12211: =over 4
12212: 
12213: =item *
12214: X<queryauthenticate()>
12215: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12216: authentication scheme
12217: 
12218: =item *
12219: X<authenticate()>
12220: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12221: authenticate user from domain's lib servers (first use the current
12222: one). C<$upass> should be the users password.
12223: $checkdefauth is optional (value is 1 if a check should be made to
12224:    authenticate user using default authentication method, and allow
12225:    account creation if username does not have account in the domain).
12226: $clientcancheckhost is optional (value is 1 if checking whether the
12227:    server can host will occur on the client side in lonauth.pm).   
12228: 
12229: =item *
12230: X<homeserver()>
12231: B<homeserver($uname,$udom)>: find the server which has
12232: the user's directory and files (there must be only one), this caches
12233: the answer, and also caches if there is a borken connection.
12234: 
12235: =item *
12236: X<idget()>
12237: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12238: (IDs are a unique resource in a domain, there must be only 1 ID per
12239: username, and only 1 username per ID in a specific domain) (returns
12240: hash: id=>name,id=>name)
12241: 
12242: =item *
12243: X<idrget()>
12244: B<idrget($udom,@unames)>: find the IDs behind a list of
12245: usernames (returns hash: name=>id,name=>id)
12246: 
12247: =item *
12248: X<idput()>
12249: B<idput($udom,%ids)>: store away a list of names and associated IDs
12250: 
12251: =item *
12252: X<rolesinit()>
12253: B<rolesinit($udom,$username)>: get user privileges.
12254: returns user role, first access and timer interval hashes
12255: 
12256: =item *
12257: X<privileged()>
12258: B<privileged($username,$domain)>: returns a true if user has a
12259: privileged and active role (i.e. su or dc), false otherwise.
12260: 
12261: =item *
12262: X<getsection()>
12263: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12264: course $cname, return section name/number or '' for "not in course"
12265: and '-1' for "no section"
12266: 
12267: =item *
12268: X<userenvironment()>
12269: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12270: passed in @what from the requested user's environment, returns a hash
12271: 
12272: =item * 
12273: X<userlog_query()>
12274: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12275: activity.log file. %filters defines filters applied when parsing the
12276: log file. These can be start or end timestamps, or the type of action
12277: - log to look for Login or Logout events, check for Checkin or
12278: Checkout, role for role selection. The response is in the form
12279: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12280: escaped strings of the action recorded in the activity.log file.
12281: 
12282: =back
12283: 
12284: =head2 User Roles
12285: 
12286: =over 4
12287: 
12288: =item *
12289: 
12290: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12291:  F: full access
12292:  U,I,K: authentication modes (cxx only)
12293:  '': forbidden
12294:  1: user needs to choose course
12295:  2: browse allowed
12296:  A: passphrase authentication needed
12297: 
12298: =item *
12299: 
12300: constructaccess($url,$setpriv) : check for access to construction space URL
12301: 
12302: See if the owner domain and name in the URL match those in the
12303: expected environment.  If so, return three element list
12304: ($ownername,$ownerdomain,$ownerhome).
12305: 
12306: Otherwise return the null string.
12307: 
12308: If second argument 'setpriv' is true, it assigns the privileges,
12309: and returns the same three element list, unless the owner has
12310: blocked "ad hoc" Domain Coordinator access to the Author Space,
12311: in which case the null string is returned.
12312: 
12313: =item *
12314: 
12315: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12316: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12317: and course level
12318: 
12319: =item *
12320: 
12321: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12322: (rolesplain.tab); plain text explanation of a user role term.
12323: $type is Course (default) or Community.
12324: If $forcedefault evaluates to true, text returned will be default 
12325: text for $type. Otherwise, if this is a course, the text returned 
12326: will be a custom name for the role (if defined in the course's 
12327: environment).  If no custom name is defined the default is returned.
12328:    
12329: =item *
12330: 
12331: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12332: All arguments are optional. Returns a hash of a roles, either for
12333: co-author/assistant author roles for a user's Construction Space
12334: (default), or if $context is 'userroles', roles for the user himself,
12335: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12336: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12337: For each key, value is set to colon-separated start and end times for
12338: the role.  If no username and domain are specified, will default to
12339: current user/domain. Types, roles, and roledoms are references to arrays
12340: of role statuses (active, future or previous), roles 
12341: (e.g., cc,in, st etc.) and domains of the roles which can be used
12342: to restrict the list of roles reported. If no array ref is 
12343: provided for types, will default to return only active roles.
12344: 
12345: =item *
12346: 
12347: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12348: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12349: 
12350: Additional optional arguments are: $type (if role checking is to be restricted 
12351: to certain user status types -- previous (expired roles), active (currently
12352: available roles) or future (roles available in the future), and
12353: $hideprivileged -- if true will not report course roles for users who
12354: have active Domain Coordinator or Super User roles.
12355: 
12356: =back
12357: 
12358: =head2 User Modification
12359: 
12360: =over 4
12361: 
12362: =item *
12363: 
12364: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12365: user for the level given by URL.  Optional start and end dates (leave empty
12366: string or zero for "no date")
12367: 
12368: =item *
12369: 
12370: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12371: change a users, password, possible return values are: ok,
12372: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12373: refused
12374: 
12375: =item *
12376: 
12377: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12378: 
12379: =item *
12380: 
12381: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12382:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12383: 
12384: will update user information (firstname,middlename,lastname,generation,
12385: permanentemail), and if forceid is true, student/employee ID also.
12386: A user's institutional affiliation(s) can also be updated.
12387: User information fields will not be overwritten with empty entries 
12388: unless the field is included in the $candelete array reference.
12389: This array is included when a single user is modified via "Manage Users",
12390: or when Autoupdate.pl is run by cron in a domain.
12391: 
12392: =item *
12393: 
12394: modifystudent
12395: 
12396: modify a student's enrollment and identification information.
12397: The course id is resolved based on the current users environment.  
12398: This means the envoking user must be a course coordinator or otherwise
12399: associated with a course.
12400: 
12401: This call is essentially a wrapper for lonnet::modifyuser and
12402: lonnet::modify_student_enrollment
12403: 
12404: Inputs: 
12405: 
12406: =over 4
12407: 
12408: =item B<$udom> Student's loncapa domain
12409: 
12410: =item B<$uname> Student's loncapa login name
12411: 
12412: =item B<$uid> Student/Employee ID
12413: 
12414: =item B<$umode> Student's authentication mode
12415: 
12416: =item B<$upass> Student's password
12417: 
12418: =item B<$first> Student's first name
12419: 
12420: =item B<$middle> Student's middle name
12421: 
12422: =item B<$last> Student's last name
12423: 
12424: =item B<$gene> Student's generation
12425: 
12426: =item B<$usec> Student's section in course
12427: 
12428: =item B<$end> Unix time of the roles expiration
12429: 
12430: =item B<$start> Unix time of the roles start date
12431: 
12432: =item B<$forceid> If defined, allow $uid to be changed
12433: 
12434: =item B<$desiredhome> server to use as home server for student
12435: 
12436: =item B<$email> Student's permanent e-mail address
12437: 
12438: =item B<$type> Type of enrollment (auto or manual)
12439: 
12440: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12441: 
12442: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12443: 
12444: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12445: 
12446: =item B<$context> role change context (shown in User Management Logs display in a course)
12447: 
12448: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12449: 
12450: =back
12451: 
12452: =item *
12453: 
12454: modify_student_enrollment
12455: 
12456: Change a students enrollment status in a class.  The environment variable
12457: 'role.request.course' must be defined for this function to proceed.
12458: 
12459: Inputs:
12460: 
12461: =over 4
12462: 
12463: =item $udom, students domain
12464: 
12465: =item $uname, students name
12466: 
12467: =item $uid, students user id
12468: 
12469: =item $first, students first name
12470: 
12471: =item $middle
12472: 
12473: =item $last
12474: 
12475: =item $gene
12476: 
12477: =item $usec
12478: 
12479: =item $end
12480: 
12481: =item $start
12482: 
12483: =item $type
12484: 
12485: =item $locktype
12486: 
12487: =item $cid
12488: 
12489: =item $selfenroll
12490: 
12491: =item $context
12492: 
12493: =back
12494: 
12495: 
12496: =item *
12497: 
12498: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12499: custom role; give a custom role to a user for the level given by URL.  Specify
12500: name and domain of role author, and role name
12501: 
12502: =item *
12503: 
12504: revokerole($udom,$uname,$url,$role) : revoke a role for url
12505: 
12506: =item *
12507: 
12508: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12509: 
12510: =back
12511: 
12512: =head2 Course Infomation
12513: 
12514: =over 4
12515: 
12516: =item *
12517: 
12518: coursedescription($courseid,$options) : returns a hash of information about the
12519: specified course id, including all environment settings for the
12520: course, the description of the course will be in the hash under the
12521: key 'description'
12522: 
12523: $options is an optional parameter that if supplied is a hash reference that controls
12524: what how this function works.  It has the following key/values:
12525: 
12526: =over 4
12527: 
12528: =item freshen_cache
12529: 
12530: If defined, and the environment cache for the course is valid, it is 
12531: returned in the returned hash.
12532: 
12533: =item one_time
12534: 
12535: If defined, the last cache time is set to _now_
12536: 
12537: =item user
12538: 
12539: If defined, the supplied username is used instead of the current user.
12540: 
12541: 
12542: =back
12543: 
12544: =item *
12545: 
12546: resdata($name,$domain,$type,@which) : request for current parameter
12547: setting for a specific $type, where $type is either 'course' or 'user',
12548: @what should be a list of parameters to ask about. This routine caches
12549: answers for 5 minutes.
12550: 
12551: =item *
12552: 
12553: get_courseresdata($courseid, $domain) : dump the entire course resource
12554: data base, returning a hash that is keyed by the resource name and has
12555: values that are the resource value.  I believe that the timestamps and
12556: versions are also returned.
12557: 
12558: =back
12559: 
12560: =head2 Course Modification
12561: 
12562: =over 4
12563: 
12564: =item *
12565: 
12566: writecoursepref($courseid,%prefs) : write preferences (environment
12567: database) for a course
12568: 
12569: =item *
12570: 
12571: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12572: 
12573: =item *
12574: 
12575: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12576: 
12577: =item *
12578: 
12579: is_course($courseid), is_course($cdom, $cnum)
12580: 
12581: Accepts either a combined $courseid (in the form of domain_courseid) or the
12582: two component version $cdom, $cnum. It checks if the specified course exists.
12583: 
12584: Returns:
12585:     undef if the course doesn't exist, otherwise
12586:     in scalar context the combined courseid.
12587:     in list context the two components of the course identifier, domain and 
12588:     courseid.    
12589: 
12590: =back
12591: 
12592: =head2 Resource Subroutines
12593: 
12594: =over 4
12595: 
12596: =item *
12597: 
12598: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12599: 
12600: =item *
12601: 
12602: repcopy($filename) : subscribes to the requested file, and attempts to
12603: replicate from the owning library server, Might return
12604: 'unavailable', 'not_found', 'forbidden', 'ok', or
12605: 'bad_request', also attempts to grab the metadata for the
12606: resource. Expects the local filesystem pathname
12607: (/home/httpd/html/res/....)
12608: 
12609: =back
12610: 
12611: =head2 Resource Information
12612: 
12613: =over 4
12614: 
12615: =item *
12616: 
12617: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12618: a vairety of different possible values, $varname should be a request
12619: string, and the other parameters can be used to specify who and what
12620: one is asking about.
12621: 
12622: Possible values for $varname are environment.lastname (or other item
12623: from the envirnment hash), user.name (or someother aspect about the
12624: user), resource.0.maxtries (or some other part and parameter of a
12625: resource)
12626: 
12627: =item *
12628: 
12629: directcondval($number) : get current value of a condition; reads from a state
12630: string
12631: 
12632: =item *
12633: 
12634: condval($condidx) : value of condition index based on state
12635: 
12636: =item *
12637: 
12638: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12639: resource's metadata, $what should be either a specific key, or either
12640: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12641: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12642: 
12643: this function automatically caches all requests
12644: 
12645: =item *
12646: 
12647: metadata_query($query,$custom,$customshow) : make a metadata query against the
12648: network of library servers; returns file handle of where SQL and regex results
12649: will be stored for query
12650: 
12651: =item *
12652: 
12653: symbread($filename) : return symbolic list entry (filename argument optional);
12654: returns the data handle
12655: 
12656: =item *
12657: 
12658: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12659: and is a possible symb for the URL in $thisfn, and if is an encrypted
12660: resource that the user accessed using /enc/ returns a 1 on success, 0
12661: on failure, user must be in a course, as it assumes the existence of
12662: the course initial hash, and uses $env('request.course.id'}.  The third
12663: arg is an optional reference to a scalar.  If this arg is passed in the 
12664: call to symbverify, it will be set to 1 if the symb has been set to be 
12665: encrypted; otherwise it will be null.  
12666: 
12667: =item *
12668: 
12669: symbclean($symb) : removes versions numbers from a symb, returns the
12670: cleaned symb
12671: 
12672: =item *
12673: 
12674: is_on_map($uri) : checks if the $uri is somewhere on the current
12675: course map, user must be in a course for it to work.
12676: 
12677: =item *
12678: 
12679: numval($salt) : return random seed value (addend for rndseed)
12680: 
12681: =item *
12682: 
12683: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12684: a random seed, all arguments are optional, if they aren't sent it uses the
12685: environment to derive them. Note: if symb isn't sent and it can't get one
12686: from &symbread it will use the current time as its return value
12687: 
12688: =item *
12689: 
12690: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12691: unfakeable, receipt
12692: 
12693: =item *
12694: 
12695: receipt() : API to ireceipt working off of env values; given out to users
12696: 
12697: =item *
12698: 
12699: countacc($url) : count the number of accesses to a given URL
12700: 
12701: =item *
12702: 
12703: 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
12704: 
12705: =item *
12706: 
12707: 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)
12708: 
12709: =item *
12710: 
12711: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12712: 
12713: =item *
12714: 
12715: devalidate($symb) : devalidate temporary spreadsheet calculations,
12716: forcing spreadsheet to reevaluate the resource scores next time.
12717: 
12718: =item * 
12719: 
12720: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12721: when viewing in course context.
12722: 
12723:  input: six args -- filename (decluttered), course number, course domain,
12724:                     url, symb (if registered) and group (if this is a 
12725:                     group item -- e.g., bulletin board, group page etc.).
12726: 
12727:  output: array of five scalars --
12728:          $cfile -- url for file editing if editable on current server
12729:          $home -- homeserver of resource (i.e., for author if published,
12730:                                           or course if uploaded.).
12731:          $switchserver --  1 if server switch will be needed.
12732:          $forceedit -- 1 if icon/link should be to go to edit mode 
12733:          $forceview -- 1 if icon/link should be to go to view mode
12734: 
12735: =item *
12736: 
12737: is_course_upload($file,$cnum,$cdom)
12738: 
12739: Used in course context to determine if current file was uploaded to 
12740: the course (i.e., would be found in /userfiles/docs on the course's 
12741: homeserver.
12742: 
12743:   input: 3 args -- filename (decluttered), course number and course domain.
12744:   output: boolean -- 1 if file was uploaded.
12745: 
12746: =back
12747: 
12748: =head2 Storing/Retreiving Data
12749: 
12750: =over 4
12751: 
12752: =item *
12753: 
12754: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12755: for this url; hashref needs to be given and should be a \%hashname; the
12756: remaining args aren't required and if they aren't passed or are '' they will
12757: be derived from the env
12758: 
12759: =item *
12760: 
12761: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12762: uses critical subroutine
12763: 
12764: =item *
12765: 
12766: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12767: all args are optional
12768: 
12769: =item *
12770: 
12771: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12772: dumps the complete (or key matching regexp) namespace into a hash
12773: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12774: normally &store()ed into
12775: 
12776: $range should be either an integer '100' (give me the first 100
12777:                                            matching records)
12778:               or be  two integers sperated by a - with no spaces
12779:                  '30-50' (give me the 30th through the 50th matching
12780:                           records)
12781: 
12782: 
12783: =item *
12784: 
12785: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12786: replaces a &store() version of data with a replacement set of data
12787: for a particular resource in a namespace passed in the $storehash hash 
12788: reference
12789: 
12790: =item *
12791: 
12792: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12793: works very similar to store/cstore, but all data is stored in a
12794: temporary location and can be reset using tmpreset, $storehash should
12795: be a hash reference, returns nothing on success
12796: 
12797: =item *
12798: 
12799: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12800: similar to restore, but all data is stored in a temporary location and
12801: can be reset using tmpreset. Returns a hash of values on success,
12802: error string otherwise.
12803: 
12804: =item *
12805: 
12806: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12807: deltes all keys for $symb form the temporary storage hash.
12808: 
12809: =item *
12810: 
12811: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12812: reference filled in from namesp ($udom and $uname are optional)
12813: 
12814: =item *
12815: 
12816: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12817: namesp ($udom and $uname are optional)
12818: 
12819: =item *
12820: 
12821: dump($namespace,$udom,$uname,$regexp,$range) : 
12822: dumps the complete (or key matching regexp) namespace into a hash
12823: ($udom, $uname, $regexp, $range are optional)
12824: 
12825: $range should be either an integer '100' (give me the first 100
12826:                                            matching records)
12827:               or be  two integers sperated by a - with no spaces
12828:                  '30-50' (give me the 30th through the 50th matching
12829:                           records)
12830: =item *
12831: 
12832: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12833: $store can be a scalar, an array reference, or if the amount to be 
12834: incremented is > 1, a hash reference.
12835: 
12836: ($udom and $uname are optional)
12837: 
12838: =item *
12839: 
12840: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12841: ($udom and $uname are optional)
12842: 
12843: =item *
12844: 
12845: cput($namespace,$storehash,$udom,$uname) : critical put
12846: ($udom and $uname are optional)
12847: 
12848: =item *
12849: 
12850: newput($namespace,$storehash,$udom,$uname) :
12851: 
12852: Attempts to store the items in the $storehash, but only if they don't
12853: currently exist, if this succeeds you can be certain that you have 
12854: successfully created a new key value pair in the $namespace db.
12855: 
12856: 
12857: Args:
12858:  $namespace: name of database to store values to
12859:  $storehash: hashref to store to the db
12860:  $udom: (optional) domain of user containing the db
12861:  $uname: (optional) name of user caontaining the db
12862: 
12863: Returns:
12864:  'ok' -> succeeded in storing all keys of $storehash
12865:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12866:                         least <key> already existed in the db (other
12867:                         requested keys may also already exist)
12868:  'error: <msg>' -> unable to tie the DB or other error occurred
12869:  'con_lost' -> unable to contact request server
12870:  'refused' -> action was not allowed by remote machine
12871: 
12872: 
12873: =item *
12874: 
12875: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12876: reference filled in from namesp (encrypts the return communication)
12877: ($udom and $uname are optional)
12878: 
12879: =item *
12880: 
12881: log($udom,$name,$home,$message) : write to permanent log for user; use
12882: critical subroutine
12883: 
12884: =item *
12885: 
12886: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12887: array reference filled in from namespace found in domain level on either
12888: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12889: 
12890: =item *
12891: 
12892: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12893: domain level either on specified domain server ($uhome) or primary domain 
12894: server ($udom and $uhome are optional)
12895: 
12896: =item * 
12897: 
12898: get_domain_defaults($target_domain) : returns hash with defaults for
12899: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12900: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12901: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12902: Values are retrieved from cache (if current), or from domain's configuration.db
12903: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12904: or lonTabs/domain.tab. 
12905: 
12906: %domdefaults = &get_auth_defaults($target_domain);
12907: 
12908: =back
12909: 
12910: =head2 Network Status Functions
12911: 
12912: =over 4
12913: 
12914: =item *
12915: 
12916: dirlist() : return directory list based on URI (first arg).
12917: 
12918: Inputs: 1 required, 5 optional.
12919: 
12920: =over
12921: 
12922: =item 
12923: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12924: 
12925: =item
12926: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12927: 
12928: =item
12929: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12930: 
12931: =item
12932: $getpropath - boolean: 1 if prepend path using &propath(). 
12933: 
12934: =item
12935: $getuserdir - boolean: 1 if prepend path for "userfiles".
12936: 
12937: =item 
12938: $alternateRoot - path to prepend in place of path from $uri.
12939: 
12940: =back
12941: 
12942: Returns: Array of up to two items.
12943: 
12944: =over
12945: 
12946: a reference to an array of files/subdirectories
12947: 
12948: =over
12949: 
12950: Each element in the array of files/subdirectories is a & separated list of
12951: item name and the result of running stat on the item.  If dirlist was requested
12952: for a file instead of a directory, the item name will be ''. For a directory 
12953: listing, if the item is a metadata file, the element will end &N&M 
12954: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12955: default copyright set (1).  
12956: 
12957: =back
12958: 
12959: a scalar containing error condition (if encountered).
12960: 
12961: =over
12962: 
12963: =item 
12964: no_host (no homeserver identified for $username:$domain).
12965: 
12966: =item 
12967: no_such_host (server contacted for listing not identified as valid host).
12968: 
12969: =item 
12970: con_lost (connection to remote server failed).
12971: 
12972: =item 
12973: refused (invalid $username:$domain received on lond side).
12974: 
12975: =item 
12976: no_such_dir (directory at specified path on lond side does not exist). 
12977: 
12978: =item 
12979: empty (directory at specified path on lond side is empty).
12980: 
12981: =over
12982: 
12983: This is currently not encountered because the &ls3, &ls2, 
12984: &ls (_handler) routines on the lond side do not filter out
12985: . and .. from a directory listing. 
12986: 
12987: =back
12988: 
12989: =back
12990: 
12991: =back
12992: 
12993: =item *
12994: 
12995: spareserver() : find server with least workload from spare.tab
12996: 
12997: 
12998: =item *
12999: 
13000: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13001: if there is no corresponding loncapa host.
13002: 
13003: =back
13004: 
13005: 
13006: =head2 Apache Request
13007: 
13008: =over 4
13009: 
13010: =item *
13011: 
13012: ssi($url,%hash) : server side include, does a complete request cycle on url to
13013: localhost, posts hash
13014: 
13015: =back
13016: 
13017: =head2 Data to String to Data
13018: 
13019: =over 4
13020: 
13021: =item *
13022: 
13023: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13024: and '&' separators, supports elements that are arrayrefs and hashrefs
13025: 
13026: =item *
13027: 
13028: hashref2str($hashref) : convert a hashref into a string complete with
13029: escaping and '=' and '&' separators, supports elements that are
13030: arrayrefs and hashrefs
13031: 
13032: =item *
13033: 
13034: arrayref2str($arrayref) : convert an arrayref into a string complete
13035: with escaping and '&' separators, supports elements that are arrayrefs
13036: and hashrefs
13037: 
13038: =item *
13039: 
13040: str2hash($string) : convert string to hash using unescaping and
13041: splitting on '=' and '&', supports elements that are arrayrefs and
13042: hashrefs
13043: 
13044: =item *
13045: 
13046: str2array($string) : convert string to hash using unescaping and
13047: splitting on '&', supports elements that are arrayrefs and hashrefs
13048: 
13049: =back
13050: 
13051: =head2 Logging Routines
13052: 
13053: 
13054: These routines allow one to make log messages in the lonnet.log and
13055: lonnet.perm logfiles.
13056: 
13057: =over 4
13058: 
13059: =item *
13060: 
13061: logtouch() : make sure the logfile, lonnet.log, exists
13062: 
13063: =item *
13064: 
13065: logthis() : append message to the normal lonnet.log file, it gets
13066: preiodically rolled over and deleted.
13067: 
13068: =item *
13069: 
13070: logperm() : append a permanent message to lonnet.perm.log, this log
13071: file never gets deleted by any automated portion of the system, only
13072: messages of critical importance should go in here.
13073: 
13074: 
13075: =back
13076: 
13077: =head2 General File Helper Routines
13078: 
13079: =over 4
13080: 
13081: =item *
13082: 
13083: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13084: (a) files in /uploaded
13085:   (i) If a local copy of the file exists - 
13086:       compares modification date of local copy with last-modified date for 
13087:       definitive version stored on home server for course. If local copy is 
13088:       stale, requests a new version from the home server and stores it. 
13089:       If the original has been removed from the home server, then local copy 
13090:       is unlinked.
13091:   (ii) If local copy does not exist -
13092:       requests the file from the home server and stores it. 
13093:   
13094:   If $caller is 'uploadrep':  
13095:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13096:     for request for files originally uploaded via DOCS. 
13097:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13098:   
13099:   Otherwise:
13100:      This indicates a call from the content generation phase of the request.
13101:      -  returns the entire contents of the file or -1.
13102:      
13103: (b) files in /res
13104:    - returns the entire contents of a file or -1; 
13105:    it properly subscribes to and replicates the file if neccessary.
13106: 
13107: 
13108: =item *
13109: 
13110: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13111:                   reference
13112: 
13113: returns either a stat() list of data about the file or an empty list
13114: if the file doesn't exist or couldn't find out about it (connection
13115: problems or user unknown)
13116: 
13117: =item *
13118: 
13119: filelocation($dir,$file) : returns file system location of a file
13120: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13121: directory that relative $file lookups are to looked in ($dir of /a/dir
13122: and a file of ../bob will become /a/bob)
13123: 
13124: =item *
13125: 
13126: hreflocation($dir,$file) : returns file system location or a URL; same as
13127: filelocation except for hrefs
13128: 
13129: =item *
13130: 
13131: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13132: 
13133: =back
13134: 
13135: =head2 Usererfile file routines (/uploaded*)
13136: 
13137: =over 4
13138: 
13139: =item *
13140: 
13141: userfileupload(): main rotine for putting a file in a user or course's
13142:                   filespace, arguments are,
13143: 
13144:  formname - required - this is the name of the element in $env where the
13145:            filename, and the contents of the file to create/modifed exist
13146:            the filename is in $env{'form.'.$formname.'.filename'} and the
13147:            contents of the file is located in $env{'form.'.$formname}
13148:  context - if coursedoc, store the file in the course of the active role
13149:              of the current user; 
13150:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13151:            if 'canceloverwrite': delete file in tmp/overwrites directory
13152:  subdir - required - subdirectory to put the file in under ../userfiles/
13153:          if undefined, it will be placed in "unknown"
13154: 
13155:  (This routine calls clean_filename() to remove any dangerous
13156:  characters from the filename, and then calls finuserfileupload() to
13157:  complete the transaction)
13158: 
13159:  returns either the url of the uploaded file (/uploaded/....) if successful
13160:  and /adm/notfound.html if unsuccessful
13161: 
13162: =item *
13163: 
13164: clean_filename(): routine for cleaing a filename up for storage in
13165:                  userfile space, argument is:
13166: 
13167:  filename - proposed filename
13168: 
13169: returns: the new clean filename
13170: 
13171: =item *
13172: 
13173: finishuserfileupload(): routine that creates and sends the file to
13174: userspace, probably shouldn't be called directly
13175: 
13176:   docuname: username or courseid of destination for the file
13177:   docudom: domain of user/course of destination for the file
13178:   formname: same as for userfileupload()
13179:   fname: filename (including subdirectories) for the file
13180:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13181:   allfiles: reference to hash used to store objects found by parser
13182:   codebase: reference to hash used for codebases of java objects found by parser
13183:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13184:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13185:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13186:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13187:   context: if 'overwrite', will move the uploaded file from its temporary location to
13188:             userfiles to facilitate overwriting a previously uploaded file with same name.
13189:   mimetype: reference to scalar to accommodate mime type determined
13190:             from File::MMagic if $parser = parse.
13191: 
13192:  returns either the url of the uploaded file (/uploaded/....) if successful
13193:  and /adm/notfound.html if unsuccessful (or an error message if context 
13194:  was 'overwrite').
13195:  
13196: 
13197: =item *
13198: 
13199: renameuserfile(): renames an existing userfile to a new name
13200: 
13201:   Args:
13202:    docuname: username or courseid of destination for the file
13203:    docudom: domain of user/course of destination for the file
13204:    old: current file name (including any subdirs under userfiles)
13205:    new: desired file name (including any subdirs under userfiles)
13206: 
13207: =item *
13208: 
13209: mkdiruserfile(): creates a directory is a userfiles dir
13210: 
13211:   Args:
13212:    docuname: username or courseid of destination for the file
13213:    docudom: domain of user/course of destination for the file
13214:    dir: dir to create (including any subdirs under userfiles)
13215: 
13216: =item *
13217: 
13218: removeuserfile(): removes a file that exists in userfiles
13219: 
13220:   Args:
13221:    docuname: username or courseid of destination for the file
13222:    docudom: domain of user/course of destination for the file
13223:    fname: filname to delete (including any subdirs under userfiles)
13224: 
13225: =item *
13226: 
13227: removeuploadedurl(): convience function for removeuserfile()
13228: 
13229:   Args:
13230:    url:  a full /uploaded/... url to delete
13231: 
13232: =item * 
13233: 
13234: get_portfile_permissions():
13235:   Args:
13236:     domain: domain of user or course contain the portfolio files
13237:     user: name of user or num of course contain the portfolio files
13238:   Returns:
13239:     hashref of a dump of the proper file_permissions.db
13240:    
13241: 
13242: =item * 
13243: 
13244: get_access_controls():
13245: 
13246: Args:
13247:   current_permissions: the hash ref returned from get_portfile_permissions()
13248:   group: (optional) the group you want the files associated with
13249:   file: (optional) the file you want access info on
13250: 
13251: Returns:
13252:     a hash (keys are file names) of hashes containing
13253:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13254:         values are XML containing access control settings (see below) 
13255: 
13256: Internal notes:
13257: 
13258:  access controls are stored in file_permissions.db as key=value pairs.
13259:     key -> path to file/file_name\0uniqueID:scope_end_start
13260:         where scope -> public,guest,course,group,domains or users.
13261:               end -> UNIX time for end of access (0 -> no end date)
13262:               start -> UNIX time for start of access
13263: 
13264:     value -> XML description of access control
13265:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13266:             <start></start>
13267:             <end></end>
13268: 
13269:             <password></password>  for scope type = guest
13270: 
13271:             <domain></domain>     for scope type = course or group
13272:             <number></number>
13273:             <roles id="">
13274:              <role></role>
13275:              <access></access>
13276:              <section></section>
13277:              <group></group>
13278:             </roles>
13279: 
13280:             <dom></dom>         for scope type = domains
13281: 
13282:             <users>             for scope type = users
13283:              <user>
13284:               <uname></uname>
13285:               <udom></udom>
13286:              </user>
13287:             </users>
13288:            </scope> 
13289:               
13290:  Access data is also aggregated for each file in an additional key=value pair:
13291:  key -> path to file/file_name\0accesscontrol 
13292:  value -> reference to hash
13293:           hash contains key = value pairs
13294:           where key = uniqueID:scope_end_start
13295:                 value = UNIX time record was last updated
13296: 
13297:           Used to improve speed of look-ups of access controls for each file.  
13298:  
13299:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13300: 
13301: =item *
13302: 
13303: modify_access_controls():
13304: 
13305: Modifies access controls for a portfolio file
13306: Args
13307: 1. file name
13308: 2. reference to hash of required changes,
13309: 3. domain
13310: 4. username
13311:   where domain,username are the domain of the portfolio owner 
13312:   (either a user or a course) 
13313: 
13314: Returns:
13315: 1. result of additions or updates ('ok' or 'error', with error message). 
13316: 2. result of deletions ('ok' or 'error', with error message).
13317: 3. reference to hash of any new or updated access controls.
13318: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13319:    key = integer (inbound ID)
13320:    value = uniqueID
13321: 
13322: =item *
13323: 
13324: get_timebased_id():
13325: 
13326: Attempts to get a unique timestamp-based suffix for use with items added to a 
13327: course via the Course Editor (e.g., folders, composite pages, 
13328: group bulletin boards).
13329: 
13330: Args: (first three required; six others optional)
13331: 
13332: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13333:    docssequence, or name of group
13334: 
13335: 2. keyid (alphanumeric): name of temporary locking key in hash,
13336:    e.g., num, boardids
13337: 
13338: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13339:    file will be named nohist_namespace.db
13340: 
13341: 4. cdom: domain of course; default is current course domain from %env
13342: 
13343: 5. cnum: course number; default is current course number from %env
13344: 
13345: 6. idtype: set to concat if an additional digit is to be appended to the 
13346:    unix timestamp to form the suffix, if the plain timestamp is already
13347:    in use.  Default is to not do this, but simply increment the unix 
13348:    timestamp by 1 until a unique key is obtained.
13349: 
13350: 7. who: holder of locking key; defaults to user:domain for user.
13351: 
13352: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13353:    retrying); default is 3.
13354: 
13355: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13356: 
13357: Returns:
13358: 
13359: 1. suffix obtained (numeric)
13360: 
13361: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13362: 
13363: 3. error: contains (localized) error message if an error occurred.
13364: 
13365: 
13366: =back
13367: 
13368: =head2 HTTP Helper Routines
13369: 
13370: =over 4
13371: 
13372: =item *
13373: 
13374: escape() : unpack non-word characters into CGI-compatible hex codes
13375: 
13376: =item *
13377: 
13378: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13379: 
13380: =back
13381: 
13382: =head1 PRIVATE SUBROUTINES
13383: 
13384: =head2 Underlying communication routines (Shouldn't call)
13385: 
13386: =over 4
13387: 
13388: =item *
13389: 
13390: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13391: 
13392: =item *
13393: 
13394: reply() : uses subreply to send a message to remote machine, logs all failures
13395: 
13396: =item *
13397: 
13398: critical() : passes a critical message to another server; if cannot
13399: get through then place message in connection buffer directory and
13400: returns con_delayed, if incapable of saving message, returns
13401: con_failed
13402: 
13403: =item *
13404: 
13405: reconlonc() : tries to reconnect lonc client processes.
13406: 
13407: =back
13408: 
13409: =head2 Resource Access Logging
13410: 
13411: =over 4
13412: 
13413: =item *
13414: 
13415: flushcourselogs() : flush (save) buffer logs and access logs
13416: 
13417: =item *
13418: 
13419: courselog($what) : save message for course in hash
13420: 
13421: =item *
13422: 
13423: courseacclog($what) : save message for course using &courselog().  Perform
13424: special processing for specific resource types (problems, exams, quizzes, etc).
13425: 
13426: =item *
13427: 
13428: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13429: as a PerlChildExitHandler
13430: 
13431: =back
13432: 
13433: =head2 Other
13434: 
13435: =over 4
13436: 
13437: =item *
13438: 
13439: symblist($mapname,%newhash) : update symbolic storage links
13440: 
13441: =back
13442: 
13443: =cut
13444: 

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