File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1160: download - view: text, annotated - select for diffs
Fri Mar 16 21:16:46 2012 UTC (12 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Store statistics

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1160 2012/03/16 21:16:46 www 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: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: 
  101: use File::Copy;
  102: 
  103: my $readit;
  104: my $max_connection_retries = 10;     # Or some such value.
  105: 
  106: require Exporter;
  107: 
  108: our @ISA = qw (Exporter);
  109: our @EXPORT = qw(%env);
  110: 
  111: 
  112: # --------------------------------------------------------------------- Logging
  113: {
  114:     my $logid;
  115:     sub instructor_log {
  116: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if (($cnum eq '') || ($cdom eq '')) {
  118:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  119:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  120:         }
  121: 	$logid++;
  122:         my $now = time();
  123: 	my $id=$now.'00000'.$$.'00000'.$logid;
  124: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  125: 				    { $id => {
  126: 					'exe_uname' => $env{'user.name'},
  127: 					'exe_udom'  => $env{'user.domain'},
  128: 					'exe_time'  => $now,
  129: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  130: 					'delflag'   => $delflag,
  131: 					'logentry'  => $storehash,
  132: 					'uname'     => $uname,
  133: 					'udom'      => $udom,
  134: 				    }
  135: 				  },$cdom,$cnum);
  136:     }
  137: }
  138: 
  139: sub logtouch {
  140:     my $execdir=$perlvar{'lonDaemons'};
  141:     unless (-e "$execdir/logs/lonnet.log") {	
  142: 	open(my $fh,">>$execdir/logs/lonnet.log");
  143: 	close $fh;
  144:     }
  145:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  146:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  147: }
  148: 
  149: sub logthis {
  150:     my $message=shift;
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     my $now=time;
  153:     my $local=localtime($now);
  154:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  155: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  156: 	print $fh $logstring;
  157: 	close($fh);
  158:     }
  159:     return 1;
  160: }
  161: 
  162: sub logperm {
  163:     my $message=shift;
  164:     my $execdir=$perlvar{'lonDaemons'};
  165:     my $now=time;
  166:     my $local=localtime($now);
  167:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  168: 	print $fh "$now:$message:$local\n";
  169: 	close($fh);
  170:     }
  171:     return 1;
  172: }
  173: 
  174: sub create_connection {
  175:     my ($hostname,$lonid) = @_;
  176:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  177: 				     Type    => SOCK_STREAM,
  178: 				     Timeout => 10);
  179:     return 0 if (!$client);
  180:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  181:     my $result = <$client>;
  182:     chomp($result);
  183:     return 1 if ($result eq 'done');
  184:     return 0;
  185: }
  186: 
  187: sub get_server_timezone {
  188:     my ($cnum,$cdom) = @_;
  189:     my $home=&homeserver($cnum,$cdom);
  190:     if ($home ne 'no_host') {
  191:         my $cachetime = 24*3600;
  192:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  193:         if (defined($cached)) {
  194:             return $timezone;
  195:         } else {
  196:             my $timezone = &reply('servertimezone',$home);
  197:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  198:         }
  199:     }
  200: }
  201: 
  202: sub get_server_distarch {
  203:     my ($lonhost,$ignore_cache) = @_;
  204:     if (defined($lonhost)) {
  205:         if (!defined(&hostname($lonhost))) {
  206:             return;
  207:         }
  208:         my $cachetime = 12*3600;
  209:         if (!$ignore_cache) {
  210:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  211:             if (defined($cached)) {
  212:                 return $distarch;
  213:             }
  214:         }
  215:         my $rep = &reply('serverdistarch',$lonhost);
  216:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  217:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  218:                 $rep eq '') {
  219:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  220:         }
  221:     }
  222:     return;
  223: }
  224: 
  225: sub get_server_loncaparev {
  226:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  227:     if (defined($lonhost)) {
  228:         if (!defined(&hostname($lonhost))) {
  229:             undef($lonhost);
  230:         }
  231:     }
  232:     if (!defined($lonhost)) {
  233:         if (defined(&domain($dom,'primary'))) {
  234:             $lonhost=&domain($dom,'primary');
  235:             if ($lonhost eq 'no_host') {
  236:                 undef($lonhost);
  237:             }
  238:         }
  239:     }
  240:     if (defined($lonhost)) {
  241:         my $cachetime = 12*3600;
  242:         if (!$ignore_cache) {
  243:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  244:             if (defined($cached)) {
  245:                 return $loncaparev;
  246:             }
  247:         }
  248:         my ($answer,$loncaparev);
  249:         my @ids=&current_machine_ids();
  250:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  251:             $answer = $perlvar{'lonVersion'};
  252:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  253:                 $loncaparev = $1;
  254:             }
  255:         } else {
  256:             $answer = &reply('serverloncaparev',$lonhost);
  257:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  258:                 if ($caller eq 'loncron') {
  259:                     my $ua=new LWP::UserAgent;
  260:                     $ua->timeout(4);
  261:                     my $protocol = $protocol{$lonhost};
  262:                     $protocol = 'http' if ($protocol ne 'https');
  263:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  264:                     my $request=new HTTP::Request('GET',$url);
  265:                     my $response=$ua->request($request);
  266:                     unless ($response->is_error()) {
  267:                         my $content = $response->content;
  268:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  269:                             $loncaparev = $1;
  270:                         }
  271:                     }
  272:                 } else {
  273:                     $loncaparev = $loncaparevs{$lonhost};
  274:                 }
  275:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  276:                 $loncaparev = $1;
  277:             }
  278:         }
  279:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  280:     }
  281: }
  282: 
  283: sub get_server_homeID {
  284:     my ($hostname,$ignore_cache,$caller) = @_;
  285:     unless ($ignore_cache) {
  286:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  287:         if (defined($cached)) {
  288:             return $serverhomeID;
  289:         }
  290:     }
  291:     my $cachetime = 12*3600;
  292:     my $serverhomeID;
  293:     if ($caller eq 'loncron') { 
  294:         my @machine_ids = &machine_ids($hostname);
  295:         foreach my $id (@machine_ids) {
  296:             my $response = &reply('serverhomeID',$id);
  297:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  298:                 $serverhomeID = $response;
  299:                 last;
  300:             }
  301:         }
  302:         if ($serverhomeID eq '') {
  303:             $serverhomeID = $machine_ids[-1];
  304:         }
  305:     } else {
  306:         $serverhomeID = $serverhomeIDs{$hostname};
  307:     }
  308:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  309: }
  310: 
  311: sub get_remote_globals {
  312:     my ($lonhost,$whathash,$ignore_cache) = @_;
  313:     my ($result,%returnhash,%whatneeded);
  314:     if (ref($whathash) eq 'HASH') {
  315:         foreach my $what (sort(keys(%{$whathash}))) {
  316:             my $hashid = $lonhost.'-'.$what;
  317:             my ($response,$cached);
  318:             unless ($ignore_cache) {
  319:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  320:             }
  321:             if (defined($cached)) {
  322:                 $returnhash{$what} = $response;
  323:             } else {
  324:                 $whatneeded{$what} = 1;
  325:             }
  326:         }
  327:         if (keys(%whatneeded) == 0) {
  328:             $result = 'ok';
  329:         } else {
  330:             my $requested = &freeze_escape(\%whatneeded);
  331:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  332:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  333:                 ($rep eq 'unknown_cmd')) {
  334:                 $result = $rep;
  335:             } else {
  336:                 $result = 'ok';
  337:                 my @pairs=split(/\&/,$rep);
  338:                 foreach my $item (@pairs) {
  339:                     my ($key,$value)=split(/=/,$item,2);
  340:                     my $what = &unescape($key);
  341:                     my $hashid = $lonhost.'-'.$what;
  342:                     $returnhash{$what}=&thaw_unescape($value);
  343:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  344:                 }
  345:             }
  346:         }
  347:     }
  348:     return ($result,\%returnhash);
  349: }
  350: 
  351: sub remote_devalidate_cache {
  352:     my ($lonhost,$name,$id) = @_;
  353:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  354:     return $response;
  355: }
  356: 
  357: # -------------------------------------------------- Non-critical communication
  358: sub subreply {
  359:     my ($cmd,$server)=@_;
  360:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  361:     #
  362:     #  With loncnew process trimming, there's a timing hole between lonc server
  363:     #  process exit and the master server picking up the listen on the AF_UNIX
  364:     #  socket.  In that time interval, a lock file will exist:
  365: 
  366:     my $lockfile=$peerfile.".lock";
  367:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  368: 	sleep(1);
  369:     }
  370:     # At this point, either a loncnew parent is listening or an old lonc
  371:     # or loncnew child is listening so we can connect or everything's dead.
  372:     #
  373:     #   We'll give the connection a few tries before abandoning it.  If
  374:     #   connection is not possible, we'll con_lost back to the client.
  375:     #   
  376:     my $client;
  377:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  378: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  379: 				      Type    => SOCK_STREAM,
  380: 				      Timeout => 10);
  381: 	if ($client) {
  382: 	    last;		# Connected!
  383: 	} else {
  384: 	    &create_connection(&hostname($server),$server);
  385: 	}
  386:         sleep(1);		# Try again later if failed connection.
  387:     }
  388:     my $answer;
  389:     if ($client) {
  390: 	print $client "sethost:$server:$cmd\n";
  391: 	$answer=<$client>;
  392: 	if (!$answer) { $answer="con_lost"; }
  393: 	chomp($answer);
  394:     } else {
  395: 	$answer = 'con_lost';	# Failed connection.
  396:     }
  397:     return $answer;
  398: }
  399: 
  400: sub reply {
  401:     my ($cmd,$server)=@_;
  402:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  403:     my $answer=subreply($cmd,$server);
  404:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  405:        &logthis("<font color=\"blue\">WARNING:".
  406:                 " $cmd to $server returned $answer</font>");
  407:     }
  408:     return $answer;
  409: }
  410: 
  411: # ----------------------------------------------------------- Send USR1 to lonc
  412: 
  413: sub reconlonc {
  414:     my ($lonid) = @_;
  415:     my $hostname = &hostname($lonid);
  416:     if ($lonid) {
  417: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  418: 	if ($hostname && -e $peerfile) {
  419: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  420: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  421: 					     Type    => SOCK_STREAM,
  422: 					     Timeout => 10);
  423: 	    if ($client) {
  424: 		print $client ("reset_retries\n");
  425: 		my $answer=<$client>;
  426: 		#reset just this one.
  427: 	    }
  428: 	}
  429: 	return;
  430:     }
  431: 
  432:     &logthis("Trying to reconnect lonc");
  433:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  434:     if (open(my $fh,"<$loncfile")) {
  435: 	my $loncpid=<$fh>;
  436:         chomp($loncpid);
  437:         if (kill 0 => $loncpid) {
  438: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  439:             kill USR1 => $loncpid;
  440:             sleep 1;
  441:          } else {
  442: 	    &logthis(
  443:                "<font color=\"blue\">WARNING:".
  444:                " lonc at pid $loncpid not responding, giving up</font>");
  445:         }
  446:     } else {
  447: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  448:     }
  449: }
  450: 
  451: # ------------------------------------------------------ Critical communication
  452: 
  453: sub critical {
  454:     my ($cmd,$server)=@_;
  455:     unless (&hostname($server)) {
  456:         &logthis("<font color=\"blue\">WARNING:".
  457:                " Critical message to unknown server ($server)</font>");
  458:         return 'no_such_host';
  459:     }
  460:     my $answer=reply($cmd,$server);
  461:     if ($answer eq 'con_lost') {
  462: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  463: 	my $answer=reply($cmd,$server);
  464:         if ($answer eq 'con_lost') {
  465:             my $now=time;
  466:             my $middlename=$cmd;
  467:             $middlename=substr($middlename,0,16);
  468:             $middlename=~s/\W//g;
  469:             my $dfilename=
  470:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  471:             $dumpcount++;
  472:             {
  473: 		my $dfh;
  474: 		if (open($dfh,">$dfilename")) {
  475: 		    print $dfh "$cmd\n"; 
  476: 		    close($dfh);
  477: 		}
  478:             }
  479:             sleep 2;
  480:             my $wcmd='';
  481:             {
  482: 		my $dfh;
  483: 		if (open($dfh,"<$dfilename")) {
  484: 		    $wcmd=<$dfh>; 
  485: 		    close($dfh);
  486: 		}
  487:             }
  488:             chomp($wcmd);
  489:             if ($wcmd eq $cmd) {
  490: 		&logthis("<font color=\"blue\">WARNING: ".
  491:                          "Connection buffer $dfilename: $cmd</font>");
  492:                 &logperm("D:$server:$cmd");
  493: 	        return 'con_delayed';
  494:             } else {
  495:                 &logthis("<font color=\"red\">CRITICAL:"
  496:                         ." Critical connection failed: $server $cmd</font>");
  497:                 &logperm("F:$server:$cmd");
  498:                 return 'con_failed';
  499:             }
  500:         }
  501:     }
  502:     return $answer;
  503: }
  504: 
  505: # ------------------------------------------- check if return value is an error
  506: 
  507: sub error {
  508:     my ($result) = @_;
  509:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  510: 	if ($2 == 2) { return undef; }
  511: 	return $1;
  512:     }
  513:     return undef;
  514: }
  515: 
  516: sub convert_and_load_session_env {
  517:     my ($lonidsdir,$handle)=@_;
  518:     my @profile;
  519:     {
  520: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  521: 	if (!$opened) {
  522: 	    return 0;
  523: 	}
  524: 	flock($idf,LOCK_SH);
  525: 	@profile=<$idf>;
  526: 	close($idf);
  527:     }
  528:     my %temp_env;
  529:     foreach my $line (@profile) {
  530: 	if ($line !~ m/=/) {
  531: 	    return 0;
  532: 	}
  533: 	chomp($line);
  534: 	my ($envname,$envvalue)=split(/=/,$line,2);
  535: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  536:     }
  537:     unlink("$lonidsdir/$handle.id");
  538:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  539: 	    0640)) {
  540: 	%disk_env = %temp_env;
  541: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  542: 	untie(%disk_env);
  543:     }
  544:     return 1;
  545: }
  546: 
  547: # ------------------------------------------- Transfer profile into environment
  548: my $env_loaded;
  549: sub transfer_profile_to_env {
  550:     my ($lonidsdir,$handle,$force_transfer) = @_;
  551:     if (!$force_transfer && $env_loaded) { return; } 
  552: 
  553:     if (!defined($lonidsdir)) {
  554: 	$lonidsdir = $perlvar{'lonIDsDir'};
  555:     }
  556:     if (!defined($handle)) {
  557:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  558:     }
  559: 
  560:     my $convert;
  561:     {
  562:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  563: 	if (!$opened) {
  564: 	    return;
  565: 	}
  566: 	flock($idf,LOCK_SH);
  567: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  568: 		&GDBM_READER(),0640)) {
  569: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  570: 	    untie(%disk_env);
  571: 	} else {
  572: 	    $convert = 1;
  573: 	}
  574:     }
  575:     if ($convert) {
  576: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  577: 	    &logthis("Failed to load session, or convert session.");
  578: 	}
  579:     }
  580: 
  581:     my %remove;
  582:     while ( my $envname = each(%env) ) {
  583:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  584:             if ($time < time-300) {
  585:                 $remove{$key}++;
  586:             }
  587:         }
  588:     }
  589: 
  590:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  591:     $env_loaded=1;
  592:     foreach my $expired_key (keys(%remove)) {
  593:         &delenv($expired_key);
  594:     }
  595: }
  596: 
  597: # ---------------------------------------------------- Check for valid session 
  598: sub check_for_valid_session {
  599:     my ($r,$name) = @_;
  600:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  601:     if ($name eq '') {
  602:         $name = 'lonID';
  603:     }
  604:     my $lonid=$cookies{$name};
  605:     return undef if (!$lonid);
  606: 
  607:     my $handle=&LONCAPA::clean_handle($lonid->value);
  608:     my $lonidsdir;
  609:     if ($name eq 'lonDAV') {
  610:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  611:     } else {
  612:         $lonidsdir=$r->dir_config('lonIDsDir');
  613:     }
  614:     return undef if (!-e "$lonidsdir/$handle.id");
  615: 
  616:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617:     return undef if (!$opened);
  618: 
  619:     flock($idf,LOCK_SH);
  620:     my %disk_env;
  621:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 	    &GDBM_READER(),0640)) {
  623: 	return undef;	
  624:     }
  625: 
  626:     if (!defined($disk_env{'user.name'})
  627: 	|| !defined($disk_env{'user.domain'})) {
  628: 	return undef;
  629:     }
  630:     return $handle;
  631: }
  632: 
  633: sub timed_flock {
  634:     my ($file,$lock_type) = @_;
  635:     my $failed=0;
  636:     eval {
  637: 	local $SIG{__DIE__}='DEFAULT';
  638: 	local $SIG{ALRM}=sub {
  639: 	    $failed=1;
  640: 	    die("failed lock");
  641: 	};
  642: 	alarm(13);
  643: 	flock($file,$lock_type);
  644: 	alarm(0);
  645:     };
  646:     if ($failed) {
  647: 	return undef;
  648:     } else {
  649: 	return 1;
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------------- Append Environment
  654: 
  655: sub appenv {
  656:     my ($newenv,$roles) = @_;
  657:     if (ref($newenv) eq 'HASH') {
  658:         foreach my $key (keys(%{$newenv})) {
  659:             my $refused = 0;
  660: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  661:                 $refused = 1;
  662:                 if (ref($roles) eq 'ARRAY') {
  663:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  664:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  665:                         $refused = 0;
  666:                     }
  667:                 }
  668:             }
  669:             if ($refused) {
  670:                 &logthis("<font color=\"blue\">WARNING: ".
  671:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  672:                          .'</font>');
  673: 	        delete($newenv->{$key});
  674:             } else {
  675:                 $env{$key}=$newenv->{$key};
  676:             }
  677:         }
  678:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  679:         if ($opened
  680: 	    && &timed_flock($env_file,LOCK_EX)
  681: 	    &&
  682: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  683: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  684: 	    while (my ($key,$value) = each(%{$newenv})) {
  685: 	        $disk_env{$key} = $value;
  686: 	    }
  687: 	    untie(%disk_env);
  688:         }
  689:     }
  690:     return 'ok';
  691: }
  692: # ----------------------------------------------------- Delete from Environment
  693: 
  694: sub delenv {
  695:     my ($delthis,$regexp,$roles) = @_;
  696:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  697:         my $refused = 1;
  698:         if (ref($roles) eq 'ARRAY') {
  699:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  700:             if (grep(/^\Q$role\E$/,@{$roles})) {
  701:                 $refused = 0;
  702:             }
  703:         }
  704:         if ($refused) {
  705:             &logthis("<font color=\"blue\">WARNING: ".
  706:                      "Attempt to delete from environment ".$delthis);
  707:             return 'error';
  708:         }
  709:     }
  710:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  711:     if ($opened
  712: 	&& &timed_flock($env_file,LOCK_EX)
  713: 	&&
  714: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  715: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  716: 	foreach my $key (keys(%disk_env)) {
  717: 	    if ($regexp) {
  718:                 if ($key=~/^$delthis/) {
  719:                     delete($env{$key});
  720:                     delete($disk_env{$key});
  721:                 } 
  722:             } else {
  723:                 if ($key=~/^\Q$delthis\E/) {
  724: 		    delete($env{$key});
  725: 		    delete($disk_env{$key});
  726: 	        }
  727:             }
  728: 	}
  729: 	untie(%disk_env);
  730:     }
  731:     return 'ok';
  732: }
  733: 
  734: sub get_env_multiple {
  735:     my ($name) = @_;
  736:     my @values;
  737:     if (defined($env{$name})) {
  738:         # exists is it an array
  739:         if (ref($env{$name})) {
  740:             @values=@{ $env{$name} };
  741:         } else {
  742:             $values[0]=$env{$name};
  743:         }
  744:     }
  745:     return(@values);
  746: }
  747: 
  748: # ------------------------------------------------------------------- Locking
  749: 
  750: sub set_lock {
  751:     my ($text)=@_;
  752:     $locknum++;
  753:     my $id=$$.'-'.$locknum;
  754:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  755:              'session.lock.'.$id => $text});
  756:     return $id;
  757: }
  758: 
  759: sub get_locks {
  760:     my $num=0;
  761:     my %texts=();
  762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  763:        if ($lock=~/\w/) {
  764:           $num++;
  765:           $texts{$lock}=$env{'session.lock.'.$lock};
  766:        }
  767:    }
  768:    return ($num,%texts);
  769: }
  770: 
  771: sub remove_lock {
  772:     my ($id)=@_;
  773:     my $newlocks='';
  774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  775:        if (($lock=~/\w/) && ($lock ne $id)) {
  776:           $newlocks.=','.$lock;
  777:        }
  778:     }
  779:     &appenv({'session.locks' => $newlocks});
  780:     &delenv('session.lock.'.$id);
  781: }
  782: 
  783: sub remove_all_locks {
  784:     my $activelocks=$env{'session.locks'};
  785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  786:        if ($lock=~/\w/) {
  787:           &remove_lock($lock);
  788:        }
  789:     }
  790: }
  791: 
  792: 
  793: # ------------------------------------------ Find out current server userload
  794: sub userload {
  795:     my $numusers=0;
  796:     {
  797: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  798: 	my $filename;
  799: 	my $curtime=time;
  800: 	while ($filename=readdir(LONIDS)) {
  801: 	    next if ($filename eq '.' || $filename eq '..');
  802: 	    next if ($filename =~ /publicuser_\d+\.id/);
  803: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  804: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  805: 	}
  806: 	closedir(LONIDS);
  807:     }
  808:     my $userloadpercent=0;
  809:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  810:     if ($maxuserload) {
  811: 	$userloadpercent=100*$numusers/$maxuserload;
  812:     }
  813:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  814:     return $userloadpercent;
  815: }
  816: 
  817: # ------------------------------ Find server with least workload from spare.tab
  818: 
  819: sub spareserver {
  820:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  821:     my $spare_server;
  822:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  823:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  824:                                                      :  $userloadpercent;
  825:     my ($uint_dom,$remotesessions);
  826:     if (($udom ne '') && (&domain($udom) ne '')) {
  827:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  828:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  829:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  830:         $remotesessions = $udomdefaults{'remotesessions'};
  831:     }
  832:     my $spareshash = &this_host_spares($udom);
  833:     if (ref($spareshash) eq 'HASH') {
  834:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  835:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  836:                 if ($uint_dom) {
  837:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  838:                                                  $try_server));
  839:                 }
  840: 	        ($spare_server, $lowest_load) =
  841: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  842:             }
  843:         }
  844: 
  845:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  846: 
  847:         if (!$found_server) {
  848:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  849: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  850:                     if ($uint_dom) {
  851:                         next unless (&spare_can_host($udom,$uint_dom,
  852:                                                      $remotesessions,$try_server));
  853:                     }
  854: 	            ($spare_server, $lowest_load) =
  855: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  856:                 }
  857: 	    }
  858:         }
  859:     }
  860: 
  861:     if (!$want_server_name) {
  862:         my $protocol = 'http';
  863:         if ($protocol{$spare_server} eq 'https') {
  864:             $protocol = $protocol{$spare_server};
  865:         }
  866:         if (defined($spare_server)) {
  867:             my $hostname = &hostname($spare_server);
  868:             if (defined($hostname)) {
  869: 	        $spare_server = $protocol.'://'.$hostname;
  870:             }
  871:         }
  872:     }
  873:     return $spare_server;
  874: }
  875: 
  876: sub compare_server_load {
  877:     my ($try_server, $spare_server, $lowest_load) = @_;
  878: 
  879:     my $loadans     = &reply('load',    $try_server);
  880:     my $userloadans = &reply('userload',$try_server);
  881: 
  882:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  883: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  884:     }
  885: 
  886:     my $load;
  887:     if ($loadans =~ /\d/) {
  888: 	if ($userloadans =~ /\d/) {
  889: 	    #both are numbers, pick the bigger one
  890: 	    $load = ($loadans > $userloadans) ? $loadans 
  891: 		                              : $userloadans;
  892: 	} else {
  893: 	    $load = $loadans;
  894: 	}
  895:     } else {
  896: 	$load = $userloadans;
  897:     }
  898: 
  899:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  900: 	$spare_server = $try_server;
  901: 	$lowest_load  = $load;
  902:     }
  903:     return ($spare_server,$lowest_load);
  904: }
  905: 
  906: # --------------------------- ask offload servers if user already has a session
  907: sub find_existing_session {
  908:     my ($udom,$uname) = @_;
  909:     my $spareshash = &this_host_spares($udom);
  910:     if (ref($spareshash) eq 'HASH') {
  911:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  912:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  913:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  914:             }
  915:         }
  916:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  917:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  918:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  919:             }
  920:         }
  921:     }
  922:     return;
  923: }
  924: 
  925: # -------------------------------- ask if server already has a session for user
  926: sub has_user_session {
  927:     my ($lonid,$udom,$uname) = @_;
  928:     my $result = &reply(join(':','userhassession',
  929: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  930:     return 1 if ($result eq 'ok');
  931: 
  932:     return 0;
  933: }
  934: 
  935: # --------- determine least loaded server in a user's domain which allows login
  936: 
  937: sub choose_server {
  938:     my ($udom,$checkloginvia) = @_;
  939:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  940:     my %servers = &get_servers($udom);
  941:     my $lowest_load = 30000;
  942:     my ($login_host,$hostname,$portal_path,$isredirect);
  943:     foreach my $lonhost (keys(%servers)) {
  944:         my $loginvia;
  945:         if ($checkloginvia) {
  946:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  947:             if ($loginvia) {
  948:                 my ($server,$path) = split(/:/,$loginvia);
  949:                 ($login_host, $lowest_load) =
  950:                     &compare_server_load($server, $login_host, $lowest_load);
  951:                 if ($login_host eq $server) {
  952:                     $portal_path = $path;
  953:                     $isredirect = 1;
  954:                 }
  955:             } else {
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  958:                 if ($login_host eq $lonhost) {
  959:                     $portal_path = '';
  960:                     $isredirect = ''; 
  961:                 }
  962:             }
  963:         } else {
  964:             ($login_host, $lowest_load) =
  965:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  966:         }
  967:     }
  968:     if ($login_host ne '') {
  969:         $hostname = &hostname($login_host);
  970:     }
  971:     return ($login_host,$hostname,$portal_path,$isredirect);
  972: }
  973: 
  974: # --------------------------------------------- Try to change a user's password
  975: 
  976: sub changepass {
  977:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  978:     $currentpass = &escape($currentpass);
  979:     $newpass     = &escape($newpass);
  980:     my $lonhost = $perlvar{'lonHostID'};
  981:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  982: 		       $server);
  983:     if (! $answer) {
  984: 	&logthis("No reply on password change request to $server ".
  985: 		 "by $uname in domain $udom.");
  986:     } elsif ($answer =~ "^ok") {
  987:         &logthis("$uname in $udom successfully changed their password ".
  988: 		 "on $server.");
  989:     } elsif ($answer =~ "^pwchange_failure") {
  990: 	&logthis("$uname in $udom was unable to change their password ".
  991: 		 "on $server.  The action was blocked by either lcpasswd ".
  992: 		 "or pwchange");
  993:     } elsif ($answer =~ "^non_authorized") {
  994:         &logthis("$uname in $udom did not get their password correct when ".
  995: 		 "attempting to change it on $server.");
  996:     } elsif ($answer =~ "^auth_mode_error") {
  997:         &logthis("$uname in $udom attempted to change their password despite ".
  998: 		 "not being locally or internally authenticated on $server.");
  999:     } elsif ($answer =~ "^unknown_user") {
 1000:         &logthis("$uname in $udom attempted to change their password ".
 1001: 		 "on $server but were unable to because $server is not ".
 1002: 		 "their home server.");
 1003:     } elsif ($answer =~ "^refused") {
 1004: 	&logthis("$server refused to change $uname in $udom password because ".
 1005: 		 "it was sent an unencrypted request to change the password.");
 1006:     } elsif ($answer =~ "invalid_client") {
 1007:         &logthis("$server refused to change $uname in $udom password because ".
 1008:                  "it was a reset by e-mail originating from an invalid server.");
 1009:     }
 1010:     return $answer;
 1011: }
 1012: 
 1013: # ----------------------- Try to determine user's current authentication scheme
 1014: 
 1015: sub queryauthenticate {
 1016:     my ($uname,$udom)=@_;
 1017:     my $uhome=&homeserver($uname,$udom);
 1018:     if (!$uhome) {
 1019: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1020: 	return 'no_host';
 1021:     }
 1022:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1023:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1024: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
 1030: 
 1031: sub authenticate {
 1032:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1033:     $upass=&escape($upass);
 1034:     $uname= &LONCAPA::clean_username($uname);
 1035:     my $uhome=&homeserver($uname,$udom,1);
 1036:     my $newhome;
 1037:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1038: # Maybe the machine was offline and only re-appeared again recently?
 1039:         &reconlonc();
 1040: # One more
 1041: 	$uhome=&homeserver($uname,$udom,1);
 1042:         if (($uhome eq 'no_host') && $checkdefauth) {
 1043:             if (defined(&domain($udom,'primary'))) {
 1044:                 $newhome=&domain($udom,'primary');
 1045:             }
 1046:             if ($newhome ne '') {
 1047:                 $uhome = $newhome;
 1048:             }
 1049:         }
 1050: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1051: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1052: 	    return 'no_host';
 1053:         }
 1054:     }
 1055:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1056:     if ($answer eq 'authorized') {
 1057:         if ($newhome) {
 1058:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1059:             return 'no_account_on_host'; 
 1060:         } else {
 1061:             &logthis("User $uname at $udom authorized by $uhome");
 1062:             return $uhome;
 1063:         }
 1064:     }
 1065:     if ($answer eq 'non_authorized') {
 1066: 	&logthis("User $uname at $udom rejected by $uhome");
 1067: 	return 'no_host'; 
 1068:     }
 1069:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1070:     return 'no_host';
 1071: }
 1072: 
 1073: sub can_host_session {
 1074:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1075:     my $canhost = 1;
 1076:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1077:     if (ref($remotesessions) eq 'HASH') {
 1078:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1079:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1080:                 $canhost = 0;
 1081:             } else {
 1082:                 $canhost = 1;
 1083:             }
 1084:         }
 1085:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1087:                 $canhost = 1;
 1088:             } else {
 1089:                 $canhost = 0;
 1090:             }
 1091:         }
 1092:         if ($canhost) {
 1093:             if ($remotesessions->{'version'} ne '') {
 1094:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1095:                 if ($reqmajor ne '' && $reqminor ne '') {
 1096:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1097:                         my $major = $1;
 1098:                         my $minor = $2;
 1099:                         if (($major < $reqmajor ) ||
 1100:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1101:                             $canhost = 0;
 1102:                         }
 1103:                     } else {
 1104:                         $canhost = 0;
 1105:                     }
 1106:                 }
 1107:             }
 1108:         }
 1109:     }
 1110:     if ($canhost) {
 1111:         if (ref($hostedsessions) eq 'HASH') {
 1112:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1113:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1114:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1115:                 if (($uint_dom ne '') && 
 1116:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1117:                     $canhost = 0;
 1118:                 } else {
 1119:                     $canhost = 1;
 1120:                 }
 1121:             }
 1122:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1123:                 if (($uint_dom ne '') && 
 1124:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1125:                     $canhost = 1;
 1126:                 } else {
 1127:                     $canhost = 0;
 1128:                 }
 1129:             }
 1130:         }
 1131:     }
 1132:     return $canhost;
 1133: }
 1134: 
 1135: sub spare_can_host {
 1136:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1137:     my $canhost=1;
 1138:     my @intdoms;
 1139:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1140:     if (ref($internet_names) eq 'ARRAY') {
 1141:         @intdoms = @{$internet_names};
 1142:     }
 1143:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1144:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1145:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1146:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1147:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1148:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1149:                                      $remotesessions,
 1150:                                      $defdomdefaults{'hostedsessions'});
 1151:     }
 1152:     return $canhost;
 1153: }
 1154: 
 1155: sub this_host_spares {
 1156:     my ($dom) = @_;
 1157:     my ($dom_in_use,$lonhost_in_use,$result);
 1158:     my @hosts = &current_machine_ids();
 1159:     foreach my $lonhost (@hosts) {
 1160:         if (&host_domain($lonhost) eq $dom) {
 1161:             $dom_in_use = $dom;
 1162:             $lonhost_in_use = $lonhost;
 1163:             last;
 1164:         }
 1165:     }
 1166:     if ($dom_in_use ne '') {
 1167:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1168:     }
 1169:     if (ref($result) ne 'HASH') {
 1170:         $lonhost_in_use = $perlvar{'lonHostID'};
 1171:         $dom_in_use = &host_domain($lonhost_in_use);
 1172:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1173:         if (ref($result) ne 'HASH') {
 1174:             $result = \%spareid;
 1175:         }
 1176:     }
 1177:     return $result;
 1178: }
 1179: 
 1180: sub spares_for_offload  {
 1181:     my ($dom_in_use,$lonhost_in_use) = @_;
 1182:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1183:     if (defined($cached)) {
 1184:         return $result;
 1185:     } else {
 1186:         my $cachetime = 60*60*24;
 1187:         my %domconfig =
 1188:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1189:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1190:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1191:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1192:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1193:                 }
 1194:             }
 1195:         }
 1196:     }
 1197:     return;
 1198: }
 1199: 
 1200: sub get_lonbalancer_config {
 1201:     my ($servers) = @_;
 1202:     my ($currbalancer,$currtargets);
 1203:     if (ref($servers) eq 'HASH') {
 1204:         foreach my $server (keys(%{$servers})) {
 1205:             my %what = (
 1206:                          spareid => 1,
 1207:                          perlvar => 1,
 1208:                        );
 1209:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1210:             if ($result eq 'ok') {
 1211:                 if (ref($returnhash) eq 'HASH') {
 1212:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1213:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1214:                             $currbalancer = $server;
 1215:                             $currtargets = {};
 1216:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1217:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1218:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1219:                                 }
 1220:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1221:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1222:                                 }
 1223:                             }
 1224:                             last;
 1225:                         }
 1226:                     }
 1227:                 }
 1228:             }
 1229:         }
 1230:     }
 1231:     return ($currbalancer,$currtargets);
 1232: }
 1233: 
 1234: sub check_loadbalancing {
 1235:     my ($uname,$udom) = @_;
 1236:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1237:         $offloadto,$otherserver);
 1238:     my $lonhost = $perlvar{'lonHostID'};
 1239:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1240:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1241:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1242:     my $serverhomedom = &host_domain($lonhost);
 1243: 
 1244:     my $cachetime = 60*60*24;
 1245: 
 1246:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1247:         $dom_in_use = $udom;
 1248:         $homeintdom = 1;
 1249:     } else {
 1250:         $dom_in_use = $serverhomedom;
 1251:     }
 1252:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1253:     unless (defined($cached)) {
 1254:         my %domconfig =
 1255:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1256:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1257:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1258:         }
 1259:     }
 1260:     if (ref($result) eq 'HASH') {
 1261:         my $currbalancer = $result->{'lonhost'};
 1262:         my $currtargets = $result->{'targets'};
 1263:         my $currrules = $result->{'rules'};
 1264:         if ($currbalancer ne '') {
 1265:             my @hosts = &current_machine_ids();
 1266:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1267:                 $is_balancer = 1;
 1268:             }
 1269:         }
 1270:         if ($is_balancer) {
 1271:             if (ref($currrules) eq 'HASH') {
 1272:                 if ($homeintdom) {
 1273:                     if ($uname ne '') {
 1274:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1275:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1276:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1277:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1278:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1279:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1280:                             }
 1281:                         }
 1282:                         if ($rule_in_effect eq '') {
 1283:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1284:                             if ($userenv{'inststatus'} ne '') {
 1285:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1286:                                 my ($othertitle,$usertypes,$types) =
 1287:                                     &Apache::loncommon::sorted_inst_types($udom);
 1288:                                 if (ref($types) eq 'ARRAY') {
 1289:                                     foreach my $type (@{$types}) {
 1290:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1291:                                             if (exists($currrules->{$type})) {
 1292:                                                 $rule_in_effect = $currrules->{$type};
 1293:                                             }
 1294:                                         }
 1295:                                     }
 1296:                                 }
 1297:                             } else {
 1298:                                 if (exists($currrules->{'default'})) {
 1299:                                     $rule_in_effect = $currrules->{'default'};
 1300:                                 }
 1301:                             }
 1302:                         }
 1303:                     } else {
 1304:                         if (exists($currrules->{'default'})) {
 1305:                             $rule_in_effect = $currrules->{'default'};
 1306:                         }
 1307:                     }
 1308:                 } else {
 1309:                     if ($currrules->{'_LC_external'} ne '') {
 1310:                         $rule_in_effect = $currrules->{'_LC_external'};
 1311:                     }
 1312:                 }
 1313:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1314:                                                        $uname,$udom);
 1315:             }
 1316:         }
 1317:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1318:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1319:         unless (defined($cached)) {
 1320:             my %domconfig =
 1321:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1322:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1323:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1324:             }
 1325:         }
 1326:         if (ref($result) eq 'HASH') {
 1327:             my $currbalancer = $result->{'lonhost'};
 1328:             my $currtargets = $result->{'targets'};
 1329:             my $currrules = $result->{'rules'};
 1330: 
 1331:             if ($currbalancer eq $lonhost) {
 1332:                 $is_balancer = 1;
 1333:                 if (ref($currrules) eq 'HASH') {
 1334:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1335:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1336:                     }
 1337:                 }
 1338:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1339:                                                        $uname,$udom);
 1340:             }
 1341:         } else {
 1342:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1343:                 $is_balancer = 1;
 1344:                 $offloadto = &this_host_spares($dom_in_use);
 1345:             }
 1346:         }
 1347:     } else {
 1348:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1349:             $is_balancer = 1;
 1350:             $offloadto = &this_host_spares($dom_in_use);
 1351:         }
 1352:     }
 1353:     my $lowest_load = 30000;
 1354:     if (ref($offloadto) eq 'HASH') {
 1355:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1356:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1357:                 ($otherserver,$lowest_load) =
 1358:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1359:             }
 1360:         }
 1361:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1362: 
 1363:         if (!$found_server) {
 1364:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1365:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1366:                     ($otherserver,$lowest_load) =
 1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1368:                 }
 1369:             }
 1370:         }
 1371:     } elsif (ref($offloadto) eq 'ARRAY') {
 1372:         if (@{$offloadto} == 1) {
 1373:             $otherserver = $offloadto->[0];
 1374:         } elsif (@{$offloadto} > 1) {
 1375:             foreach my $try_server (@{$offloadto}) {
 1376:                 ($otherserver,$lowest_load) =
 1377:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1378:             }
 1379:         }
 1380:     }
 1381:     return ($is_balancer,$otherserver);
 1382: }
 1383: 
 1384: sub get_loadbalancer_targets {
 1385:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1386:     my $offloadto;
 1387:     if ($rule_in_effect eq '') {
 1388:         $offloadto = $currtargets;
 1389:     } else {
 1390:         if ($rule_in_effect eq 'homeserver') {
 1391:             my $homeserver = &homeserver($uname,$udom);
 1392:             if ($homeserver ne 'no_host') {
 1393:                 $offloadto = [$homeserver];
 1394:             }
 1395:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1396:             my %domconfig =
 1397:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1398:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1399:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1400:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1401:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1402:                     }
 1403:                 }
 1404:             } else {
 1405:                 my %servers = &dom_servers($udom);
 1406:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1407:                 if (&hostname($remotebalancer) ne '') {
 1408:                     $offloadto = [$remotebalancer];
 1409:                 }
 1410:             }
 1411:         } elsif (&hostname($rule_in_effect) ne '') {
 1412:             $offloadto = [$rule_in_effect];
 1413:         }
 1414:     }
 1415:     return $offloadto;
 1416: }
 1417: 
 1418: sub internet_dom_servers {
 1419:     my ($dom) = @_;
 1420:     my (%uniqservers,%servers);
 1421:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1422:     my @machinedoms = &machine_domains($primaryserver);
 1423:     foreach my $mdom (@machinedoms) {
 1424:         my %currservers = %servers;
 1425:         my %server = &get_servers($mdom);
 1426:         %servers = (%currservers,%server);
 1427:     }
 1428:     my %by_hostname;
 1429:     foreach my $id (keys(%servers)) {
 1430:         push(@{$by_hostname{$servers{$id}}},$id);
 1431:     }
 1432:     foreach my $hostname (sort(keys(%by_hostname))) {
 1433:         if (@{$by_hostname{$hostname}} > 1) {
 1434:             my $match = 0;
 1435:             foreach my $id (@{$by_hostname{$hostname}}) {
 1436:                 if (&host_domain($id) eq $dom) {
 1437:                     $uniqservers{$id} = $hostname;
 1438:                     $match = 1;
 1439:                 }
 1440:             }
 1441:             unless ($match) {
 1442:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1443:             }
 1444:         } else {
 1445:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1446:         }
 1447:     }
 1448:     return %uniqservers;
 1449: }
 1450: 
 1451: # ---------------------- Find the homebase for a user from domain's lib servers
 1452: 
 1453: my %homecache;
 1454: sub homeserver {
 1455:     my ($uname,$udom,$ignoreBadCache)=@_;
 1456:     my $index="$uname:$udom";
 1457: 
 1458:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1459: 
 1460:     my %servers = &get_servers($udom,'library');
 1461:     foreach my $tryserver (keys(%servers)) {
 1462:         next if ($ignoreBadCache ne 'true' && 
 1463: 		 exists($badServerCache{$tryserver}));
 1464: 
 1465: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1466: 	if ($answer eq 'found') {
 1467: 	    delete($badServerCache{$tryserver}); 
 1468: 	    return $homecache{$index}=$tryserver;
 1469: 	} elsif ($answer eq 'no_host') {
 1470: 	    $badServerCache{$tryserver}=1;
 1471: 	}
 1472:     }    
 1473:     return 'no_host';
 1474: }
 1475: 
 1476: # ------------------------------------- Find the usernames behind a list of IDs
 1477: 
 1478: sub idget {
 1479:     my ($udom,@ids)=@_;
 1480:     my %returnhash=();
 1481:     
 1482:     my %servers = &get_servers($udom,'library');
 1483:     foreach my $tryserver (keys(%servers)) {
 1484: 	my $idlist=join('&',@ids);
 1485: 	$idlist=~tr/A-Z/a-z/; 
 1486: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1487: 	my @answer=();
 1488: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1489: 	    @answer=split(/\&/,$reply);
 1490: 	}                    ;
 1491: 	my $i;
 1492: 	for ($i=0;$i<=$#ids;$i++) {
 1493: 	    if ($answer[$i]) {
 1494: 		$returnhash{$ids[$i]}=$answer[$i];
 1495: 	    } 
 1496: 	}
 1497:     } 
 1498:     return %returnhash;
 1499: }
 1500: 
 1501: # ------------------------------------- Find the IDs behind a list of usernames
 1502: 
 1503: sub idrget {
 1504:     my ($udom,@unames)=@_;
 1505:     my %returnhash=();
 1506:     foreach my $uname (@unames) {
 1507:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1508:     }
 1509:     return %returnhash;
 1510: }
 1511: 
 1512: # ------------------------------- Store away a list of names and associated IDs
 1513: 
 1514: sub idput {
 1515:     my ($udom,%ids)=@_;
 1516:     my %servers=();
 1517:     foreach my $uname (keys(%ids)) {
 1518: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1519:         my $uhom=&homeserver($uname,$udom);
 1520:         if ($uhom ne 'no_host') {
 1521:             my $id=&escape($ids{$uname});
 1522:             $id=~tr/A-Z/a-z/;
 1523:             my $esc_unam=&escape($uname);
 1524: 	    if ($servers{$uhom}) {
 1525: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1526:             } else {
 1527:                 $servers{$uhom}=$id.'='.$esc_unam;
 1528:             }
 1529:         }
 1530:     }
 1531:     foreach my $server (keys(%servers)) {
 1532:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1533:     }
 1534: }
 1535: 
 1536: # ------------------------------dump from db file owned by domainconfig user
 1537: sub dump_dom {
 1538:     my ($namespace,$udom,$regexp,$range)=@_;
 1539:     if (!$udom) {
 1540:         $udom=$env{'user.domain'};
 1541:     }
 1542:     my %returnhash;
 1543:     if ($udom) {
 1544:         my $uname = &get_domainconfiguser($udom);
 1545:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
 1546:     }
 1547:     return %returnhash;
 1548: }
 1549: 
 1550: # ------------------------------------------ get items from domain db files   
 1551: 
 1552: sub get_dom {
 1553:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1554:     my $items='';
 1555:     foreach my $item (@$storearr) {
 1556:         $items.=&escape($item).'&';
 1557:     }
 1558:     $items=~s/\&$//;
 1559:     if (!$udom) {
 1560:         $udom=$env{'user.domain'};
 1561:         if (defined(&domain($udom,'primary'))) {
 1562:             $uhome=&domain($udom,'primary');
 1563:         } else {
 1564:             undef($uhome);
 1565:         }
 1566:     } else {
 1567:         if (!$uhome) {
 1568:             if (defined(&domain($udom,'primary'))) {
 1569:                 $uhome=&domain($udom,'primary');
 1570:             }
 1571:         }
 1572:     }
 1573:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1574:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1575:         my %returnhash;
 1576:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1577:             return %returnhash;
 1578:         }
 1579:         my @pairs=split(/\&/,$rep);
 1580:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1581:             return @pairs;
 1582:         }
 1583:         my $i=0;
 1584:         foreach my $item (@$storearr) {
 1585:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1586:             $i++;
 1587:         }
 1588:         return %returnhash;
 1589:     } else {
 1590:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1591:     }
 1592: }
 1593: 
 1594: # -------------------------------------------- put items in domain db files 
 1595: 
 1596: sub put_dom {
 1597:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1598:     if (!$udom) {
 1599:         $udom=$env{'user.domain'};
 1600:         if (defined(&domain($udom,'primary'))) {
 1601:             $uhome=&domain($udom,'primary');
 1602:         } else {
 1603:             undef($uhome);
 1604:         }
 1605:     } else {
 1606:         if (!$uhome) {
 1607:             if (defined(&domain($udom,'primary'))) {
 1608:                 $uhome=&domain($udom,'primary');
 1609:             }
 1610:         }
 1611:     } 
 1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1613:         my $items='';
 1614:         foreach my $item (keys(%$storehash)) {
 1615:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1616:         }
 1617:         $items=~s/\&$//;
 1618:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1619:     } else {
 1620:         &logthis("put_dom failed - no homeserver and/or domain");
 1621:     }
 1622: }
 1623: 
 1624: # --------------------- newput for items in db file owned by domainconfig user
 1625: sub newput_dom {
 1626:     my ($namespace,$storehash,$udom) = @_;
 1627:     my $result;
 1628:     if (!$udom) {
 1629:         $udom=$env{'user.domain'};
 1630:     }
 1631:     if ($udom) {
 1632:         my $uname = &get_domainconfiguser($udom);
 1633:         $result = &newput($namespace,$storehash,$udom,$uname);
 1634:     }
 1635:     return $result;
 1636: }
 1637: 
 1638: # --------------------- delete for items in db file owned by domainconfig user
 1639: sub del_dom {
 1640:     my ($namespace,$storearr,$udom)=@_;
 1641:     if (ref($storearr) eq 'ARRAY') {
 1642:         if (!$udom) {
 1643:             $udom=$env{'user.domain'};
 1644:         }
 1645:         if ($udom) {
 1646:             my $uname = &get_domainconfiguser($udom); 
 1647:             return &del($namespace,$storearr,$udom,$uname);
 1648:         }
 1649:     }
 1650: }
 1651: 
 1652: # ----------------------------------construct domainconfig user for a domain 
 1653: sub get_domainconfiguser {
 1654:     my ($udom) = @_;
 1655:     return $udom.'-domainconfig';
 1656: }
 1657: 
 1658: sub retrieve_inst_usertypes {
 1659:     my ($udom) = @_;
 1660:     my (%returnhash,@order);
 1661:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1662:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1663:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1664:         %returnhash = %{$domdefs{'inststatustypes'}};
 1665:         @order = @{$domdefs{'inststatusorder'}};
 1666:     } else {
 1667:         if (defined(&domain($udom,'primary'))) {
 1668:             my $uhome=&domain($udom,'primary');
 1669:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1670:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1671:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1672:                 return (\%returnhash,\@order);
 1673:             }
 1674:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1675:             my @pairs=split(/\&/,$hashitems);
 1676:             foreach my $item (@pairs) {
 1677:                 my ($key,$value)=split(/=/,$item,2);
 1678:                 $key = &unescape($key);
 1679:                 next if ($key =~ /^error: 2 /);
 1680:                 $returnhash{$key}=&thaw_unescape($value);
 1681:             }
 1682:             my @esc_order = split(/\&/,$orderitems);
 1683:             foreach my $item (@esc_order) {
 1684:                 push(@order,&unescape($item));
 1685:             }
 1686:         } else {
 1687:             &logthis("get_dom failed - no primary domain server for $udom");
 1688:         }
 1689:     }
 1690:     return (\%returnhash,\@order);
 1691: }
 1692: 
 1693: sub is_domainimage {
 1694:     my ($url) = @_;
 1695:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1696:         if (&domain($1) ne '') {
 1697:             return '1';
 1698:         }
 1699:     }
 1700:     return;
 1701: }
 1702: 
 1703: sub inst_directory_query {
 1704:     my ($srch) = @_;
 1705:     my $udom = $srch->{'srchdomain'};
 1706:     my %results;
 1707:     my $homeserver = &domain($udom,'primary');
 1708:     my $outcome;
 1709:     if ($homeserver ne '') {
 1710: 	my $queryid=&reply("querysend:instdirsearch:".
 1711: 			   &escape($srch->{'srchby'}).':'.
 1712: 			   &escape($srch->{'srchterm'}).':'.
 1713: 			   &escape($srch->{'srchtype'}),$homeserver);
 1714: 	my $host=&hostname($homeserver);
 1715: 	if ($queryid !~/^\Q$host\E\_/) {
 1716: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1717: 	    return;
 1718: 	}
 1719: 	my $response = &get_query_reply($queryid);
 1720: 	my $maxtries = 5;
 1721: 	my $tries = 1;
 1722: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1723: 	    $response = &get_query_reply($queryid);
 1724: 	    $tries ++;
 1725: 	}
 1726: 
 1727:         if (!&error($response) && $response ne 'refused') {
 1728:             if ($response eq 'unavailable') {
 1729:                 $outcome = $response;
 1730:             } else {
 1731:                 $outcome = 'ok';
 1732:                 my @matches = split(/\n/,$response);
 1733:                 foreach my $match (@matches) {
 1734:                     my ($key,$value) = split(/=/,$match);
 1735:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1736:                 }
 1737:             }
 1738:         }
 1739:     }
 1740:     return ($outcome,%results);
 1741: }
 1742: 
 1743: sub usersearch {
 1744:     my ($srch) = @_;
 1745:     my $dom = $srch->{'srchdomain'};
 1746:     my %results;
 1747:     my %libserv = &all_library();
 1748:     my $query = 'usersearch';
 1749:     foreach my $tryserver (keys(%libserv)) {
 1750:         if (&host_domain($tryserver) eq $dom) {
 1751:             my $host=&hostname($tryserver);
 1752:             my $queryid=
 1753:                 &reply("querysend:".&escape($query).':'.
 1754:                        &escape($srch->{'srchby'}).':'.
 1755:                        &escape($srch->{'srchtype'}).':'.
 1756:                        &escape($srch->{'srchterm'}),$tryserver);
 1757:             if ($queryid !~/^\Q$host\E\_/) {
 1758:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1759:                 next;
 1760:             }
 1761:             my $reply = &get_query_reply($queryid);
 1762:             my $maxtries = 1;
 1763:             my $tries = 1;
 1764:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1765:                 $reply = &get_query_reply($queryid);
 1766:                 $tries ++;
 1767:             }
 1768:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1769:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1770:             } else {
 1771:                 my @matches;
 1772:                 if ($reply =~ /\n/) {
 1773:                     @matches = split(/\n/,$reply);
 1774:                 } else {
 1775:                     @matches = split(/\&/,$reply);
 1776:                 }
 1777:                 foreach my $match (@matches) {
 1778:                     my ($uname,$udom,%userhash);
 1779:                     foreach my $entry (split(/:/,$match)) {
 1780:                         my ($key,$value) =
 1781:                             map {&unescape($_);} split(/=/,$entry);
 1782:                         $userhash{$key} = $value;
 1783:                         if ($key eq 'username') {
 1784:                             $uname = $value;
 1785:                         } elsif ($key eq 'domain') {
 1786:                             $udom = $value;
 1787:                         }
 1788:                     }
 1789:                     $results{$uname.':'.$udom} = \%userhash;
 1790:                 }
 1791:             }
 1792:         }
 1793:     }
 1794:     return %results;
 1795: }
 1796: 
 1797: sub get_instuser {
 1798:     my ($udom,$uname,$id) = @_;
 1799:     my $homeserver = &domain($udom,'primary');
 1800:     my ($outcome,%results);
 1801:     if ($homeserver ne '') {
 1802:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1803:                            &escape($id).':'.&escape($udom),$homeserver);
 1804:         my $host=&hostname($homeserver);
 1805:         if ($queryid !~/^\Q$host\E\_/) {
 1806:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1807:             return;
 1808:         }
 1809:         my $response = &get_query_reply($queryid);
 1810:         my $maxtries = 5;
 1811:         my $tries = 1;
 1812:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1813:             $response = &get_query_reply($queryid);
 1814:             $tries ++;
 1815:         }
 1816:         if (!&error($response) && $response ne 'refused') {
 1817:             if ($response eq 'unavailable') {
 1818:                 $outcome = $response;
 1819:             } else {
 1820:                 $outcome = 'ok';
 1821:                 my @matches = split(/\n/,$response);
 1822:                 foreach my $match (@matches) {
 1823:                     my ($key,$value) = split(/=/,$match);
 1824:                     $results{&unescape($key)} = &thaw_unescape($value);
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     my %userinfo;
 1830:     if (ref($results{$uname}) eq 'HASH') {
 1831:         %userinfo = %{$results{$uname}};
 1832:     } 
 1833:     return ($outcome,%userinfo);
 1834: }
 1835: 
 1836: sub inst_rulecheck {
 1837:     my ($udom,$uname,$id,$item,$rules) = @_;
 1838:     my %returnhash;
 1839:     if ($udom ne '') {
 1840:         if (ref($rules) eq 'ARRAY') {
 1841:             @{$rules} = map {&escape($_);} (@{$rules});
 1842:             my $rulestr = join(':',@{$rules});
 1843:             my $homeserver=&domain($udom,'primary');
 1844:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1845:                 my $response;
 1846:                 if ($item eq 'username') {                
 1847:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1848:                                               ':'.&escape($uname).':'.$rulestr,
 1849:                                               $homeserver));
 1850:                 } elsif ($item eq 'id') {
 1851:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1852:                                               ':'.&escape($id).':'.$rulestr,
 1853:                                               $homeserver));
 1854:                 } elsif ($item eq 'selfcreate') {
 1855:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1856:                                                &escape($udom).':'.&escape($uname).
 1857:                                               ':'.$rulestr,$homeserver));
 1858:                 }
 1859:                 if ($response ne 'refused') {
 1860:                     my @pairs=split(/\&/,$response);
 1861:                     foreach my $item (@pairs) {
 1862:                         my ($key,$value)=split(/=/,$item,2);
 1863:                         $key = &unescape($key);
 1864:                         next if ($key =~ /^error: 2 /);
 1865:                         $returnhash{$key}=&thaw_unescape($value);
 1866:                     }
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     return %returnhash;
 1872: }
 1873: 
 1874: sub inst_userrules {
 1875:     my ($udom,$check) = @_;
 1876:     my (%ruleshash,@ruleorder);
 1877:     if ($udom ne '') {
 1878:         my $homeserver=&domain($udom,'primary');
 1879:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:             my $response;
 1881:             if ($check eq 'id') {
 1882:                 $response=&reply('instidrules:'.&escape($udom),
 1883:                                  $homeserver);
 1884:             } elsif ($check eq 'email') {
 1885:                 $response=&reply('instemailrules:'.&escape($udom),
 1886:                                  $homeserver);
 1887:             } else {
 1888:                 $response=&reply('instuserrules:'.&escape($udom),
 1889:                                  $homeserver);
 1890:             }
 1891:             if (($response ne 'refused') && ($response ne 'error') && 
 1892:                 ($response ne 'unknown_cmd') && 
 1893:                 ($response ne 'no_such_host')) {
 1894:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1895:                 my @pairs=split(/\&/,$hashitems);
 1896:                 foreach my $item (@pairs) {
 1897:                     my ($key,$value)=split(/=/,$item,2);
 1898:                     $key = &unescape($key);
 1899:                     next if ($key =~ /^error: 2 /);
 1900:                     $ruleshash{$key}=&thaw_unescape($value);
 1901:                 }
 1902:                 my @esc_order = split(/\&/,$orderitems);
 1903:                 foreach my $item (@esc_order) {
 1904:                     push(@ruleorder,&unescape($item));
 1905:                 }
 1906:             }
 1907:         }
 1908:     }
 1909:     return (\%ruleshash,\@ruleorder);
 1910: }
 1911: 
 1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1913: 
 1914: sub get_domain_defaults {
 1915:     my ($domain) = @_;
 1916:     my $cachetime = 60*60*24;
 1917:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1918:     if (defined($cached)) {
 1919:         if (ref($result) eq 'HASH') {
 1920:             return %{$result};
 1921:         }
 1922:     }
 1923:     my %domdefaults;
 1924:     my %domconfig =
 1925:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1926:                                   'requestcourses','inststatus',
 1927:                                   'coursedefaults','usersessions'],$domain);
 1928:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1929:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1930:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1931:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1932:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1933:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1934:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1935:     } else {
 1936:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1937:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1938:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1939:     }
 1940:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1941:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1943:         } else {
 1944:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1945:         } 
 1946:         my @usertools = ('aboutme','blog','portfolio');
 1947:         foreach my $item (@usertools) {
 1948:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1949:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1950:             }
 1951:         }
 1952:     }
 1953:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1954:         foreach my $item ('official','unofficial','community') {
 1955:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1956:         }
 1957:     }
 1958:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1959:         foreach my $item ('inststatustypes','inststatusorder') {
 1960:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1961:         }
 1962:     }
 1963:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1964:         foreach my $item ('canuse_pdfforms') {
 1965:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1966:         }
 1967:     }
 1968:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1969:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1970:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1971:         }
 1972:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1973:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1974:         }
 1975:     }
 1976:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1977:                                   $cachetime);
 1978:     return %domdefaults;
 1979: }
 1980: 
 1981: # --------------------------------------------------- Assign a key to a student
 1982: 
 1983: sub assign_access_key {
 1984: #
 1985: # a valid key looks like uname:udom#comments
 1986: # comments are being appended
 1987: #
 1988:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1989:     $kdom=
 1990:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1991:     $knum=
 1992:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1993:     $cdom=
 1994:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1995:     $cnum=
 1996:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1997:     $udom=$env{'user.name'} unless (defined($udom));
 1998:     $uname=$env{'user.domain'} unless (defined($uname));
 1999:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2000:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2001:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2002:                                                   # assigned to this person
 2003:                                                   # - this should not happen,
 2004:                                                   # unless something went wrong
 2005:                                                   # the first time around
 2006: # ready to assign
 2007:         $logentry=$1.'; '.$logentry;
 2008:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2009:                                                  $kdom,$knum) eq 'ok') {
 2010: # key now belongs to user
 2011: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2012:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2013:                 &appenv({'environment.'.$envkey => $ckey});
 2014:                 return 'ok';
 2015:             } else {
 2016:                 return 
 2017:   'error: Count not permanently assign key, will need to be re-entered later.';
 2018: 	    }
 2019:         } else {
 2020:             return 'error: Could not assign key, try again later.';
 2021:         }
 2022:     } elsif (!$existing{$ckey}) {
 2023: # the key does not exist
 2024: 	return 'error: The key does not exist';
 2025:     } else {
 2026: # the key is somebody else's
 2027: 	return 'error: The key is already in use';
 2028:     }
 2029: }
 2030: 
 2031: # ------------------------------------------ put an additional comment on a key
 2032: 
 2033: sub comment_access_key {
 2034: #
 2035: # a valid key looks like uname:udom#comments
 2036: # comments are being appended
 2037: #
 2038:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2039:     $cdom=
 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2041:     $cnum=
 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2043:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2044:     if ($existing{$ckey}) {
 2045:         $existing{$ckey}.='; '.$logentry;
 2046: # ready to assign
 2047:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2048:                                                  $cdom,$cnum) eq 'ok') {
 2049: 	    return 'ok';
 2050:         } else {
 2051: 	    return 'error: Count not store comment.';
 2052:         }
 2053:     } else {
 2054: # the key does not exist
 2055: 	return 'error: The key does not exist';
 2056:     }
 2057: }
 2058: 
 2059: # ------------------------------------------------------ Generate a set of keys
 2060: 
 2061: sub generate_access_keys {
 2062:     my ($number,$cdom,$cnum,$logentry)=@_;
 2063:     $cdom=
 2064:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2065:     $cnum=
 2066:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2067:     unless (&allowed('mky',$cdom)) { return 0; }
 2068:     unless (($cdom) && ($cnum)) { return 0; }
 2069:     if ($number>10000) { return 0; }
 2070:     sleep(2); # make sure don't get same seed twice
 2071:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2072:     my $total=0;
 2073:     for (my $i=1;$i<=$number;$i++) {
 2074:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2075:                   sprintf("%lx",int(100000*rand)).'-'.
 2076:                   sprintf("%lx",int(100000*rand));
 2077:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2078:        $newkey=~s/0/h/g; # and also 0 and O
 2079:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2080:        if ($existing{$newkey}) {
 2081:            $i--;
 2082:        } else {
 2083: 	  if (&put('accesskeys',
 2084:               { $newkey => '# generated '.localtime().
 2085:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2086:                            '; '.$logentry },
 2087: 		   $cdom,$cnum) eq 'ok') {
 2088:               $total++;
 2089: 	  }
 2090:        }
 2091:     }
 2092:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2093:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2094:     return $total;
 2095: }
 2096: 
 2097: # ------------------------------------------------------- Validate an accesskey
 2098: 
 2099: sub validate_access_key {
 2100:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2101:     $cdom=
 2102:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2103:     $cnum=
 2104:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2105:     $udom=$env{'user.domain'} unless (defined($udom));
 2106:     $uname=$env{'user.name'} unless (defined($uname));
 2107:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2108:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2109: }
 2110: 
 2111: # ------------------------------------- Find the section of student in a course
 2112: sub devalidate_getsection_cache {
 2113:     my ($udom,$unam,$courseid)=@_;
 2114:     my $hashid="$udom:$unam:$courseid";
 2115:     &devalidate_cache_new('getsection',$hashid);
 2116: }
 2117: 
 2118: sub courseid_to_courseurl {
 2119:     my ($courseid) = @_;
 2120:     #already url style courseid
 2121:     return $courseid if ($courseid =~ m{^/});
 2122: 
 2123:     if (exists($env{'course.'.$courseid.'.num'})) {
 2124: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2125: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2126: 	return "/$cdom/$cnum";
 2127:     }
 2128: 
 2129:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2130:     if (exists($courseinfo{'num'})) {
 2131: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2132:     }
 2133: 
 2134:     return undef;
 2135: }
 2136: 
 2137: sub getsection {
 2138:     my ($udom,$unam,$courseid)=@_;
 2139:     my $cachetime=1800;
 2140: 
 2141:     my $hashid="$udom:$unam:$courseid";
 2142:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2143:     if (defined($cached)) { return $result; }
 2144: 
 2145:     my %Pending; 
 2146:     my %Expired;
 2147:     #
 2148:     # Each role can either have not started yet (pending), be active, 
 2149:     #    or have expired.
 2150:     #
 2151:     # If there is an active role, we are done.
 2152:     #
 2153:     # If there is more than one role which has not started yet, 
 2154:     #     choose the one which will start sooner
 2155:     # If there is one role which has not started yet, return it.
 2156:     #
 2157:     # If there is more than one expired role, choose the one which ended last.
 2158:     # If there is a role which has expired, return it.
 2159:     #
 2160:     $courseid = &courseid_to_courseurl($courseid);
 2161:     my $extra = &freeze_escape({'skipcheck' => 1});
 2162:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
 2163:     foreach my $key (keys(%roleshash)) {
 2164:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2165:         my $section=$1;
 2166:         if ($key eq $courseid.'_st') { $section=''; }
 2167:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2168:         my $now=time;
 2169:         if (defined($end) && $end && ($now > $end)) {
 2170:             $Expired{$end}=$section;
 2171:             next;
 2172:         }
 2173:         if (defined($start) && $start && ($now < $start)) {
 2174:             $Pending{$start}=$section;
 2175:             next;
 2176:         }
 2177:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2178:     }
 2179:     #
 2180:     # Presumedly there will be few matching roles from the above
 2181:     # loop and the sorting time will be negligible.
 2182:     if (scalar(keys(%Pending))) {
 2183:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2184:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2185:     } 
 2186:     if (scalar(keys(%Expired))) {
 2187:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2188:         my $time = pop(@sorted);
 2189:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2190:     }
 2191:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2192: }
 2193: 
 2194: sub save_cache {
 2195:     &purge_remembered();
 2196:     #&Apache::loncommon::validate_page();
 2197:     undef(%env);
 2198:     undef($env_loaded);
 2199: }
 2200: 
 2201: my $to_remember=-1;
 2202: my %remembered;
 2203: my %accessed;
 2204: my $kicks=0;
 2205: my $hits=0;
 2206: sub make_key {
 2207:     my ($name,$id) = @_;
 2208:     if (length($id) > 65 
 2209: 	&& length(&escape($id)) > 200) {
 2210: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2211:     }
 2212:     return &escape($name.':'.$id);
 2213: }
 2214: 
 2215: sub devalidate_cache_new {
 2216:     my ($name,$id,$debug) = @_;
 2217:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2218:     $id=&make_key($name,$id);
 2219:     $memcache->delete($id);
 2220:     delete($remembered{$id});
 2221:     delete($accessed{$id});
 2222: }
 2223: 
 2224: sub is_cached_new {
 2225:     my ($name,$id,$debug) = @_;
 2226:     $id=&make_key($name,$id);
 2227:     if (exists($remembered{$id})) {
 2228: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2229: 	$accessed{$id}=[&gettimeofday()];
 2230: 	$hits++;
 2231: 	return ($remembered{$id},1);
 2232:     }
 2233:     my $value = $memcache->get($id);
 2234:     if (!(defined($value))) {
 2235: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2236: 	return (undef,undef);
 2237:     }
 2238:     if ($value eq '__undef__') {
 2239: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2240: 	$value=undef;
 2241:     }
 2242:     &make_room($id,$value,$debug);
 2243:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2244:     return ($value,1);
 2245: }
 2246: 
 2247: sub do_cache_new {
 2248:     my ($name,$id,$value,$time,$debug) = @_;
 2249:     $id=&make_key($name,$id);
 2250:     my $setvalue=$value;
 2251:     if (!defined($setvalue)) {
 2252: 	$setvalue='__undef__';
 2253:     }
 2254:     if (!defined($time) ) {
 2255: 	$time=600;
 2256:     }
 2257:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2258:     my $result = $memcache->set($id,$setvalue,$time);
 2259:     if (! $result) {
 2260: 	&logthis("caching of id -> $id  failed");
 2261: 	$memcache->disconnect_all();
 2262:     }
 2263:     # need to make a copy of $value
 2264:     &make_room($id,$value,$debug);
 2265:     return $value;
 2266: }
 2267: 
 2268: sub make_room {
 2269:     my ($id,$value,$debug)=@_;
 2270: 
 2271:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2272:                                     : $value;
 2273:     if ($to_remember<0) { return; }
 2274:     $accessed{$id}=[&gettimeofday()];
 2275:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2276:     my $to_kick;
 2277:     my $max_time=0;
 2278:     foreach my $other (keys(%accessed)) {
 2279: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2280: 	    $to_kick=$other;
 2281: 	    $max_time=&tv_interval($accessed{$other});
 2282: 	}
 2283:     }
 2284:     delete($remembered{$to_kick});
 2285:     delete($accessed{$to_kick});
 2286:     $kicks++;
 2287:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2288:     return;
 2289: }
 2290: 
 2291: sub purge_remembered {
 2292:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2293:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2294:     undef(%remembered);
 2295:     undef(%accessed);
 2296: }
 2297: # ------------------------------------- Read an entry from a user's environment
 2298: 
 2299: sub userenvironment {
 2300:     my ($udom,$unam,@what)=@_;
 2301:     my $items;
 2302:     foreach my $item (@what) {
 2303:         $items.=&escape($item).'&';
 2304:     }
 2305:     $items=~s/\&$//;
 2306:     my %returnhash=();
 2307:     my $uhome = &homeserver($unam,$udom);
 2308:     unless ($uhome eq 'no_host') {
 2309:         my @answer=split(/\&/, 
 2310:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2311:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2312:             return %returnhash;
 2313:         }
 2314:         my $i;
 2315:         for ($i=0;$i<=$#what;$i++) {
 2316: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2317:         }
 2318:     }
 2319:     return %returnhash;
 2320: }
 2321: 
 2322: # ---------------------------------------------------------- Get a studentphoto
 2323: sub studentphoto {
 2324:     my ($udom,$unam,$ext) = @_;
 2325:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2326:     if (defined($env{'request.course.id'})) {
 2327:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2328:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2329:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2330:             } else {
 2331:                 my ($result,$perm_reqd)=
 2332: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2333:                 if ($result eq 'ok') {
 2334:                     if (!($perm_reqd eq 'yes')) {
 2335:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2336:                     }
 2337:                 }
 2338:             }
 2339:         }
 2340:     } else {
 2341:         my ($result,$perm_reqd) = 
 2342: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2343:         if ($result eq 'ok') {
 2344:             if (!($perm_reqd eq 'yes')) {
 2345:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2346:             }
 2347:         }
 2348:     }
 2349:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2350: }
 2351: 
 2352: sub retrievestudentphoto {
 2353:     my ($udom,$unam,$ext,$type) = @_;
 2354:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2355:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2356:     if ($ret eq 'ok') {
 2357:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2358:         if ($type eq 'thumbnail') {
 2359:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2360:         }
 2361:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2362:         return $tokenurl;
 2363:     } else {
 2364:         if ($type eq 'thumbnail') {
 2365:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2366:         } else { 
 2367:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2368:         }
 2369:     }
 2370: }
 2371: 
 2372: # -------------------------------------------------------------------- New chat
 2373: 
 2374: sub chatsend {
 2375:     my ($newentry,$anon,$group)=@_;
 2376:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2377:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2378:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2379:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2380: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2381: 		   &escape($newentry)).':'.$group,$chome);
 2382: }
 2383: 
 2384: # ------------------------------------------ Find current version of a resource
 2385: 
 2386: sub getversion {
 2387:     my $fname=&clutter(shift);
 2388:     unless ($fname=~/^\/res\//) { return -1; }
 2389:     return &currentversion(&filelocation('',$fname));
 2390: }
 2391: 
 2392: sub currentversion {
 2393:     my $fname=shift;
 2394:     my $author=$fname;
 2395:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2396:     my ($udom,$uname)=split(/\//,$author);
 2397:     my $home=&homeserver($uname,$udom);
 2398:     if ($home eq 'no_host') { 
 2399:         return -1; 
 2400:     }
 2401:     my $answer=&reply("currentversion:$fname",$home);
 2402:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2403: 	return -1;
 2404:     }
 2405:     return $answer;
 2406: }
 2407: 
 2408: #
 2409: # Return special version number of resource if set by override, empty otherwise
 2410: #
 2411: sub usedversion {
 2412:     my $fname=shift;
 2413:     unless ($fname) { $fname=$env{'request.uri'}; }
 2414:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2415:     if ($urlversion) { return $urlversion; }
 2416:     return '';
 2417: }
 2418: 
 2419: # ----------------------------- Subscribe to a resource, return URL if possible
 2420: 
 2421: sub subscribe {
 2422:     my $fname=shift;
 2423:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2424:     $fname=~s/[\n\r]//g;
 2425:     my $author=$fname;
 2426:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2427:     my ($udom,$uname)=split(/\//,$author);
 2428:     my $home=homeserver($uname,$udom);
 2429:     if ($home eq 'no_host') {
 2430:         return 'not_found';
 2431:     }
 2432:     my $answer=reply("sub:$fname",$home);
 2433:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2434: 	$answer.=' by '.$home;
 2435:     }
 2436:     return $answer;
 2437: }
 2438:     
 2439: # -------------------------------------------------------------- Replicate file
 2440: 
 2441: sub repcopy {
 2442:     my $filename=shift;
 2443:     $filename=~s/\/+/\//g;
 2444:     my $londocroot = $perlvar{'lonDocRoot'};
 2445:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2446:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
 2447:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2448: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2449: 	return &repcopy_userfile($filename);
 2450:     }
 2451:     $filename=~s/[\n\r]//g;
 2452:     my $transname="$filename.in.transfer";
 2453: # FIXME: this should flock
 2454:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2455:     my $remoteurl=subscribe($filename);
 2456:     if ($remoteurl =~ /^con_lost by/) {
 2457: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2458:            return 'unavailable';
 2459:     } elsif ($remoteurl eq 'not_found') {
 2460: 	   #&logthis("Subscribe returned not_found: $filename");
 2461: 	   return 'not_found';
 2462:     } elsif ($remoteurl =~ /^rejected by/) {
 2463: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2464:            return 'forbidden';
 2465:     } elsif ($remoteurl eq 'directory') {
 2466:            return 'ok';
 2467:     } else {
 2468:         my $author=$filename;
 2469:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2470:         my ($udom,$uname)=split(/\//,$author);
 2471:         my $home=homeserver($uname,$udom);
 2472:         unless ($home eq $perlvar{'lonHostID'}) {
 2473:            my @parts=split(/\//,$filename);
 2474:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2475:            if ($path ne "$londocroot/res") {
 2476:                &logthis("Malconfiguration for replication: $filename");
 2477: 	       return 'bad_request';
 2478:            }
 2479:            my $count;
 2480:            for ($count=5;$count<$#parts;$count++) {
 2481:                $path.="/$parts[$count]";
 2482:                if ((-e $path)!=1) {
 2483: 		   mkdir($path,0777);
 2484:                }
 2485:            }
 2486:            my $ua=new LWP::UserAgent;
 2487:            my $request=new HTTP::Request('GET',"$remoteurl");
 2488:            my $response=$ua->request($request,$transname);
 2489:            if ($response->is_error()) {
 2490: 	       unlink($transname);
 2491:                my $message=$response->status_line;
 2492:                &logthis("<font color=\"blue\">WARNING:"
 2493:                        ." LWP get: $message: $filename</font>");
 2494:                return 'unavailable';
 2495:            } else {
 2496: 	       if ($remoteurl!~/\.meta$/) {
 2497:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2498:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2499:                   if ($mresponse->is_error()) {
 2500: 		      unlink($filename.'.meta');
 2501:                       &logthis(
 2502:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2503:                   }
 2504: 	       }
 2505:                rename($transname,$filename);
 2506:                return 'ok';
 2507:            }
 2508:        }
 2509:     }
 2510: }
 2511: 
 2512: # ------------------------------------------------ Get server side include body
 2513: sub ssi_body {
 2514:     my ($filelink,%form)=@_;
 2515:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2516:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2517:     }
 2518:     my $output='';
 2519:     my $response;
 2520:     if ($filelink=~/^https?\:/) {
 2521:        ($output,$response)=&externalssi($filelink);
 2522:     } else {
 2523:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2524:        $filelink .= 'inhibitmenu=yes';
 2525:        ($output,$response)=&ssi($filelink,%form);
 2526:     }
 2527:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2528:     $output=~s/^.*?\<body[^\>]*\>//si;
 2529:     $output=~s/\<\/body\s*\>.*?$//si;
 2530:     if (wantarray) {
 2531:         return ($output, $response);
 2532:     } else {
 2533:         return $output;
 2534:     }
 2535: }
 2536: 
 2537: # --------------------------------------------------------- Server Side Include
 2538: 
 2539: sub absolute_url {
 2540:     my ($host_name) = @_;
 2541:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2542:     if ($host_name eq '') {
 2543: 	$host_name = $ENV{'SERVER_NAME'};
 2544:     }
 2545:     return $protocol.$host_name;
 2546: }
 2547: 
 2548: #
 2549: #   Server side include.
 2550: # Parameters:
 2551: #  fn     Possibly encrypted resource name/id.
 2552: #  form   Hash that describes how the rendering should be done
 2553: #         and other things.
 2554: # Returns:
 2555: #   Scalar context: The content of the response.
 2556: #   Array context:  2 element list of the content and the full response object.
 2557: #     
 2558: sub ssi {
 2559: 
 2560:     my ($fn,%form)=@_;
 2561:     my $ua=new LWP::UserAgent;
 2562:     my $request;
 2563: 
 2564:     $form{'no_update_last_known'}=1;
 2565:     &Apache::lonenc::check_encrypt(\$fn);
 2566:     if (%form) {
 2567:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2568:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2569:     } else {
 2570:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2571:     }
 2572: 
 2573:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2574:     my $response=$ua->request($request);
 2575: 
 2576:     if (wantarray) {
 2577: 	return ($response->content, $response);
 2578:     } else {
 2579: 	return $response->content;
 2580:     }
 2581: }
 2582: 
 2583: sub externalssi {
 2584:     my ($url)=@_;
 2585:     my $ua=new LWP::UserAgent;
 2586:     my $request=new HTTP::Request('GET',$url);
 2587:     my $response=$ua->request($request);
 2588:     if (wantarray) {
 2589:         return ($response->content, $response);
 2590:     } else {
 2591:         return $response->content;
 2592:     }
 2593: }
 2594: 
 2595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2596: 
 2597: sub allowuploaded {
 2598:     my ($srcurl,$url)=@_;
 2599:     $url=&clutter(&declutter($url));
 2600:     my $dir=$url;
 2601:     $dir=~s/\/[^\/]+$//;
 2602:     my %httpref=();
 2603:     my $httpurl=&hreflocation('',$url);
 2604:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2605:     &Apache::lonnet::appenv(\%httpref);
 2606: }
 2607: 
 2608: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2609: # input: action, courseID, current domain, intended
 2610: #        path to file, source of file, instruction to parse file for objects,
 2611: #        ref to hash for embedded objects,
 2612: #        ref to hash for codebase of java objects.
 2613: #        reference to scalar to accommodate mime type determined
 2614: #          from File::MMagic if $parser = parse.
 2615: #
 2616: # output: url to file (if action was uploaddoc), 
 2617: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2618: #
 2619: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2620: # course.
 2621: #
 2622: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2623: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2624: #          course's home server.
 2625: #
 2626: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2627: #          be copied from $source (current location) to 
 2628: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2629: #         and will then be copied to
 2630: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2631: #         course's home server.
 2632: #
 2633: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2634: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2635: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2636: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2637: #         in course's home server.
 2638: #
 2639: 
 2640: sub process_coursefile {
 2641:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2642:         $mimetype)=@_;
 2643:     my $fetchresult;
 2644:     my $home=&homeserver($docuname,$docudom);
 2645:     if ($action eq 'propagate') {
 2646:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2647: 			     $home);
 2648:     } else {
 2649:         my $fpath = '';
 2650:         my $fname = $file;
 2651:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2652:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2653:         my $filepath = &build_filepath($fpath);
 2654:         if ($action eq 'copy') {
 2655:             if ($source eq '') {
 2656:                 $fetchresult = 'no source file';
 2657:                 return $fetchresult;
 2658:             } else {
 2659:                 my $destination = $filepath.'/'.$fname;
 2660:                 rename($source,$destination);
 2661:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2662:                                  $home);
 2663:             }
 2664:         } elsif ($action eq 'uploaddoc') {
 2665:             open(my $fh,'>'.$filepath.'/'.$fname);
 2666:             print $fh $env{'form.'.$source};
 2667:             close($fh);
 2668:             if ($parser eq 'parse') {
 2669:                 my $mm = new File::MMagic;
 2670:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2671:                 if ($type eq 'text/html') {
 2672:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2673:                     unless ($parse_result eq 'ok') {
 2674:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2675:                     }
 2676:                 }
 2677:                 if (ref($mimetype)) {
 2678:                     $$mimetype = $type;
 2679:                 } 
 2680:             }
 2681:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2682:                                  $home);
 2683:             if ($fetchresult eq 'ok') {
 2684:                 return '/uploaded/'.$fpath.'/'.$fname;
 2685:             } else {
 2686:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2687:                         ' to host '.$home.': '.$fetchresult);
 2688:                 return '/adm/notfound.html';
 2689:             }
 2690:         }
 2691:     }
 2692:     unless ( $fetchresult eq 'ok') {
 2693:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2694:              ' to host '.$home.': '.$fetchresult);
 2695:     }
 2696:     return $fetchresult;
 2697: }
 2698: 
 2699: sub build_filepath {
 2700:     my ($fpath) = @_;
 2701:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2702:     unless ($fpath eq '') {
 2703:         my @parts=split('/',$fpath);
 2704:         foreach my $part (@parts) {
 2705:             $filepath.= '/'.$part;
 2706:             if ((-e $filepath)!=1) {
 2707:                 mkdir($filepath,0777);
 2708:             }
 2709:         }
 2710:     }
 2711:     return $filepath;
 2712: }
 2713: 
 2714: sub store_edited_file {
 2715:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2716:     my $file = $primary_url;
 2717:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2718:     my $fpath = '';
 2719:     my $fname = $file;
 2720:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2721:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2722:     my $filepath = &build_filepath($fpath);
 2723:     open(my $fh,'>'.$filepath.'/'.$fname);
 2724:     print $fh $content;
 2725:     close($fh);
 2726:     my $home=&homeserver($docuname,$docudom);
 2727:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2728: 			  $home);
 2729:     if ($$fetchresult eq 'ok') {
 2730:         return '/uploaded/'.$fpath.'/'.$fname;
 2731:     } else {
 2732:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2733: 		 ' to host '.$home.': '.$$fetchresult);
 2734:         return '/adm/notfound.html';
 2735:     }
 2736: }
 2737: 
 2738: sub clean_filename {
 2739:     my ($fname,$args)=@_;
 2740: # Replace Windows backslashes by forward slashes
 2741:     $fname=~s/\\/\//g;
 2742:     if (!$args->{'keep_path'}) {
 2743:         # Get rid of everything but the actual filename
 2744: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2745:     }
 2746: # Replace spaces by underscores
 2747:     $fname=~s/\s+/\_/g;
 2748: # Replace all other weird characters by nothing
 2749:     $fname=~s{[^/\w\.\-]}{}g;
 2750: # Replace all .\d. sequences with _\d. so they no longer look like version
 2751: # numbers
 2752:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2753:     return $fname;
 2754: }
 2755: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2756: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2757: # image with the same aspect ratio as the original, but with dimensions which do 
 2758: # not exceed $resizewidth and $resizeheight.
 2759:  
 2760: sub resizeImage {
 2761:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2762:     my $ima = Image::Magick->new;
 2763:     my $resized;
 2764:     if (-e $img_path) {
 2765:         $ima->Read($img_path);
 2766:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2767:             my $width = $ima->Get('width');
 2768:             my $height = $ima->Get('height');
 2769:             if ($width > $resizewidth) {
 2770: 	        my $factor = $width/$resizewidth;
 2771:                 my $newheight = $height/$factor;
 2772:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2773:                 $resized = 1;
 2774:             }
 2775:         }
 2776:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2777:             my $width = $ima->Get('width');
 2778:             my $height = $ima->Get('height');
 2779:             if ($height > $resizeheight) {
 2780:                 my $factor = $height/$resizeheight;
 2781:                 my $newwidth = $width/$factor;
 2782:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2783:                 $resized = 1;
 2784:             }
 2785:         }
 2786:         if ($resized) {
 2787:             $ima->Write($img_path);
 2788:         }
 2789:     }
 2790:     return;
 2791: }
 2792: 
 2793: # --------------- Take an uploaded file and put it into the userfiles directory
 2794: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2795: #                    the desired filename is in $env{"form.$formname.filename"}
 2796: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2797: #                                    canceloverwrite, or ''. 
 2798: #                   if 'coursedoc': upload to the current course
 2799: #                   if 'existingfile': write file to tmp/overwrites directory 
 2800: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2801: #                   $context is passed as argument to &finishuserfileupload
 2802: #        $subdir - directory in userfile to store the file into
 2803: #        $parser - instruction to parse file for objects ($parser = parse)    
 2804: #        $allfiles - reference to hash for embedded objects
 2805: #        $codebase - reference to hash for codebase of java objects
 2806: #        $desuname - username for permanent storage of uploaded file
 2807: #        $dsetudom - domain for permanaent storage of uploaded file
 2808: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2809: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2810: #        $resizewidth - width (pixels) to which to resize uploaded image
 2811: #        $resizeheight - height (pixels) to which to resize uploaded image
 2812: #        $mimetype - reference to scalar to accommodate mime type determined
 2813: #                    from File::MMagic.
 2814: # 
 2815: # output: url of file in userspace, or error: <message> 
 2816: #             or /adm/notfound.html if failure to upload occurse
 2817: 
 2818: sub userfileupload {
 2819:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2820:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2821:     if (!defined($subdir)) { $subdir='unknown'; }
 2822:     my $fname=$env{'form.'.$formname.'.filename'};
 2823:     $fname=&clean_filename($fname);
 2824:     # See if there is anything left
 2825:     unless ($fname) { return 'error: no uploaded file'; }
 2826:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2827:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2828:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2829:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2830:         my $now = time;
 2831:         my $filepath;
 2832:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2833:              $filepath = 'tmp/helprequests/'.$now;
 2834:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2835:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2836:                          '_'.$env{'user.domain'}.'/pending';
 2837:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2838:             my ($docuname,$docudom);
 2839:             if ($destudom) {
 2840:                 $docudom = $destudom;
 2841:             } else {
 2842:                 $docudom = $env{'user.domain'};
 2843:             }
 2844:             if ($destuname) {
 2845:                 $docuname = $destuname;
 2846:             } else {
 2847:                 $docuname = $env{'user.name'};
 2848:             }
 2849:             if (exists($env{'form.group'})) {
 2850:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2851:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2852:             }
 2853:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2854:             if ($context eq 'canceloverwrite') {
 2855:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2856:                 if (-e  $tempfile) {
 2857:                     my @info = stat($tempfile);
 2858:                     if ($info[9] eq $env{'form.timestamp'}) {
 2859:                         unlink($tempfile);
 2860:                     }
 2861:                 }
 2862:                 return;
 2863:             }
 2864:         }
 2865:         # Create the directory if not present
 2866:         my @parts=split(/\//,$filepath);
 2867:         my $fullpath = $perlvar{'lonDaemons'};
 2868:         for (my $i=0;$i<@parts;$i++) {
 2869:             $fullpath .= '/'.$parts[$i];
 2870:             if ((-e $fullpath)!=1) {
 2871:                 mkdir($fullpath,0777);
 2872:             }
 2873:         }
 2874:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2875:         print $fh $env{'form.'.$formname};
 2876:         close($fh);
 2877:         if ($context eq 'existingfile') {
 2878:             my @info = stat($fullpath.'/'.$fname);
 2879:             return ($fullpath.'/'.$fname,$info[9]);
 2880:         } else {
 2881:             return $fullpath.'/'.$fname;
 2882:         }
 2883:     }
 2884:     if ($subdir eq 'scantron') {
 2885:         $fname = 'scantron_orig_'.$fname;
 2886:     } else {
 2887:         $fname="$subdir/$fname";
 2888:     }
 2889:     if ($context eq 'coursedoc') {
 2890: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2891: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2892:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2893:             return &finishuserfileupload($docuname,$docudom,
 2894: 					 $formname,$fname,$parser,$allfiles,
 2895: 					 $codebase,$thumbwidth,$thumbheight,
 2896:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2897:         } else {
 2898:             $fname=$env{'form.folder'}.'/'.$fname;
 2899:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2900: 				       $fname,$formname,$parser,
 2901: 				       $allfiles,$codebase,$mimetype);
 2902:         }
 2903:     } elsif (defined($destuname)) {
 2904:         my $docuname=$destuname;
 2905:         my $docudom=$destudom;
 2906: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2907: 				     $parser,$allfiles,$codebase,
 2908:                                      $thumbwidth,$thumbheight,
 2909:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2910:     } else {
 2911:         my $docuname=$env{'user.name'};
 2912:         my $docudom=$env{'user.domain'};
 2913:         if (exists($env{'form.group'})) {
 2914:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2915:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2916:         }
 2917: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2918: 				     $parser,$allfiles,$codebase,
 2919:                                      $thumbwidth,$thumbheight,
 2920:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2921:     }
 2922: }
 2923: 
 2924: sub finishuserfileupload {
 2925:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2926:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2927:     my $path=$docudom.'/'.$docuname.'/';
 2928:     my $filepath=$perlvar{'lonDocRoot'};
 2929:   
 2930:     my ($fnamepath,$file,$fetchthumb);
 2931:     $file=$fname;
 2932:     if ($fname=~m|/|) {
 2933:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2934: 	$path.=$fnamepath.'/';
 2935:     }
 2936:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2937:     my $count;
 2938:     for ($count=4;$count<=$#parts;$count++) {
 2939:         $filepath.="/$parts[$count]";
 2940:         if ((-e $filepath)!=1) {
 2941: 	    mkdir($filepath,0777);
 2942:         }
 2943:     }
 2944: 
 2945: # Save the file
 2946:     {
 2947: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2948: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2949: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2950: 	    return '/adm/notfound.html';
 2951: 	}
 2952:         if ($context eq 'overwrite') {
 2953:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2954:             my $target = $filepath.'/'.$file;
 2955:             if (-e $source) {
 2956:                 my @info = stat($source);
 2957:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2958:                     unless (&File::Copy::move($source,$target)) {
 2959:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2960:                         return "Moving from $source failed";
 2961:                     }
 2962:                 } else {
 2963:                     return "Temporary file: $source had unexpected date/time for last modification";
 2964:                 }
 2965:             } else {
 2966:                 return "Temporary file: $source missing";
 2967:             }
 2968:         } elsif (!print FH ($env{'form.'.$formname})) {
 2969: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2970: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2971: 	    return '/adm/notfound.html';
 2972: 	}
 2973: 	close(FH);
 2974:         if ($resizewidth && $resizeheight) {
 2975:             my $mm = new File::MMagic;
 2976:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2977:             if ($mime_type =~ m{^image/}) {
 2978: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2979:             }  
 2980: 	}
 2981:     }
 2982:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2983:         if (ref($mimetype)) {
 2984:             if ($$mimetype eq '') {
 2985:                 my $mm = new File::MMagic;
 2986:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2987:                 $$mimetype = $type;
 2988:             }
 2989:         }
 2990:     }
 2991:     if ($parser eq 'parse') {
 2992:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2993:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2994:                                                        $allfiles,$codebase);
 2995:             unless ($parse_result eq 'ok') {
 2996:                 &logthis('Failed to parse '.$filepath.$file.
 2997: 	   	         ' for embedded media: '.$parse_result); 
 2998:             }
 2999:         }
 3000:     }
 3001:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3002:         my $input = $filepath.'/'.$file;
 3003:         my $output = $filepath.'/'.'tn-'.$file;
 3004:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3005:         system("convert -sample $thumbsize $input $output");
 3006:         if (-e $filepath.'/'.'tn-'.$file) {
 3007:             $fetchthumb  = 1; 
 3008:         }
 3009:     }
 3010:  
 3011: # Notify homeserver to grep it
 3012: #
 3013:     my $docuhome=&homeserver($docuname,$docudom);	
 3014:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3015:     if ($fetchresult eq 'ok') {
 3016:         if ($fetchthumb) {
 3017:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3018:             if ($thumbresult ne 'ok') {
 3019:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3020:                          $docuhome.': '.$thumbresult);
 3021:             }
 3022:         }
 3023: #
 3024: # Return the URL to it
 3025:         return '/uploaded/'.$path.$file;
 3026:     } else {
 3027:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3028: 		 ': '.$fetchresult);
 3029:         return '/adm/notfound.html';
 3030:     }
 3031: }
 3032: 
 3033: sub extract_embedded_items {
 3034:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3035:     my @state = ();
 3036:     my %javafiles = (
 3037:                       codebase => '',
 3038:                       code => '',
 3039:                       archive => ''
 3040:                     );
 3041:     my %mediafiles = (
 3042:                       src => '',
 3043:                       movie => '',
 3044:                      );
 3045:     my $p;
 3046:     if ($content) {
 3047:         $p = HTML::LCParser->new($content);
 3048:     } else {
 3049:         $p = HTML::LCParser->new($fullpath);
 3050:     }
 3051:     while (my $t=$p->get_token()) {
 3052: 	if ($t->[0] eq 'S') {
 3053: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3054: 	    push(@state, $tagname);
 3055:             if (lc($tagname) eq 'allow') {
 3056:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3057:             }
 3058: 	    if (lc($tagname) eq 'img') {
 3059: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3060: 	    }
 3061: 	    if (lc($tagname) eq 'a') {
 3062: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3063: 	    }
 3064:             if (lc($tagname) eq 'script') {
 3065:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3066:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3067:                 } else {
 3068:                     &add_filetype($allfiles,$attr->{'src'},'src');
 3069:                 }
 3070:             }
 3071:             if (lc($tagname) eq 'link') {
 3072:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3073:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3074:                 }
 3075:             }
 3076: 	    if (lc($tagname) eq 'object' ||
 3077: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3078: 		foreach my $item (keys(%javafiles)) {
 3079: 		    $javafiles{$item} = '';
 3080: 		}
 3081: 	    }
 3082: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3083: 		my $name = lc($attr->{'name'});
 3084: 		foreach my $item (keys(%javafiles)) {
 3085: 		    if ($name eq $item) {
 3086: 			$javafiles{$item} = $attr->{'value'};
 3087: 			last;
 3088: 		    }
 3089: 		}
 3090: 		foreach my $item (keys(%mediafiles)) {
 3091: 		    if ($name eq $item) {
 3092: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 3093: 			last;
 3094: 		    }
 3095: 		}
 3096: 	    }
 3097: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3098: 		foreach my $item (keys(%javafiles)) {
 3099: 		    if ($attr->{$item}) {
 3100: 			$javafiles{$item} = $attr->{$item};
 3101: 			last;
 3102: 		    }
 3103: 		}
 3104: 		foreach my $item (keys(%mediafiles)) {
 3105: 		    if ($attr->{$item}) {
 3106: 			&add_filetype($allfiles,$attr->{$item},$item);
 3107: 			last;
 3108: 		    }
 3109: 		}
 3110: 	    }
 3111: 	} elsif ($t->[0] eq 'E') {
 3112: 	    my ($tagname) = ($t->[1]);
 3113: 	    if ($javafiles{'codebase'} ne '') {
 3114: 		$javafiles{'codebase'} .= '/';
 3115: 	    }  
 3116: 	    if (lc($tagname) eq 'applet' ||
 3117: 		lc($tagname) eq 'object' ||
 3118: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3119: 		) {
 3120: 		foreach my $item (keys(%javafiles)) {
 3121: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3122: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3123: 			&add_filetype($allfiles,$file,$item);
 3124: 		    }
 3125: 		}
 3126: 	    } 
 3127: 	    pop @state;
 3128: 	}
 3129:     }
 3130:     return 'ok';
 3131: }
 3132: 
 3133: sub add_filetype {
 3134:     my ($allfiles,$file,$type)=@_;
 3135:     if (exists($allfiles->{$file})) {
 3136: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3137: 	    push(@{$allfiles->{$file}}, &escape($type));
 3138: 	}
 3139:     } else {
 3140: 	@{$allfiles->{$file}} = (&escape($type));
 3141:     }
 3142: }
 3143: 
 3144: sub removeuploadedurl {
 3145:     my ($url)=@_;	
 3146:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3147:     return &removeuserfile($uname,$udom,$fname);
 3148: }
 3149: 
 3150: sub removeuserfile {
 3151:     my ($docuname,$docudom,$fname)=@_;
 3152:     my $home=&homeserver($docuname,$docudom);    
 3153:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3154:     if ($result eq 'ok') {	
 3155:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3156:             my $metafile = $fname.'.meta';
 3157:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3158: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3159:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3160:             my $sqlresult = 
 3161:                 &update_portfolio_table($docuname,$docudom,$file,
 3162:                                         'portfolio_metadata',$group,
 3163:                                         'delete');
 3164:         }
 3165:     }
 3166:     return $result;
 3167: }
 3168: 
 3169: sub mkdiruserfile {
 3170:     my ($docuname,$docudom,$dir)=@_;
 3171:     my $home=&homeserver($docuname,$docudom);
 3172:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3173: }
 3174: 
 3175: sub renameuserfile {
 3176:     my ($docuname,$docudom,$old,$new)=@_;
 3177:     my $home=&homeserver($docuname,$docudom);
 3178:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3179:                         &escape("$old").':'.&escape("$new"),$home);
 3180:     if ($result eq 'ok') {
 3181:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3182:             my $oldmeta = $old.'.meta';
 3183:             my $newmeta = $new.'.meta';
 3184:             my $metaresult = 
 3185:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3186: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3187:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3188:             my $sqlresult = 
 3189:                 &update_portfolio_table($docuname,$docudom,$file,
 3190:                                         'portfolio_metadata',$group,
 3191:                                         'delete');
 3192:         }
 3193:     }
 3194:     return $result;
 3195: }
 3196: 
 3197: # ------------------------------------------------------------------------- Log
 3198: 
 3199: sub log {
 3200:     my ($dom,$nam,$hom,$what)=@_;
 3201:     return critical("log:$dom:$nam:$what",$hom);
 3202: }
 3203: 
 3204: # ------------------------------------------------------------------ Course Log
 3205: #
 3206: # This routine flushes several buffers of non-mission-critical nature
 3207: #
 3208: 
 3209: sub flushcourselogs {
 3210:     &logthis('Flushing log buffers');
 3211: #
 3212: # course logs
 3213: # This is a log of all transactions in a course, which can be used
 3214: # for data mining purposes
 3215: #
 3216: # It also collects the courseid database, which lists last transaction
 3217: # times and course titles for all courseids
 3218: #
 3219:     my %courseidbuffer=();
 3220:     foreach my $crsid (keys(%courselogs)) {
 3221:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3222: 		          &escape($courselogs{$crsid}),
 3223: 		          $coursehombuf{$crsid}) eq 'ok') {
 3224: 	    delete $courselogs{$crsid};
 3225:         } else {
 3226:             &logthis('Failed to flush log buffer for '.$crsid);
 3227:             if (length($courselogs{$crsid})>40000) {
 3228:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3229:                         " exceeded maximum size, deleting.</font>");
 3230:                delete $courselogs{$crsid};
 3231:             }
 3232:         }
 3233:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3234:             'description' => $coursedescrbuf{$crsid},
 3235:             'inst_code'    => $courseinstcodebuf{$crsid},
 3236:             'type'        => $coursetypebuf{$crsid},
 3237:             'owner'       => $courseownerbuf{$crsid},
 3238:         };
 3239:     }
 3240: #
 3241: # Write course id database (reverse lookup) to homeserver of courses 
 3242: # Is used in pickcourse
 3243: #
 3244:     foreach my $crs_home (keys(%courseidbuffer)) {
 3245:         my $response = &courseidput(&host_domain($crs_home),
 3246:                                     $courseidbuffer{$crs_home},
 3247:                                     $crs_home,'timeonly');
 3248:     }
 3249: #
 3250: # File accesses
 3251: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3252: #
 3253:     foreach my $entry (keys(%accesshash)) {
 3254:         if ($entry =~ /___count$/) {
 3255:             my ($dom,$name);
 3256:             ($dom,$name,undef)=
 3257: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3258:             if (! defined($dom) || $dom eq '' || 
 3259:                 ! defined($name) || $name eq '') {
 3260:                 my $cid = $env{'request.course.id'};
 3261:                 $dom  = $env{'request.'.$cid.'.domain'};
 3262:                 $name = $env{'request.'.$cid.'.num'};
 3263:             }
 3264:             my $value = $accesshash{$entry};
 3265:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3266:             my %temphash=($url => $value);
 3267:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3268:             if ($result eq 'ok') {
 3269:                 delete $accesshash{$entry};
 3270:             }
 3271:         } else {
 3272:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3273:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3274:             my %temphash=($entry => $accesshash{$entry});
 3275:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3276:                 delete $accesshash{$entry};
 3277:             }
 3278:         }
 3279:     }
 3280: #
 3281: # Roles
 3282: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3283: #
 3284:     foreach my $entry (keys(%userrolehash)) {
 3285:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3286: 	    split(/\:/,$entry);
 3287:         if (&Apache::lonnet::put('nohist_userroles',
 3288:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3289:                 $rudom,$runame) eq 'ok') {
 3290: 	    delete $userrolehash{$entry};
 3291:         }
 3292:     }
 3293: #
 3294: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3295: #
 3296:     my %domrolebuffer = ();
 3297:     foreach my $entry (keys(%domainrolehash)) {
 3298:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3299:         if ($domrolebuffer{$rudom}) {
 3300:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3301:                       '='.&escape($domainrolehash{$entry});
 3302:         } else {
 3303:             $domrolebuffer{$rudom}.=&escape($entry).
 3304:                       '='.&escape($domainrolehash{$entry});
 3305:         }
 3306:         delete $domainrolehash{$entry};
 3307:     }
 3308:     foreach my $dom (keys(%domrolebuffer)) {
 3309: 	my %servers = &get_servers($dom,'library');
 3310: 	foreach my $tryserver (keys(%servers)) {
 3311: 	    unless (&reply('domroleput:'.$dom.':'.
 3312: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3313: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3314: 	    }
 3315:         }
 3316:     }
 3317:     $dumpcount++;
 3318: }
 3319: 
 3320: sub courselog {
 3321:     my $what=shift;
 3322:     $what=time.':'.$what;
 3323:     unless ($env{'request.course.id'}) { return ''; }
 3324:     $coursedombuf{$env{'request.course.id'}}=
 3325:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3326:     $coursenumbuf{$env{'request.course.id'}}=
 3327:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3328:     $coursehombuf{$env{'request.course.id'}}=
 3329:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3330:     $coursedescrbuf{$env{'request.course.id'}}=
 3331:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3332:     $courseinstcodebuf{$env{'request.course.id'}}=
 3333:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3334:     $courseownerbuf{$env{'request.course.id'}}=
 3335:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3336:     $coursetypebuf{$env{'request.course.id'}}=
 3337:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3338:     if (defined $courselogs{$env{'request.course.id'}}) {
 3339: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3340:     } else {
 3341: 	$courselogs{$env{'request.course.id'}}.=$what;
 3342:     }
 3343:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3344: 	&flushcourselogs();
 3345:     }
 3346: }
 3347: 
 3348: sub courseacclog {
 3349:     my $fnsymb=shift;
 3350:     unless ($env{'request.course.id'}) { return ''; }
 3351:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3352:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3353:         $what.=':POST';
 3354:         # FIXME: Probably ought to escape things....
 3355: 	foreach my $key (keys(%env)) {
 3356:             if ($key=~/^form\.(.*)/) {
 3357:                 my $formitem = $1;
 3358:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3359:                     $what.=':'.$formitem.'='.$env{$key};
 3360:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3361:                     $what.=':'.$formitem.'='.$env{$key};
 3362:                 }
 3363:             }
 3364:         }
 3365:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3366:         # FIXME: We should not be depending on a form parameter that someone
 3367:         # editing lonsearchcat.pm might change in the future.
 3368:         if ($env{'form.phase'} eq 'course_search') {
 3369:             $what.= ':POST';
 3370:             # FIXME: Probably ought to escape things....
 3371:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3372:                                  'crsdiscuss') {
 3373:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3374:             }
 3375:         }
 3376:     }
 3377:     &courselog($what);
 3378: }
 3379: 
 3380: sub countacc {
 3381:     my $url=&declutter(shift);
 3382:     return if (! defined($url) || $url eq '');
 3383:     unless ($env{'request.course.id'}) { return ''; }
 3384: #
 3385: # Mark that this url was used in this course
 3386: #
 3387:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3388: #
 3389: # Increase the access count for this resource in this child process
 3390: #
 3391:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3392:     $accesshash{$key}++;
 3393: }
 3394: 
 3395: sub linklog {
 3396:     my ($from,$to)=@_;
 3397:     $from=&declutter($from);
 3398:     $to=&declutter($to);
 3399:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3400:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3401: }
 3402: 
 3403: sub statslog {
 3404:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3405:     if ($users<2) { return; }
 3406:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3407:             'course'       => $env{'request.course.id'},
 3408:             'sections'     => '"all"',
 3409:             'num_students' => $users,
 3410:             'part'         => $part,
 3411:             'symb'         => $symb,
 3412:             'mean_tries'   => $av_attempts,
 3413:             'deg_of_diff'  => $degdiff});
 3414:     foreach my $key (keys(%dynstore)) {
 3415:         $accesshash{$key}=$dynstore{$key};
 3416:     }
 3417: }
 3418:   
 3419: sub userrolelog {
 3420:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3421:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3422:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3423:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3424:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3425:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3426:        $userrolehash
 3427:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3428:                     =$tend.':'.$tstart;
 3429:     }
 3430:     if (($env{'request.role'} =~ /dc\./) &&
 3431: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3432: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3433: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3434:          ($trole=~/^co/))) {
 3435:        $userrolehash
 3436:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3437:                     =$tend.':'.$tstart;
 3438:     }
 3439:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3440:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3441:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3442:         ($trole=~/^sc/)) {
 3443:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3444:        $domainrolehash
 3445:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3446:                     = $tend.':'.$tstart;
 3447:     }
 3448: }
 3449: 
 3450: sub courserolelog {
 3451:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3452:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3453:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3454:         ($trole eq 'ta') || ($trole eq 'st') ||
 3455:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3456:         ($trole eq 'co')) {
 3457:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3458:             my $cdom = $1;
 3459:             my $cnum = $2;
 3460:             my $sec = $3;
 3461:             my $namespace = 'rolelog';
 3462:             my %storehash = (
 3463:                                role    => $trole,
 3464:                                start   => $tstart,
 3465:                                end     => $tend,
 3466:                                selfenroll => $selfenroll,
 3467:                                context    => $context,
 3468:                             );
 3469:             if ($trole eq 'gr') {
 3470:                 $namespace = 'groupslog';
 3471:                 $storehash{'group'} = $sec;
 3472:             } else {
 3473:                 $storehash{'section'} = $sec;
 3474:             }
 3475:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3476:             if (($trole ne 'st') || ($sec ne '')) {
 3477:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3478:             }
 3479:         }
 3480:     }
 3481:     return;
 3482: }
 3483: 
 3484: sub get_course_adv_roles {
 3485:     my ($cid,$codes) = @_;
 3486:     $cid=$env{'request.course.id'} unless (defined($cid));
 3487:     my %coursehash=&coursedescription($cid);
 3488:     my $crstype = &Apache::loncommon::course_type($cid);
 3489:     my %nothide=();
 3490:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3491:         if ($user !~ /:/) {
 3492: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3493:         } else {
 3494:             $nothide{$user}=1;
 3495:         }
 3496:     }
 3497:     my %returnhash=();
 3498:     my %dumphash=
 3499:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3500:     my $now=time;
 3501:     my %privileged;
 3502:     foreach my $entry (keys(%dumphash)) {
 3503: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3504:         if (($tstart) && ($tstart<0)) { next; }
 3505:         if (($tend) && ($tend<$now)) { next; }
 3506:         if (($tstart) && ($now<$tstart)) { next; }
 3507:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3508: 	if ($username eq '' || $domain eq '') { next; }
 3509:         unless (ref($privileged{$domain}) eq 'HASH') {
 3510:             my %dompersonnel =
 3511:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3512:             $privileged{$domain} = {};
 3513:             foreach my $server (keys(%dompersonnel)) {
 3514:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3515:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3516:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3517:                         $privileged{$udom}{$uname} = 1;
 3518:                     }
 3519:                 }
 3520:             }
 3521:         }
 3522:         if ((exists($privileged{$domain}{$username})) && 
 3523:             (!$nothide{$username.':'.$domain})) { next; }
 3524: 	if ($role eq 'cr') { next; }
 3525:         if ($codes) {
 3526:             if ($section) { $role .= ':'.$section; }
 3527:             if ($returnhash{$role}) {
 3528:                 $returnhash{$role}.=','.$username.':'.$domain;
 3529:             } else {
 3530:                 $returnhash{$role}=$username.':'.$domain;
 3531:             }
 3532:         } else {
 3533:             my $key=&plaintext($role,$crstype);
 3534:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3535:             if ($returnhash{$key}) {
 3536: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3537:             } else {
 3538:                 $returnhash{$key}=$username.':'.$domain;
 3539:             }
 3540:         }
 3541:     }
 3542:     return %returnhash;
 3543: }
 3544: 
 3545: sub get_my_roles {
 3546:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3547:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3548:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3549:     my (%dumphash,%nothide);
 3550:     if ($context eq 'userroles') {
 3551:         my $extra = &freeze_escape({'skipcheck' => 1});
 3552:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3553:     } else {
 3554:         %dumphash=
 3555:             &dump('nohist_userroles',$udom,$uname);
 3556:         if ($hidepriv) {
 3557:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3558:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3559:                 if ($user !~ /:/) {
 3560:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3561:                 } else {
 3562:                     $nothide{$user} = 1;
 3563:                 }
 3564:             }
 3565:         }
 3566:     }
 3567:     my %returnhash=();
 3568:     my $now=time;
 3569:     my %privileged;
 3570:     foreach my $entry (keys(%dumphash)) {
 3571:         my ($role,$tend,$tstart);
 3572:         if ($context eq 'userroles') {
 3573:             next if ($entry =~ /^rolesdef/);
 3574: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3575:         } else {
 3576:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3577:         }
 3578:         if (($tstart) && ($tstart<0)) { next; }
 3579:         my $status = 'active';
 3580:         if (($tend) && ($tend<=$now)) {
 3581:             $status = 'previous';
 3582:         } 
 3583:         if (($tstart) && ($now<$tstart)) {
 3584:             $status = 'future';
 3585:         }
 3586:         if (ref($types) eq 'ARRAY') {
 3587:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3588:                 next;
 3589:             } 
 3590:         } else {
 3591:             if ($status ne 'active') {
 3592:                 next;
 3593:             }
 3594:         }
 3595:         my ($rolecode,$username,$domain,$section,$area);
 3596:         if ($context eq 'userroles') {
 3597:             ($area,$rolecode) = split(/_/,$entry);
 3598:             (undef,$domain,$username,$section) = split(/\//,$area);
 3599:         } else {
 3600:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3601:         }
 3602:         if (ref($roledoms) eq 'ARRAY') {
 3603:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3604:                 next;
 3605:             }
 3606:         }
 3607:         if (ref($roles) eq 'ARRAY') {
 3608:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3609:                 if ($role =~ /^cr\//) {
 3610:                     if (!grep(/^cr$/,@{$roles})) {
 3611:                         next;
 3612:                     }
 3613:                 } elsif ($role =~ /^gr\//) {
 3614:                     if (!grep(/^gr$/,@{$roles})) {
 3615:                         next;
 3616:                     }
 3617:                 } else {
 3618:                     next;
 3619:                 }
 3620:             }
 3621:         }
 3622:         if ($hidepriv) {
 3623:             if ($context eq 'userroles') {
 3624:                 if ((&privileged($username,$domain)) &&
 3625:                     (!$nothide{$username.':'.$domain})) {
 3626:                     next;
 3627:                 }
 3628:             } else {
 3629:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3630:                     my %dompersonnel =
 3631:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3632:                     $privileged{$domain} = {};
 3633:                     if (keys(%dompersonnel)) {
 3634:                         foreach my $server (keys(%dompersonnel)) {
 3635:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3636:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3637:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3638:                                     $privileged{$udom}{$uname} = $trole;
 3639:                                 }
 3640:                             }
 3641:                         }
 3642:                     }
 3643:                 }
 3644:                 if (exists($privileged{$domain}{$username})) {
 3645:                     if (!$nothide{$username.':'.$domain}) {
 3646:                         next;
 3647:                     }
 3648:                 }
 3649:             }
 3650:         }
 3651:         if ($withsec) {
 3652:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3653:                 $tstart.':'.$tend;
 3654:         } else {
 3655:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3656:         }
 3657:     }
 3658:     return %returnhash;
 3659: }
 3660: 
 3661: # ----------------------------------------------------- Frontpage Announcements
 3662: #
 3663: #
 3664: 
 3665: sub postannounce {
 3666:     my ($server,$text)=@_;
 3667:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3668:     unless ($text=~/\w/) { $text=''; }
 3669:     return &reply('setannounce:'.&escape($text),$server);
 3670: }
 3671: 
 3672: sub getannounce {
 3673: 
 3674:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3675: 	my $announcement='';
 3676: 	while (my $line = <$fh>) { $announcement .= $line; }
 3677: 	close($fh);
 3678: 	if ($announcement=~/\w/) { 
 3679: 	    return 
 3680:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3681:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3682: 	} else {
 3683: 	    return '';
 3684: 	}
 3685:     } else {
 3686: 	return '';
 3687:     }
 3688: }
 3689: 
 3690: # ---------------------------------------------------------- Course ID routines
 3691: # Deal with domain's nohist_courseid.db files
 3692: #
 3693: 
 3694: sub courseidput {
 3695:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3696:     return unless (ref($storehash) eq 'HASH');
 3697:     my $outcome;
 3698:     if ($caller eq 'timeonly') {
 3699:         my $cids = '';
 3700:         foreach my $item (keys(%$storehash)) {
 3701:             $cids.=&escape($item).'&';
 3702:         }
 3703:         $cids=~s/\&$//;
 3704:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3705:                           $coursehome);       
 3706:     } else {
 3707:         my $items = '';
 3708:         foreach my $item (keys(%$storehash)) {
 3709:             $items.= &escape($item).'='.
 3710:                      &freeze_escape($$storehash{$item}).'&';
 3711:         }
 3712:         $items=~s/\&$//;
 3713:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3714:                           $coursehome);
 3715:     }
 3716:     if ($outcome eq 'unknown_cmd') {
 3717:         my $what;
 3718:         foreach my $cid (keys(%$storehash)) {
 3719:             $what .= &escape($cid).'=';
 3720:             foreach my $item ('description','inst_code','owner','type') {
 3721:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3722:             }
 3723:             $what =~ s/\:$/&/;
 3724:         }
 3725:         $what =~ s/\&$//;  
 3726:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3727:     } else {
 3728:         return $outcome;
 3729:     }
 3730: }
 3731: 
 3732: sub courseiddump {
 3733:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3734:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3735:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3736:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3737:     my $as_hash = 1;
 3738:     my %returnhash;
 3739:     if (!$domfilter) { $domfilter=''; }
 3740:     my %libserv = &all_library();
 3741:     foreach my $tryserver (keys(%libserv)) {
 3742:         if ( (  $hostidflag == 1 
 3743: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3744: 	     || (!defined($hostidflag)) ) {
 3745: 
 3746: 	    if (($domfilter eq '') ||
 3747: 		(&host_domain($tryserver) eq $domfilter)) {
 3748:                 my $rep = 
 3749:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3750:                          $sincefilter.':'.&escape($descfilter).':'.
 3751:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3752:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3753:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3754:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3755:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3756:                          &escape($cc_clone).':'.$cloneonly.':'.
 3757:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3758:                          &escape($creationcontext).':'.$domcloner,
 3759:                          $tryserver);
 3760:                 my @pairs=split(/\&/,$rep);
 3761:                 foreach my $item (@pairs) {
 3762:                     my ($key,$value)=split(/\=/,$item,2);
 3763:                     $key = &unescape($key);
 3764:                     next if ($key =~ /^error: 2 /);
 3765:                     my $result = &thaw_unescape($value);
 3766:                     if (ref($result) eq 'HASH') {
 3767:                         $returnhash{$key}=$result;
 3768:                     } else {
 3769:                         my @responses = split(/:/,$value);
 3770:                         my @items = ('description','inst_code','owner','type');
 3771:                         for (my $i=0; $i<@responses; $i++) {
 3772:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3773:                         }
 3774:                     }
 3775:                 }
 3776:             }
 3777:         }
 3778:     }
 3779:     return %returnhash;
 3780: }
 3781: 
 3782: sub courselastaccess {
 3783:     my ($cdom,$cnum,$hostidref) = @_;
 3784:     my %returnhash;
 3785:     if ($cdom && $cnum) {
 3786:         my $chome = &homeserver($cnum,$cdom);
 3787:         if ($chome ne 'no_host') {
 3788:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3789:             &extract_lastaccess(\%returnhash,$rep);
 3790:         }
 3791:     } else {
 3792:         if (!$cdom) { $cdom=''; }
 3793:         my %libserv = &all_library();
 3794:         foreach my $tryserver (keys(%libserv)) {
 3795:             if (ref($hostidref) eq 'ARRAY') {
 3796:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3797:             } 
 3798:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3799:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3800:                 &extract_lastaccess(\%returnhash,$rep);
 3801:             }
 3802:         }
 3803:     }
 3804:     return %returnhash;
 3805: }
 3806: 
 3807: sub extract_lastaccess {
 3808:     my ($returnhash,$rep) = @_;
 3809:     if (ref($returnhash) eq 'HASH') {
 3810:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3811:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3812:                  $rep eq '') {
 3813:             my @pairs=split(/\&/,$rep);
 3814:             foreach my $item (@pairs) {
 3815:                 my ($key,$value)=split(/\=/,$item,2);
 3816:                 $key = &unescape($key);
 3817:                 next if ($key =~ /^error: 2 /);
 3818:                 $returnhash->{$key} = &thaw_unescape($value);
 3819:             }
 3820:         }
 3821:     }
 3822:     return;
 3823: }
 3824: 
 3825: # ---------------------------------------------------------- DC e-mail
 3826: 
 3827: sub dcmailput {
 3828:     my ($domain,$msgid,$message,$server)=@_;
 3829:     my $status = &Apache::lonnet::critical(
 3830:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3831:        &escape($message),$server);
 3832:     return $status;
 3833: }
 3834: 
 3835: sub dcmaildump {
 3836:     my ($dom,$startdate,$enddate,$senders) = @_;
 3837:     my %returnhash=();
 3838: 
 3839:     if (defined(&domain($dom,'primary'))) {
 3840:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3841:                                                          &escape($enddate).':';
 3842: 	my @esc_senders=map { &escape($_)} @$senders;
 3843: 	$cmd.=&escape(join('&',@esc_senders));
 3844: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3845:             my ($key,$value) = split(/\=/,$line,2);
 3846:             if (($key) && ($value)) {
 3847:                 $returnhash{&unescape($key)} = &unescape($value);
 3848:             }
 3849:         }
 3850:     }
 3851:     return %returnhash;
 3852: }
 3853: # ---------------------------------------------------------- Domain roles
 3854: 
 3855: sub get_domain_roles {
 3856:     my ($dom,$roles,$startdate,$enddate)=@_;
 3857:     if ((!defined($startdate)) || ($startdate eq '')) {
 3858:         $startdate = '.';
 3859:     }
 3860:     if ((!defined($enddate)) || ($enddate eq '')) {
 3861:         $enddate = '.';
 3862:     }
 3863:     my $rolelist;
 3864:     if (ref($roles) eq 'ARRAY') {
 3865:         $rolelist = join(':',@{$roles});
 3866:     }
 3867:     my %personnel = ();
 3868: 
 3869:     my %servers = &get_servers($dom,'library');
 3870:     foreach my $tryserver (keys(%servers)) {
 3871: 	%{$personnel{$tryserver}}=();
 3872: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3873: 					    &escape($startdate).':'.
 3874: 					    &escape($enddate).':'.
 3875: 					    &escape($rolelist), $tryserver))) {
 3876: 	    my ($key,$value) = split(/\=/,$line,2);
 3877: 	    if (($key) && ($value)) {
 3878: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3879: 	    }
 3880: 	}
 3881:     }
 3882:     return %personnel;
 3883: }
 3884: 
 3885: # ----------------------------------------------------------- Interval timing 
 3886: 
 3887: {
 3888: # Caches needed for speedup of navmaps
 3889: # We don't want to cache this for very long at all (5 seconds at most)
 3890: # 
 3891: # The user for whom we cache
 3892: my $cachedkey='';
 3893: # The cached times for this user
 3894: my %cachedtimes=();
 3895: # When this was last done
 3896: my $cachedtime=();
 3897: 
 3898: sub load_all_first_access {
 3899:     my ($uname,$udom)=@_;
 3900:     if (($cachedkey eq $uname.':'.$udom) &&
 3901:         (abs($cachedtime-time)<5)) {
 3902:         return;
 3903:     }
 3904:     $cachedtime=time;
 3905:     $cachedkey=$uname.':'.$udom;
 3906:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3907: }
 3908: 
 3909: sub get_first_access {
 3910:     my ($type,$argsymb)=@_;
 3911:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3912:     if ($argsymb) { $symb=$argsymb; }
 3913:     my ($map,$id,$res)=&decode_symb($symb);
 3914:     if ($type eq 'course') {
 3915: 	$res='course';
 3916:     } elsif ($type eq 'map') {
 3917: 	$res=&symbread($map);
 3918:     } else {
 3919: 	$res=$symb;
 3920:     }
 3921:     &load_all_first_access($uname,$udom);
 3922:     return $cachedtimes{"$courseid\0$res"};
 3923: }
 3924: 
 3925: sub set_first_access {
 3926:     my ($type)=@_;
 3927:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3928:     my ($map,$id,$res)=&decode_symb($symb);
 3929:     if ($type eq 'course') {
 3930: 	$res='course';
 3931:     } elsif ($type eq 'map') {
 3932: 	$res=&symbread($map);
 3933:     } else {
 3934: 	$res=$symb;
 3935:     }
 3936:     $cachedkey='';
 3937:     my $firstaccess=&get_first_access($type,$symb);
 3938:     if (!$firstaccess) {
 3939: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3940:     }
 3941:     return 'already_set';
 3942: }
 3943: }
 3944: # --------------------------------------------- Set Expire Date for Spreadsheet
 3945: 
 3946: sub expirespread {
 3947:     my ($uname,$udom,$stype,$usymb)=@_;
 3948:     my $cid=$env{'request.course.id'}; 
 3949:     if ($cid) {
 3950:        my $now=time;
 3951:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3952:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3953:                             $env{'course.'.$cid.'.num'}.
 3954: 	        	    ':nohist_expirationdates:'.
 3955:                             &escape($key).'='.$now,
 3956:                             $env{'course.'.$cid.'.home'})
 3957:     }
 3958:     return 'ok';
 3959: }
 3960: 
 3961: # ----------------------------------------------------- Devalidate Spreadsheets
 3962: 
 3963: sub devalidate {
 3964:     my ($symb,$uname,$udom)=@_;
 3965:     my $cid=$env{'request.course.id'}; 
 3966:     if ($cid) {
 3967:         # delete the stored spreadsheets for
 3968:         # - the student level sheet of this user in course's homespace
 3969:         # - the assessment level sheet for this resource 
 3970:         #   for this user in user's homespace
 3971: 	# - current conditional state info
 3972: 	my $key=$uname.':'.$udom.':';
 3973:         my $status=
 3974: 	    &del('nohist_calculatedsheets',
 3975: 		 [$key.'studentcalc:'],
 3976: 		 $env{'course.'.$cid.'.domain'},
 3977: 		 $env{'course.'.$cid.'.num'})
 3978: 		.' '.
 3979: 	    &del('nohist_calculatedsheets_'.$cid,
 3980: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3981:         unless ($status eq 'ok ok') {
 3982:            &logthis('Could not devalidate spreadsheet '.
 3983:                     $uname.' at '.$udom.' for '.
 3984: 		    $symb.': '.$status);
 3985:         }
 3986: 	&delenv('user.state.'.$cid);
 3987:     }
 3988: }
 3989: 
 3990: sub get_scalar {
 3991:     my ($string,$end) = @_;
 3992:     my $value;
 3993:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3994: 	$value = $1;
 3995:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3996: 	$value = $1;
 3997:     }
 3998:     return &unescape($value);
 3999: }
 4000: 
 4001: sub array2str {
 4002:   my (@array) = @_;
 4003:   my $result=&arrayref2str(\@array);
 4004:   $result=~s/^__ARRAY_REF__//;
 4005:   $result=~s/__END_ARRAY_REF__$//;
 4006:   return $result;
 4007: }
 4008: 
 4009: sub arrayref2str {
 4010:   my ($arrayref) = @_;
 4011:   my $result='__ARRAY_REF__';
 4012:   foreach my $elem (@$arrayref) {
 4013:     if(ref($elem) eq 'ARRAY') {
 4014:       $result.=&arrayref2str($elem).'&';
 4015:     } elsif(ref($elem) eq 'HASH') {
 4016:       $result.=&hashref2str($elem).'&';
 4017:     } elsif(ref($elem)) {
 4018:       #print("Got a ref of ".(ref($elem))." skipping.");
 4019:     } else {
 4020:       $result.=&escape($elem).'&';
 4021:     }
 4022:   }
 4023:   $result=~s/\&$//;
 4024:   $result .= '__END_ARRAY_REF__';
 4025:   return $result;
 4026: }
 4027: 
 4028: sub hash2str {
 4029:   my (%hash) = @_;
 4030:   my $result=&hashref2str(\%hash);
 4031:   $result=~s/^__HASH_REF__//;
 4032:   $result=~s/__END_HASH_REF__$//;
 4033:   return $result;
 4034: }
 4035: 
 4036: sub hashref2str {
 4037:   my ($hashref)=@_;
 4038:   my $result='__HASH_REF__';
 4039:   foreach my $key (sort(keys(%$hashref))) {
 4040:     if (ref($key) eq 'ARRAY') {
 4041:       $result.=&arrayref2str($key).'=';
 4042:     } elsif (ref($key) eq 'HASH') {
 4043:       $result.=&hashref2str($key).'=';
 4044:     } elsif (ref($key)) {
 4045:       $result.='=';
 4046:       #print("Got a ref of ".(ref($key))." skipping.");
 4047:     } else {
 4048: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4049:     }
 4050: 
 4051:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4052:       $result.=&arrayref2str($hashref->{$key}).'&';
 4053:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4054:       $result.=&hashref2str($hashref->{$key}).'&';
 4055:     } elsif(ref($hashref->{$key})) {
 4056:        $result.='&';
 4057:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4058:     } else {
 4059:       $result.=&escape($hashref->{$key}).'&';
 4060:     }
 4061:   }
 4062:   $result=~s/\&$//;
 4063:   $result .= '__END_HASH_REF__';
 4064:   return $result;
 4065: }
 4066: 
 4067: sub str2hash {
 4068:     my ($string)=@_;
 4069:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4070:     return %$hash;
 4071: }
 4072: 
 4073: sub str2hashref {
 4074:   my ($string) = @_;
 4075: 
 4076:   my %hash;
 4077: 
 4078:   if($string !~ /^__HASH_REF__/) {
 4079:       if (! ($string eq '' || !defined($string))) {
 4080: 	  $hash{'error'}='Not hash reference';
 4081:       }
 4082:       return (\%hash, $string);
 4083:   }
 4084: 
 4085:   $string =~ s/^__HASH_REF__//;
 4086: 
 4087:   while($string !~ /^__END_HASH_REF__/) {
 4088:       #key
 4089:       my $key='';
 4090:       if($string =~ /^__HASH_REF__/) {
 4091:           ($key, $string)=&str2hashref($string);
 4092:           if(defined($key->{'error'})) {
 4093:               $hash{'error'}='Bad data';
 4094:               return (\%hash, $string);
 4095:           }
 4096:       } elsif($string =~ /^__ARRAY_REF__/) {
 4097:           ($key, $string)=&str2arrayref($string);
 4098:           if($key->[0] eq 'Array reference error') {
 4099:               $hash{'error'}='Bad data';
 4100:               return (\%hash, $string);
 4101:           }
 4102:       } else {
 4103:           $string =~ s/^(.*?)=//;
 4104: 	  $key=&unescape($1);
 4105:       }
 4106:       $string =~ s/^=//;
 4107: 
 4108:       #value
 4109:       my $value='';
 4110:       if($string =~ /^__HASH_REF__/) {
 4111:           ($value, $string)=&str2hashref($string);
 4112:           if(defined($value->{'error'})) {
 4113:               $hash{'error'}='Bad data';
 4114:               return (\%hash, $string);
 4115:           }
 4116:       } elsif($string =~ /^__ARRAY_REF__/) {
 4117:           ($value, $string)=&str2arrayref($string);
 4118:           if($value->[0] eq 'Array reference error') {
 4119:               $hash{'error'}='Bad data';
 4120:               return (\%hash, $string);
 4121:           }
 4122:       } else {
 4123: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4124:       }
 4125:       $string =~ s/^&//;
 4126: 
 4127:       $hash{$key}=$value;
 4128:   }
 4129: 
 4130:   $string =~ s/^__END_HASH_REF__//;
 4131: 
 4132:   return (\%hash, $string);
 4133: }
 4134: 
 4135: sub str2array {
 4136:     my ($string)=@_;
 4137:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4138:     return @$array;
 4139: }
 4140: 
 4141: sub str2arrayref {
 4142:   my ($string) = @_;
 4143:   my @array;
 4144: 
 4145:   if($string !~ /^__ARRAY_REF__/) {
 4146:       if (! ($string eq '' || !defined($string))) {
 4147: 	  $array[0]='Array reference error';
 4148:       }
 4149:       return (\@array, $string);
 4150:   }
 4151: 
 4152:   $string =~ s/^__ARRAY_REF__//;
 4153: 
 4154:   while($string !~ /^__END_ARRAY_REF__/) {
 4155:       my $value='';
 4156:       if($string =~ /^__HASH_REF__/) {
 4157:           ($value, $string)=&str2hashref($string);
 4158:           if(defined($value->{'error'})) {
 4159:               $array[0] ='Array reference error';
 4160:               return (\@array, $string);
 4161:           }
 4162:       } elsif($string =~ /^__ARRAY_REF__/) {
 4163:           ($value, $string)=&str2arrayref($string);
 4164:           if($value->[0] eq 'Array reference error') {
 4165:               $array[0] ='Array reference error';
 4166:               return (\@array, $string);
 4167:           }
 4168:       } else {
 4169: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4170:       }
 4171:       $string =~ s/^&//;
 4172: 
 4173:       push(@array, $value);
 4174:   }
 4175: 
 4176:   $string =~ s/^__END_ARRAY_REF__//;
 4177: 
 4178:   return (\@array, $string);
 4179: }
 4180: 
 4181: # -------------------------------------------------------------------Temp Store
 4182: 
 4183: sub tmpreset {
 4184:   my ($symb,$namespace,$domain,$stuname) = @_;
 4185:   if (!$symb) {
 4186:     $symb=&symbread();
 4187:     if (!$symb) { $symb= $env{'request.url'}; }
 4188:   }
 4189:   $symb=escape($symb);
 4190: 
 4191:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4192:   $namespace=~s/\//\_/g;
 4193:   $namespace=~s/\W//g;
 4194: 
 4195:   if (!$domain) { $domain=$env{'user.domain'}; }
 4196:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4197:   if ($domain eq 'public' && $stuname eq 'public') {
 4198:       $stuname=$ENV{'REMOTE_ADDR'};
 4199:   }
 4200:   my $path=LONCAPA::tempdir();
 4201:   my %hash;
 4202:   if (tie(%hash,'GDBM_File',
 4203: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4204: 	  &GDBM_WRCREAT(),0640)) {
 4205:     foreach my $key (keys(%hash)) {
 4206:       if ($key=~ /:$symb/) {
 4207: 	delete($hash{$key});
 4208:       }
 4209:     }
 4210:   }
 4211: }
 4212: 
 4213: sub tmpstore {
 4214:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4215: 
 4216:   if (!$symb) {
 4217:     $symb=&symbread();
 4218:     if (!$symb) { $symb= $env{'request.url'}; }
 4219:   }
 4220:   $symb=escape($symb);
 4221: 
 4222:   if (!$namespace) {
 4223:     # I don't think we would ever want to store this for a course.
 4224:     # it seems this will only be used if we don't have a course.
 4225:     #$namespace=$env{'request.course.id'};
 4226:     #if (!$namespace) {
 4227:       $namespace=$env{'request.state'};
 4228:     #}
 4229:   }
 4230:   $namespace=~s/\//\_/g;
 4231:   $namespace=~s/\W//g;
 4232:   if (!$domain) { $domain=$env{'user.domain'}; }
 4233:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4234:   if ($domain eq 'public' && $stuname eq 'public') {
 4235:       $stuname=$ENV{'REMOTE_ADDR'};
 4236:   }
 4237:   my $now=time;
 4238:   my %hash;
 4239:   my $path=LONCAPA::tempdir();
 4240:   if (tie(%hash,'GDBM_File',
 4241: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4242: 	  &GDBM_WRCREAT(),0640)) {
 4243:     $hash{"version:$symb"}++;
 4244:     my $version=$hash{"version:$symb"};
 4245:     my $allkeys=''; 
 4246:     foreach my $key (keys(%$storehash)) {
 4247:       $allkeys.=$key.':';
 4248:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4249:     }
 4250:     $hash{"$version:$symb:timestamp"}=$now;
 4251:     $allkeys.='timestamp';
 4252:     $hash{"$version:keys:$symb"}=$allkeys;
 4253:     if (untie(%hash)) {
 4254:       return 'ok';
 4255:     } else {
 4256:       return "error:$!";
 4257:     }
 4258:   } else {
 4259:     return "error:$!";
 4260:   }
 4261: }
 4262: 
 4263: # -----------------------------------------------------------------Temp Restore
 4264: 
 4265: sub tmprestore {
 4266:   my ($symb,$namespace,$domain,$stuname) = @_;
 4267: 
 4268:   if (!$symb) {
 4269:     $symb=&symbread();
 4270:     if (!$symb) { $symb= $env{'request.url'}; }
 4271:   }
 4272:   $symb=escape($symb);
 4273: 
 4274:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4275: 
 4276:   if (!$domain) { $domain=$env{'user.domain'}; }
 4277:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4278:   if ($domain eq 'public' && $stuname eq 'public') {
 4279:       $stuname=$ENV{'REMOTE_ADDR'};
 4280:   }
 4281:   my %returnhash;
 4282:   $namespace=~s/\//\_/g;
 4283:   $namespace=~s/\W//g;
 4284:   my %hash;
 4285:   my $path=LONCAPA::tempdir();
 4286:   if (tie(%hash,'GDBM_File',
 4287: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4288: 	  &GDBM_READER(),0640)) {
 4289:     my $version=$hash{"version:$symb"};
 4290:     $returnhash{'version'}=$version;
 4291:     my $scope;
 4292:     for ($scope=1;$scope<=$version;$scope++) {
 4293:       my $vkeys=$hash{"$scope:keys:$symb"};
 4294:       my @keys=split(/:/,$vkeys);
 4295:       my $key;
 4296:       $returnhash{"$scope:keys"}=$vkeys;
 4297:       foreach $key (@keys) {
 4298: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4299: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4300:       }
 4301:     }
 4302:     if (!(untie(%hash))) {
 4303:       return "error:$!";
 4304:     }
 4305:   } else {
 4306:     return "error:$!";
 4307:   }
 4308:   return %returnhash;
 4309: }
 4310: 
 4311: # ----------------------------------------------------------------------- Store
 4312: 
 4313: sub store {
 4314:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4315:     my $home='';
 4316: 
 4317:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4318: 
 4319:     $symb=&symbclean($symb);
 4320:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4321: 
 4322:     if (!$domain) { $domain=$env{'user.domain'}; }
 4323:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4324: 
 4325:     &devalidate($symb,$stuname,$domain);
 4326: 
 4327:     $symb=escape($symb);
 4328:     if (!$namespace) { 
 4329:        unless ($namespace=$env{'request.course.id'}) { 
 4330:           return ''; 
 4331:        } 
 4332:     }
 4333:     if (!$home) { $home=$env{'user.home'}; }
 4334: 
 4335:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4336:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4337: 
 4338:     my $namevalue='';
 4339:     foreach my $key (keys(%$storehash)) {
 4340:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4341:     }
 4342:     $namevalue=~s/\&$//;
 4343:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4344:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4345: }
 4346: 
 4347: # -------------------------------------------------------------- Critical Store
 4348: 
 4349: sub cstore {
 4350:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4351:     my $home='';
 4352: 
 4353:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4354: 
 4355:     $symb=&symbclean($symb);
 4356:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4357: 
 4358:     if (!$domain) { $domain=$env{'user.domain'}; }
 4359:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4360: 
 4361:     &devalidate($symb,$stuname,$domain);
 4362: 
 4363:     $symb=escape($symb);
 4364:     if (!$namespace) { 
 4365:        unless ($namespace=$env{'request.course.id'}) { 
 4366:           return ''; 
 4367:        } 
 4368:     }
 4369:     if (!$home) { $home=$env{'user.home'}; }
 4370: 
 4371:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4372:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4373: 
 4374:     my $namevalue='';
 4375:     foreach my $key (keys(%$storehash)) {
 4376:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4377:     }
 4378:     $namevalue=~s/\&$//;
 4379:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4380:     return critical
 4381:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4382: }
 4383: 
 4384: # --------------------------------------------------------------------- Restore
 4385: 
 4386: sub restore {
 4387:     my ($symb,$namespace,$domain,$stuname) = @_;
 4388:     my $home='';
 4389: 
 4390:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4391: 
 4392:     if (!$symb) {
 4393:       unless ($symb=escape(&symbread())) { return ''; }
 4394:     } else {
 4395:       $symb=&escape(&symbclean($symb));
 4396:     }
 4397:     if (!$namespace) { 
 4398:        unless ($namespace=$env{'request.course.id'}) { 
 4399:           return ''; 
 4400:        } 
 4401:     }
 4402:     if (!$domain) { $domain=$env{'user.domain'}; }
 4403:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4404:     if (!$home) { $home=$env{'user.home'}; }
 4405:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4406: 
 4407:     my %returnhash=();
 4408:     foreach my $line (split(/\&/,$answer)) {
 4409: 	my ($name,$value)=split(/\=/,$line);
 4410:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4411:     }
 4412:     my $version;
 4413:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4414:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4415:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4416:        }
 4417:     }
 4418:     return %returnhash;
 4419: }
 4420: 
 4421: # ---------------------------------------------------------- Course Description
 4422: #
 4423: #  
 4424: 
 4425: sub coursedescription {
 4426:     my ($courseid,$args)=@_;
 4427:     $courseid=~s/^\///;
 4428:     $courseid=~s/\_/\//g;
 4429:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4430:     my $chome=&homeserver($cnum,$cdomain);
 4431:     my $normalid=$cdomain.'_'.$cnum;
 4432:     # need to always cache even if we get errors otherwise we keep 
 4433:     # trying and trying and trying to get the course description.
 4434:     my %envhash=();
 4435:     my %returnhash=();
 4436:     
 4437:     my $expiretime=600;
 4438:     if ($env{'request.course.id'} eq $normalid) {
 4439: 	$expiretime=120;
 4440:     }
 4441: 
 4442:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4443:     if (!$args->{'freshen_cache'}
 4444: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4445: 	foreach my $key (keys(%env)) {
 4446: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4447: 	    my ($setting) = $1;
 4448: 	    $returnhash{$setting} = $env{$key};
 4449: 	}
 4450: 	return %returnhash;
 4451:     }
 4452: 
 4453:     # get the data again
 4454: 
 4455:     if (!$args->{'one_time'}) {
 4456: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4457:     }
 4458: 
 4459:     if ($chome ne 'no_host') {
 4460:        %returnhash=&dump('environment',$cdomain,$cnum);
 4461:        if (!exists($returnhash{'con_lost'})) {
 4462: 	   my $username = $env{'user.name'}; # Defult username
 4463: 	   if(defined $args->{'user'}) {
 4464: 	       $username = $args->{'user'};
 4465: 	   }
 4466:            $returnhash{'home'}= $chome;
 4467: 	   $returnhash{'domain'} = $cdomain;
 4468: 	   $returnhash{'num'} = $cnum;
 4469:            if (!defined($returnhash{'type'})) {
 4470:                $returnhash{'type'} = 'Course';
 4471:            }
 4472:            while (my ($name,$value) = each %returnhash) {
 4473:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4474:            }
 4475:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4476:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4477: 	       $username.'_'.$cdomain.'_'.$cnum;
 4478:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4479:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4480:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4481:        }
 4482:     }
 4483:     if (!$args->{'one_time'}) {
 4484: 	&appenv(\%envhash);
 4485:     }
 4486:     return %returnhash;
 4487: }
 4488: 
 4489: sub update_released_required {
 4490:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4491:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4492:         $cid = $env{'request.course.id'};
 4493:         $cdom = $env{'course.'.$cid.'.domain'};
 4494:         $cnum = $env{'course.'.$cid.'.num'};
 4495:         $chome = $env{'course.'.$cid.'.home'};
 4496:     }
 4497:     if ($needsrelease) {
 4498:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4499:         my $needsupdate;
 4500:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4501:             $needsupdate = 1;
 4502:         } else {
 4503:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4504:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4505:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4506:                 $needsupdate = 1;
 4507:             }
 4508:         }
 4509:         if ($needsupdate) {
 4510:             my %needshash = (
 4511:                              'internal.releaserequired' => $needsrelease,
 4512:                             );
 4513:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4514:             if ($putresult eq 'ok') {
 4515:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4516:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4517:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4518:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4519:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4520:                 }
 4521:             }
 4522:         }
 4523:     }
 4524:     return;
 4525: }
 4526: 
 4527: # -------------------------------------------------See if a user is privileged
 4528: 
 4529: sub privileged {
 4530:     my ($username,$domain)=@_;
 4531:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4532: 			&homeserver($username,$domain));
 4533:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4534:         ($rolesdump =~ /^error:/)) {
 4535:         return 0;
 4536:     }
 4537:     my $now=time;
 4538:     if ($rolesdump ne '') {
 4539:         foreach my $entry (split(/&/,$rolesdump)) {
 4540: 	    if ($entry!~/^rolesdef_/) {
 4541: 		my ($area,$role)=split(/=/,$entry);
 4542: 		$area=~s/\_\w\w$//;
 4543: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4544: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4545: 		    my $active=1;
 4546: 		    if ($tend) {
 4547: 			if ($tend<$now) { $active=0; }
 4548: 		    }
 4549: 		    if ($tstart) {
 4550: 			if ($tstart>$now) { $active=0; }
 4551: 		    }
 4552: 		    if ($active) { return 1; }
 4553: 		}
 4554: 	    }
 4555: 	}
 4556:     }
 4557:     return 0;
 4558: }
 4559: 
 4560: # -------------------------------------------------------- Get user privileges
 4561: 
 4562: sub rolesinit {
 4563:     my ($domain,$username,$authhost)=@_;
 4564:     my $now=time;
 4565:     my %userroles = ('user.login.time' => $now);
 4566:     my $extra = &freeze_escape({'skipcheck' => 1});
 4567:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4568:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4569:         ($rolesdump =~ /^error:/)) {
 4570:         return \%userroles;
 4571:     }
 4572:     my %allroles=();
 4573:     my %allgroups=();   
 4574: 
 4575:     if ($rolesdump ne '') {
 4576:         foreach my $entry (split(/&/,$rolesdump)) {
 4577: 	  if ($entry!~/^rolesdef_/) {
 4578:             my ($area,$role)=split(/=/,$entry);
 4579: 	    $area=~s/\_\w\w$//;
 4580:             my ($trole,$tend,$tstart,$group_privs);
 4581: 	    if ($role=~/^cr/) { 
 4582: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4583: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4584: 		    ($tend,$tstart)=split('_',$trest);
 4585: 		} else {
 4586: 		    $trole=$role;
 4587: 		}
 4588:             } elsif ($role =~ m|^gr/|) {
 4589:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4590:                 next if ($tstart eq '-1');
 4591:                 ($trole,$group_privs) = split(/\//,$trole);
 4592:                 $group_privs = &unescape($group_privs);
 4593: 	    } else {
 4594: 		($trole,$tend,$tstart)=split(/_/,$role);
 4595: 	    }
 4596: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4597: 					 $username);
 4598: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4599:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4600:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4601:             if (($area ne '') && ($trole ne '')) {
 4602: 		my $spec=$trole.'.'.$area;
 4603: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4604: 		if ($trole =~ /^cr\//) {
 4605:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4606:                 } elsif ($trole eq 'gr') {
 4607:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4608: 		} else {
 4609:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4610: 		}
 4611:             }
 4612:           }
 4613:         }
 4614:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4615:         $userroles{'user.adv'}    = $adv;
 4616: 	$userroles{'user.author'} = $author;
 4617:         $env{'user.adv'}=$adv;
 4618:     }
 4619:     return \%userroles;  
 4620: }
 4621: 
 4622: sub set_arearole {
 4623:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4624: # log the associated role with the area
 4625:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4626:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4627: }
 4628: 
 4629: sub custom_roleprivs {
 4630:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4631:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4632:     my $homsvr=homeserver($rauthor,$rdomain);
 4633:     if (&hostname($homsvr) ne '') {
 4634:         my ($rdummy,$roledef)=
 4635:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4636:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4637:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4638:             if (defined($syspriv)) {
 4639:                 if ($trest =~ /^$match_community$/) {
 4640:                     $syspriv =~ s/bre\&S//; 
 4641:                 }
 4642:                 $$allroles{'cm./'}.=':'.$syspriv;
 4643:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4644:             }
 4645:             if ($tdomain ne '') {
 4646:                 if (defined($dompriv)) {
 4647:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4648:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4649:                 }
 4650:                 if (($trest ne '') && (defined($coursepriv))) {
 4651:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4652:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4653:                 }
 4654:             }
 4655:         }
 4656:     }
 4657: }
 4658: 
 4659: sub group_roleprivs {
 4660:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4661:     my $access = 1;
 4662:     my $now = time;
 4663:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4664:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4665:     if ($access) {
 4666:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4667:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4668:     }
 4669: }
 4670: 
 4671: sub standard_roleprivs {
 4672:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4673:     if (defined($pr{$trole.':s'})) {
 4674:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4675:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4676:     }
 4677:     if ($tdomain ne '') {
 4678:         if (defined($pr{$trole.':d'})) {
 4679:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4680:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4681:         }
 4682:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4683:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4684:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4685:         }
 4686:     }
 4687: }
 4688: 
 4689: sub set_userprivs {
 4690:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4691:     my $author=0;
 4692:     my $adv=0;
 4693:     my %grouproles = ();
 4694:     if (keys(%{$allgroups}) > 0) {
 4695:         my @groupkeys; 
 4696:         foreach my $role (keys(%{$allroles})) {
 4697:             push(@groupkeys,$role);
 4698:         }
 4699:         if (ref($groups_roles) eq 'HASH') {
 4700:             foreach my $key (keys(%{$groups_roles})) {
 4701:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4702:                     push(@groupkeys,$key);
 4703:                 }
 4704:             }
 4705:         }
 4706:         if (@groupkeys > 0) {
 4707:             foreach my $role (@groupkeys) {
 4708:                 my ($trole,$area,$sec,$extendedarea);
 4709:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4710:                     $trole = $1;
 4711:                     $area = $2;
 4712:                     $sec = $3;
 4713:                     $extendedarea = $area.$sec;
 4714:                     if (exists($$allgroups{$area})) {
 4715:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4716:                             my $spec = $trole.'.'.$extendedarea;
 4717:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4718:                                                 $$allgroups{$area}{$group};
 4719:                         }
 4720:                     }
 4721:                 }
 4722:             }
 4723:         }
 4724:     }
 4725:     foreach my $group (keys(%grouproles)) {
 4726:         $$allroles{$group} = $grouproles{$group};
 4727:     }
 4728:     foreach my $role (keys(%{$allroles})) {
 4729:         my %thesepriv;
 4730:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4731:         foreach my $item (split(/:/,$$allroles{$role})) {
 4732:             if ($item ne '') {
 4733:                 my ($privilege,$restrictions)=split(/&/,$item);
 4734:                 if ($restrictions eq '') {
 4735:                     $thesepriv{$privilege}='F';
 4736:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4737:                     $thesepriv{$privilege}.=$restrictions;
 4738:                 }
 4739:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4740:             }
 4741:         }
 4742:         my $thesestr='';
 4743:         foreach my $priv (sort(keys(%thesepriv))) {
 4744: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4745: 	}
 4746:         $userroles->{'user.priv.'.$role} = $thesestr;
 4747:     }
 4748:     return ($author,$adv);
 4749: }
 4750: 
 4751: sub role_status {
 4752:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4753:     my @pwhere = ();
 4754:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4755:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4756:         unless (!defined($$role) || $$role eq '') {
 4757:             $$where=join('.',@pwhere);
 4758:             $$trolecode=$$role.'.'.$$where;
 4759:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4760:             $$tstatus='is';
 4761:             if ($$tstart && $$tstart>$update) {
 4762:                 $$tstatus='future';
 4763:                 if ($$tstart<$now) {
 4764:                     if ($$tstart && $$tstart>$refresh) {
 4765:                         if (($$where ne '') && ($$role ne '')) {
 4766:                             my (%allroles,%allgroups,$group_privs,
 4767:                                 %groups_roles,@rolecodes);
 4768:                             my %userroles = (
 4769:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4770:                             );
 4771:                             @rolecodes = ('cm'); 
 4772:                             my $spec=$$role.'.'.$$where;
 4773:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4774:                             if ($$role =~ /^cr\//) {
 4775:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4776:                                 push(@rolecodes,'cr');
 4777:                             } elsif ($$role eq 'gr') {
 4778:                                 push(@rolecodes,$$role);
 4779:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4780:                                                     $env{'user.name'});
 4781:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4782:                                 (undef,my $group_privs) = split(/\//,$trole);
 4783:                                 $group_privs = &unescape($group_privs);
 4784:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4785:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4786:                                 &get_groups_roles($tdomain,$trest,
 4787:                                                   \%course_roles,\@rolecodes,
 4788:                                                   \%groups_roles);
 4789:                             } else {
 4790:                                 push(@rolecodes,$$role);
 4791:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4792:                             }
 4793:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4794:                             &appenv(\%userroles,\@rolecodes);
 4795:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4796:                         }
 4797:                     }
 4798:                     $$tstatus = 'is';
 4799:                 }
 4800:             }
 4801:             if ($$tend) {
 4802:                 if ($$tend<$update) {
 4803:                     $$tstatus='expired';
 4804:                 } elsif ($$tend<$now) {
 4805:                     $$tstatus='will_not';
 4806:                 }
 4807:             }
 4808:         }
 4809:     }
 4810: }
 4811: 
 4812: sub get_groups_roles {
 4813:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4814:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4815:                   (ref($rolecodes) eq 'ARRAY') && 
 4816:                   (ref($groups_roles) eq 'HASH')); 
 4817:     if (keys(%{$cdom_courseroles}) > 0) {
 4818:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4819:         if ($cdom ne '' && $cnum ne '') {
 4820:             foreach my $key (keys(%{$cdom_courseroles})) {
 4821:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4822:                     my $crsrole = $1;
 4823:                     my $crssec = $2;
 4824:                     if ($crsrole =~ /^cr/) {
 4825:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4826:                             push(@{$rolecodes},'cr');
 4827:                         }
 4828:                     } else {
 4829:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4830:                             push(@{$rolecodes},$crsrole);
 4831:                         }
 4832:                     }
 4833:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4834:                     if ($crssec ne '') {
 4835:                         $rolekey .= "/$crssec";
 4836:                     }
 4837:                     $rolekey .= './';
 4838:                     $groups_roles->{$rolekey} = $rolecodes;
 4839:                 }
 4840:             }
 4841:         }
 4842:     }
 4843:     return;
 4844: }
 4845: 
 4846: sub delete_env_groupprivs {
 4847:     my ($where,$courseroles,$possroles) = @_;
 4848:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4849:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4850:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4851:         %{$courseroles->{$udom}} =
 4852:             &get_my_roles('','','userroles',['active'],
 4853:                           $possroles,[$udom],1);
 4854:     }
 4855:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4856:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4857:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4858:             my $area = '/'.$cdom.'/'.$cnum;
 4859:             my $privkey = "user.priv.$crsrole.$area";
 4860:             if ($crssec ne '') {
 4861:                 $privkey .= '/'.$crssec;
 4862:             }
 4863:             $privkey .= ".$area/$group";
 4864:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4865:         }
 4866:     }
 4867:     return;
 4868: }
 4869: 
 4870: sub check_adhoc_privs {
 4871:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4872:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4873:     if ($env{$cckey}) {
 4874:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4875:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4876:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4877:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4878:         }
 4879:     } else {
 4880:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4881:     }
 4882: }
 4883: 
 4884: sub set_adhoc_privileges {
 4885: # role can be cc or ca
 4886:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4887:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4888:     my $spec = $role.'.'.$area;
 4889:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4890:                                   $env{'user.name'});
 4891:     my %ccrole = ();
 4892:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4893:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4894:     &appenv(\%userroles,[$role,'cm']);
 4895:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4896:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 4897:         &appenv( {'request.role'        => $spec,
 4898:                   'request.role.domain' => $dcdom,
 4899:                   'request.course.sec'  => ''
 4900:                  }
 4901:                );
 4902:         my $tadv=0;
 4903:         if (&allowed('adv') eq 'F') { $tadv=1; }
 4904:         &appenv({'request.role.adv'    => $tadv});
 4905:     }
 4906: }
 4907: 
 4908: # --------------------------------------------------------------- get interface
 4909: 
 4910: sub get {
 4911:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4912:    my $items='';
 4913:    foreach my $item (@$storearr) {
 4914:        $items.=&escape($item).'&';
 4915:    }
 4916:    $items=~s/\&$//;
 4917:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4918:    if (!$uname) { $uname=$env{'user.name'}; }
 4919:    my $uhome=&homeserver($uname,$udomain);
 4920: 
 4921:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4922:    my @pairs=split(/\&/,$rep);
 4923:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4924:      return @pairs;
 4925:    }
 4926:    my %returnhash=();
 4927:    my $i=0;
 4928:    foreach my $item (@$storearr) {
 4929:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4930:       $i++;
 4931:    }
 4932:    return %returnhash;
 4933: }
 4934: 
 4935: # --------------------------------------------------------------- del interface
 4936: 
 4937: sub del {
 4938:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4939:    my $items='';
 4940:    foreach my $item (@$storearr) {
 4941:        $items.=&escape($item).'&';
 4942:    }
 4943: 
 4944:    $items=~s/\&$//;
 4945:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4946:    if (!$uname) { $uname=$env{'user.name'}; }
 4947:    my $uhome=&homeserver($uname,$udomain);
 4948:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4949: }
 4950: 
 4951: # -------------------------------------------------------------- dump interface
 4952: 
 4953: sub dump {
 4954:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 4955:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4956:     if (!$uname) { $uname=$env{'user.name'}; }
 4957:     my $uhome=&homeserver($uname,$udomain);
 4958:     if ($regexp) {
 4959: 	$regexp=&escape($regexp);
 4960:     } else {
 4961: 	$regexp='.';
 4962:     }
 4963:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 4964:     my @pairs=split(/\&/,$rep);
 4965:     my %returnhash=();
 4966:     if (!($rep =~ /^error/ )) {
 4967: 	foreach my $item (@pairs) {
 4968: 	    my ($key,$value)=split(/=/,$item,2);
 4969: 	    $key = &unescape($key);
 4970: 	    next if ($key =~ /^error: 2 /);
 4971: 	    $returnhash{$key}=&thaw_unescape($value);
 4972: 	}
 4973:     }
 4974:     return %returnhash;
 4975: }
 4976: 
 4977: 
 4978: # --------------------------------------------------------- dumpstore interface
 4979: 
 4980: sub dumpstore {
 4981:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4982:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4983:    if (!$uname) { $uname=$env{'user.name'}; }
 4984:    my $uhome=&homeserver($uname,$udomain);
 4985:    if ($regexp) {
 4986:        $regexp=&escape($regexp);
 4987:    } else {
 4988:        $regexp='.';
 4989:    }
 4990:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4991:    my @pairs=split(/\&/,$rep);
 4992:    my %returnhash=();
 4993:    foreach my $item (@pairs) {
 4994:        my ($key,$value)=split(/=/,$item,2);
 4995:        next if ($key =~ /^error: 2 /);
 4996:        $returnhash{$key}=&thaw_unescape($value);
 4997:    }
 4998:    return %returnhash;
 4999: }
 5000: 
 5001: # -------------------------------------------------------------- keys interface
 5002: 
 5003: sub getkeys {
 5004:    my ($namespace,$udomain,$uname)=@_;
 5005:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5006:    if (!$uname) { $uname=$env{'user.name'}; }
 5007:    my $uhome=&homeserver($uname,$udomain);
 5008:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5009:    my @keyarray=();
 5010:    foreach my $key (split(/\&/,$rep)) {
 5011:       next if ($key =~ /^error: 2 /);
 5012:       push(@keyarray,&unescape($key));
 5013:    }
 5014:    return @keyarray;
 5015: }
 5016: 
 5017: # --------------------------------------------------------------- currentdump
 5018: sub currentdump {
 5019:    my ($courseid,$sdom,$sname)=@_;
 5020:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5021:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5022:    $sname    = $env{'user.name'}         if (! defined($sname));
 5023:    my $uhome = &homeserver($sname,$sdom);
 5024:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5025:    return if ($rep =~ /^(error:|no_such_host)/);
 5026:    #
 5027:    my %returnhash=();
 5028:    #
 5029:    if ($rep eq "unknown_cmd") { 
 5030:        # an old lond will not know currentdump
 5031:        # Do a dump and make it look like a currentdump
 5032:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5033:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5034:        my %hash = @tmp;
 5035:        @tmp=();
 5036:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5037:    } else {
 5038:        my @pairs=split(/\&/,$rep);
 5039:        foreach my $pair (@pairs) {
 5040:            my ($key,$value)=split(/=/,$pair,2);
 5041:            my ($symb,$param) = split(/:/,$key);
 5042:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5043:                                                         &thaw_unescape($value);
 5044:        }
 5045:    }
 5046:    return %returnhash;
 5047: }
 5048: 
 5049: sub convert_dump_to_currentdump{
 5050:     my %hash = %{shift()};
 5051:     my %returnhash;
 5052:     # Code ripped from lond, essentially.  The only difference
 5053:     # here is the unescaping done by lonnet::dump().  Conceivably
 5054:     # we might run in to problems with parameter names =~ /^v\./
 5055:     while (my ($key,$value) = each(%hash)) {
 5056:         my ($v,$symb,$param) = split(/:/,$key);
 5057: 	$symb  = &unescape($symb);
 5058: 	$param = &unescape($param);
 5059:         next if ($v eq 'version' || $symb eq 'keys');
 5060:         next if (exists($returnhash{$symb}) &&
 5061:                  exists($returnhash{$symb}->{$param}) &&
 5062:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5063:         $returnhash{$symb}->{$param}=$value;
 5064:         $returnhash{$symb}->{'v.'.$param}=$v;
 5065:     }
 5066:     #
 5067:     # Remove all of the keys in the hashes which keep track of
 5068:     # the version of the parameter.
 5069:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5070:         # use a foreach because we are going to delete from the hash.
 5071:         foreach my $key (keys(%$param_hash)) {
 5072:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5073:         }
 5074:     }
 5075:     return \%returnhash;
 5076: }
 5077: 
 5078: # ------------------------------------------------------ critical inc interface
 5079: 
 5080: sub cinc {
 5081:     return &inc(@_,'critical');
 5082: }
 5083: 
 5084: # --------------------------------------------------------------- inc interface
 5085: 
 5086: sub inc {
 5087:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5088:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5089:     if (!$uname) { $uname=$env{'user.name'}; }
 5090:     my $uhome=&homeserver($uname,$udomain);
 5091:     my $items='';
 5092:     if (! ref($store)) {
 5093:         # got a single value, so use that instead
 5094:         $items = &escape($store).'=&';
 5095:     } elsif (ref($store) eq 'SCALAR') {
 5096:         $items = &escape($$store).'=&';        
 5097:     } elsif (ref($store) eq 'ARRAY') {
 5098:         $items = join('=&',map {&escape($_);} @{$store});
 5099:     } elsif (ref($store) eq 'HASH') {
 5100:         while (my($key,$value) = each(%{$store})) {
 5101:             $items.= &escape($key).'='.&escape($value).'&';
 5102:         }
 5103:     }
 5104:     $items=~s/\&$//;
 5105:     if ($critical) {
 5106: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5107:     } else {
 5108: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5109:     }
 5110: }
 5111: 
 5112: # --------------------------------------------------------------- put interface
 5113: 
 5114: sub put {
 5115:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5117:    if (!$uname) { $uname=$env{'user.name'}; }
 5118:    my $uhome=&homeserver($uname,$udomain);
 5119:    my $items='';
 5120:    foreach my $item (keys(%$storehash)) {
 5121:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5122:    }
 5123:    $items=~s/\&$//;
 5124:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5125: }
 5126: 
 5127: # ------------------------------------------------------------ newput interface
 5128: 
 5129: sub newput {
 5130:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5132:    if (!$uname) { $uname=$env{'user.name'}; }
 5133:    my $uhome=&homeserver($uname,$udomain);
 5134:    my $items='';
 5135:    foreach my $key (keys(%$storehash)) {
 5136:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5137:    }
 5138:    $items=~s/\&$//;
 5139:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5140: }
 5141: 
 5142: # ---------------------------------------------------------  putstore interface
 5143: 
 5144: sub putstore {
 5145:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5146:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5147:    if (!$uname) { $uname=$env{'user.name'}; }
 5148:    my $uhome=&homeserver($uname,$udomain);
 5149:    my $items='';
 5150:    foreach my $key (keys(%$storehash)) {
 5151:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5152:    }
 5153:    $items=~s/\&$//;
 5154:    my $esc_symb=&escape($symb);
 5155:    my $esc_v=&escape($version);
 5156:    my $reply =
 5157:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5158: 	      $uhome);
 5159:    if ($reply eq 'unknown_cmd') {
 5160:        # gfall back to way things use to be done
 5161:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5162: 			    $uname);
 5163:    }
 5164:    return $reply;
 5165: }
 5166: 
 5167: sub old_putstore {
 5168:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5169:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5170:     if (!$uname) { $uname=$env{'user.name'}; }
 5171:     my $uhome=&homeserver($uname,$udomain);
 5172:     my %newstorehash;
 5173:     foreach my $item (keys(%$storehash)) {
 5174: 	my $key = $version.':'.&escape($symb).':'.$item;
 5175: 	$newstorehash{$key} = $storehash->{$item};
 5176:     }
 5177:     my $items='';
 5178:     my %allitems = ();
 5179:     foreach my $item (keys(%newstorehash)) {
 5180: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5181: 	    my $key = $1.':keys:'.$2;
 5182: 	    $allitems{$key} .= $3.':';
 5183: 	}
 5184: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5185:     }
 5186:     foreach my $item (keys(%allitems)) {
 5187: 	$allitems{$item} =~ s/\:$//;
 5188: 	$items.= $item.'='.$allitems{$item}.'&';
 5189:     }
 5190:     $items=~s/\&$//;
 5191:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5192: }
 5193: 
 5194: # ------------------------------------------------------ critical put interface
 5195: 
 5196: sub cput {
 5197:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5198:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5199:    if (!$uname) { $uname=$env{'user.name'}; }
 5200:    my $uhome=&homeserver($uname,$udomain);
 5201:    my $items='';
 5202:    foreach my $item (keys(%$storehash)) {
 5203:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5204:    }
 5205:    $items=~s/\&$//;
 5206:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5207: }
 5208: 
 5209: # -------------------------------------------------------------- eget interface
 5210: 
 5211: sub eget {
 5212:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5213:    my $items='';
 5214:    foreach my $item (@$storearr) {
 5215:        $items.=&escape($item).'&';
 5216:    }
 5217:    $items=~s/\&$//;
 5218:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5219:    if (!$uname) { $uname=$env{'user.name'}; }
 5220:    my $uhome=&homeserver($uname,$udomain);
 5221:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5222:    my @pairs=split(/\&/,$rep);
 5223:    my %returnhash=();
 5224:    my $i=0;
 5225:    foreach my $item (@$storearr) {
 5226:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5227:       $i++;
 5228:    }
 5229:    return %returnhash;
 5230: }
 5231: 
 5232: # ------------------------------------------------------------ tmpput interface
 5233: sub tmpput {
 5234:     my ($storehash,$server,$context)=@_;
 5235:     my $items='';
 5236:     foreach my $item (keys(%$storehash)) {
 5237: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5238:     }
 5239:     $items=~s/\&$//;
 5240:     if (defined($context)) {
 5241:         $items .= ':'.&escape($context);
 5242:     }
 5243:     return &reply("tmpput:$items",$server);
 5244: }
 5245: 
 5246: # ------------------------------------------------------------ tmpget interface
 5247: sub tmpget {
 5248:     my ($token,$server)=@_;
 5249:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5250:     my $rep=&reply("tmpget:$token",$server);
 5251:     my %returnhash;
 5252:     foreach my $item (split(/\&/,$rep)) {
 5253: 	my ($key,$value)=split(/=/,$item);
 5254:         next if ($key =~ /^error: 2 /);
 5255: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5256:     }
 5257:     return %returnhash;
 5258: }
 5259: 
 5260: # ------------------------------------------------------------ tmpdel interface
 5261: sub tmpdel {
 5262:     my ($token,$server)=@_;
 5263:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5264:     return &reply("tmpdel:$token",$server);
 5265: }
 5266: 
 5267: # -------------------------------------------------- portfolio access checking
 5268: 
 5269: sub portfolio_access {
 5270:     my ($requrl) = @_;
 5271:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5272:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5273:     if ($result) {
 5274:         my %setters;
 5275:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5276:             my ($startblock,$endblock) =
 5277:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5278:             if ($startblock && $endblock) {
 5279:                 return 'B';
 5280:             }
 5281:         } else {
 5282:             my ($startblock,$endblock) =
 5283:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5284:             if ($startblock && $endblock) {
 5285:                 return 'B';
 5286:             }
 5287:         }
 5288:     }
 5289:     if ($result eq 'ok') {
 5290:        return 'F';
 5291:     } elsif ($result =~ /^[^:]+:guest_/) {
 5292:        return 'A';
 5293:     }
 5294:     return '';
 5295: }
 5296: 
 5297: sub get_portfolio_access {
 5298:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5299: 
 5300:     if (!ref($access_hash)) {
 5301: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5302: 	my %access_controls = &get_access_controls($current_perms,$group,
 5303: 						   $file_name);
 5304: 	$access_hash = $access_controls{$file_name};
 5305:     }
 5306: 
 5307:     my ($public,$guest,@domains,@users,@courses,@groups);
 5308:     my $now = time;
 5309:     if (ref($access_hash) eq 'HASH') {
 5310:         foreach my $key (keys(%{$access_hash})) {
 5311:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5312:             if ($start > $now) {
 5313:                 next;
 5314:             }
 5315:             if ($end && $end<$now) {
 5316:                 next;
 5317:             }
 5318:             if ($scope eq 'public') {
 5319:                 $public = $key;
 5320:                 last;
 5321:             } elsif ($scope eq 'guest') {
 5322:                 $guest = $key;
 5323:             } elsif ($scope eq 'domains') {
 5324:                 push(@domains,$key);
 5325:             } elsif ($scope eq 'users') {
 5326:                 push(@users,$key);
 5327:             } elsif ($scope eq 'course') {
 5328:                 push(@courses,$key);
 5329:             } elsif ($scope eq 'group') {
 5330:                 push(@groups,$key);
 5331:             }
 5332:         }
 5333:         if ($public) {
 5334:             return 'ok';
 5335:         }
 5336:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5337:             if ($guest) {
 5338:                 return $guest;
 5339:             }
 5340:         } else {
 5341:             if (@domains > 0) {
 5342:                 foreach my $domkey (@domains) {
 5343:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5344:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5345:                             return 'ok';
 5346:                         }
 5347:                     }
 5348:                 }
 5349:             }
 5350:             if (@users > 0) {
 5351:                 foreach my $userkey (@users) {
 5352:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5353:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5354:                             if (ref($item) eq 'HASH') {
 5355:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5356:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5357:                                     return 'ok';
 5358:                                 }
 5359:                             }
 5360:                         }
 5361:                     } 
 5362:                 }
 5363:             }
 5364:             my %roleshash;
 5365:             my @courses_and_groups = @courses;
 5366:             push(@courses_and_groups,@groups); 
 5367:             if (@courses_and_groups > 0) {
 5368:                 my (%allgroups,%allroles); 
 5369:                 my ($start,$end,$role,$sec,$group);
 5370:                 foreach my $envkey (%env) {
 5371:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5372:                         my $cid = $2.'_'.$3; 
 5373:                         if ($1 eq 'gr') {
 5374:                             $group = $4;
 5375:                             $allgroups{$cid}{$group} = $env{$envkey};
 5376:                         } else {
 5377:                             if ($4 eq '') {
 5378:                                 $sec = 'none';
 5379:                             } else {
 5380:                                 $sec = $4;
 5381:                             }
 5382:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5383:                         }
 5384:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5385:                         my $cid = $2.'_'.$3;
 5386:                         if ($4 eq '') {
 5387:                             $sec = 'none';
 5388:                         } else {
 5389:                             $sec = $4;
 5390:                         }
 5391:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5392:                     }
 5393:                 }
 5394:                 if (keys(%allroles) == 0) {
 5395:                     return;
 5396:                 }
 5397:                 foreach my $key (@courses_and_groups) {
 5398:                     my %content = %{$$access_hash{$key}};
 5399:                     my $cnum = $content{'number'};
 5400:                     my $cdom = $content{'domain'};
 5401:                     my $cid = $cdom.'_'.$cnum;
 5402:                     if (!exists($allroles{$cid})) {
 5403:                         next;
 5404:                     }    
 5405:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5406:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5407:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5408:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5409:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5410:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5411:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5412:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5413:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5414:                                         if (grep/^all$/,@sections) {
 5415:                                             return 'ok';
 5416:                                         } else {
 5417:                                             if (grep/^$sec$/,@sections) {
 5418:                                                 return 'ok';
 5419:                                             }
 5420:                                         }
 5421:                                     }
 5422:                                 }
 5423:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5424:                                     if (grep/^none$/,@groups) {
 5425:                                         return 'ok';
 5426:                                     }
 5427:                                 } else {
 5428:                                     if (grep/^all$/,@groups) {
 5429:                                         return 'ok';
 5430:                                     } 
 5431:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5432:                                         if (grep/^$group$/,@groups) {
 5433:                                             return 'ok';
 5434:                                         }
 5435:                                     }
 5436:                                 } 
 5437:                             }
 5438:                         }
 5439:                     }
 5440:                 }
 5441:             }
 5442:             if ($guest) {
 5443:                 return $guest;
 5444:             }
 5445:         }
 5446:     }
 5447:     return;
 5448: }
 5449: 
 5450: sub course_group_datechecker {
 5451:     my ($dates,$now,$status) = @_;
 5452:     my ($start,$end) = split(/\./,$dates);
 5453:     if (!$start && !$end) {
 5454:         return 'ok';
 5455:     }
 5456:     if (grep/^active$/,@{$status}) {
 5457:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5458:             return 'ok';
 5459:         }
 5460:     }
 5461:     if (grep/^previous$/,@{$status}) {
 5462:         if ($end > $now ) {
 5463:             return 'ok';
 5464:         }
 5465:     }
 5466:     if (grep/^future$/,@{$status}) {
 5467:         if ($start > $now) {
 5468:             return 'ok';
 5469:         }
 5470:     }
 5471:     return; 
 5472: }
 5473: 
 5474: sub parse_portfolio_url {
 5475:     my ($url) = @_;
 5476: 
 5477:     my ($type,$udom,$unum,$group,$file_name);
 5478:     
 5479:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5480: 	$type = 1;
 5481:         $udom = $1;
 5482:         $unum = $2;
 5483:         $file_name = $3;
 5484:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5485: 	$type = 2;
 5486:         $udom = $1;
 5487:         $unum = $2;
 5488:         $group = $3;
 5489:         $file_name = $3.'/'.$4;
 5490:     }
 5491:     if (wantarray) {
 5492: 	return ($type,$udom,$unum,$file_name,$group);
 5493:     }
 5494:     return $type;
 5495: }
 5496: 
 5497: sub is_portfolio_url {
 5498:     my ($url) = @_;
 5499:     return scalar(&parse_portfolio_url($url));
 5500: }
 5501: 
 5502: sub is_portfolio_file {
 5503:     my ($file) = @_;
 5504:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5505:         return 1;
 5506:     }
 5507:     return;
 5508: }
 5509: 
 5510: sub usertools_access {
 5511:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5512:     my ($access,%tools);
 5513:     if ($context eq '') {
 5514:         $context = 'tools';
 5515:     }
 5516:     if ($context eq 'requestcourses') {
 5517:         %tools = (
 5518:                       official   => 1,
 5519:                       unofficial => 1,
 5520:                       community  => 1,
 5521:                  );
 5522:     } else {
 5523:         %tools = (
 5524:                       aboutme   => 1,
 5525:                       blog      => 1,
 5526:                       portfolio => 1,
 5527:                  );
 5528:     }
 5529:     return if (!defined($tools{$tool}));
 5530: 
 5531:     if ((!defined($udom)) || (!defined($uname))) {
 5532:         $udom = $env{'user.domain'};
 5533:         $uname = $env{'user.name'};
 5534:     }
 5535: 
 5536:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5537:         if ($action ne 'reload') {
 5538:             if ($context eq 'requestcourses') {
 5539:                 return $env{'environment.canrequest.'.$tool};
 5540:             } else {
 5541:                 return $env{'environment.availabletools.'.$tool};
 5542:             }
 5543:         }
 5544:     }
 5545: 
 5546:     my ($toolstatus,$inststatus);
 5547: 
 5548:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5549:          ($action ne 'reload')) {
 5550:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5551:         $inststatus = $env{'environment.inststatus'};
 5552:     } else {
 5553:         if (ref($userenvref) eq 'HASH') {
 5554:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5555:             $inststatus = $userenvref->{'inststatus'};
 5556:         } else {
 5557:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5558:             $toolstatus = $userenv{$context.'.'.$tool};
 5559:             $inststatus = $userenv{'inststatus'};
 5560:         }
 5561:     }
 5562: 
 5563:     if ($toolstatus ne '') {
 5564:         if ($toolstatus) {
 5565:             $access = 1;
 5566:         } else {
 5567:             $access = 0;
 5568:         }
 5569:         return $access;
 5570:     }
 5571: 
 5572:     my ($is_adv,%domdef);
 5573:     if (ref($is_advref) eq 'HASH') {
 5574:         $is_adv = $is_advref->{'is_adv'};
 5575:     } else {
 5576:         $is_adv = &is_advanced_user($udom,$uname);
 5577:     }
 5578:     if (ref($domdefref) eq 'HASH') {
 5579:         %domdef = %{$domdefref};
 5580:     } else {
 5581:         %domdef = &get_domain_defaults($udom);
 5582:     }
 5583:     if (ref($domdef{$tool}) eq 'HASH') {
 5584:         if ($is_adv) {
 5585:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5586:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5587:                     $access = 1;
 5588:                 } else {
 5589:                     $access = 0;
 5590:                 }
 5591:                 return $access;
 5592:             }
 5593:         }
 5594:         if ($inststatus ne '') {
 5595:             my ($hasaccess,$hasnoaccess);
 5596:             foreach my $affiliation (split(/:/,$inststatus)) {
 5597:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5598:                     if ($domdef{$tool}{$affiliation}) {
 5599:                         $hasaccess = 1;
 5600:                     } else {
 5601:                         $hasnoaccess = 1;
 5602:                     }
 5603:                 }
 5604:             }
 5605:             if ($hasaccess || $hasnoaccess) {
 5606:                 if ($hasaccess) {
 5607:                     $access = 1;
 5608:                 } elsif ($hasnoaccess) {
 5609:                     $access = 0; 
 5610:                 }
 5611:                 return $access;
 5612:             }
 5613:         } else {
 5614:             if ($domdef{$tool}{'default'} ne '') {
 5615:                 if ($domdef{$tool}{'default'}) {
 5616:                     $access = 1;
 5617:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5618:                     $access = 0;
 5619:                 }
 5620:                 return $access;
 5621:             }
 5622:         }
 5623:     } else {
 5624:         if ($context eq 'tools') {
 5625:             $access = 1;
 5626:         } else {
 5627:             $access = 0;
 5628:         }
 5629:         return $access;
 5630:     }
 5631: }
 5632: 
 5633: sub is_course_owner {
 5634:     my ($cdom,$cnum,$udom,$uname) = @_;
 5635:     if (($udom eq '') || ($uname eq '')) {
 5636:         $udom = $env{'user.domain'};
 5637:         $uname = $env{'user.name'};
 5638:     }
 5639:     unless (($udom eq '') || ($uname eq '')) {
 5640:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5641:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5642:                 return 1;
 5643:             } else {
 5644:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5645:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5646:                     return 1;
 5647:                 }
 5648:             }
 5649:         }
 5650:     }
 5651:     return;
 5652: }
 5653: 
 5654: sub is_advanced_user {
 5655:     my ($udom,$uname) = @_;
 5656:     if ($udom ne '' && $uname ne '') {
 5657:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5658:             if (wantarray) {
 5659:                 return ($env{'user.adv'},$env{'user.author'});
 5660:             } else {
 5661:                 return $env{'user.adv'};
 5662:             }
 5663:         }
 5664:     }
 5665:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5666:     my %allroles;
 5667:     my ($is_adv,$is_author);
 5668:     foreach my $role (keys(%roleshash)) {
 5669:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5670:         my $area = '/'.$tdomain.'/'.$trest;
 5671:         if ($sec ne '') {
 5672:             $area .= '/'.$sec;
 5673:         }
 5674:         if (($area ne '') && ($trole ne '')) {
 5675:             my $spec=$trole.'.'.$area;
 5676:             if ($trole =~ /^cr\//) {
 5677:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5678:             } elsif ($trole ne 'gr') {
 5679:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5680:             }
 5681:             if ($trole eq 'au') {
 5682:                 $is_author = 1;
 5683:             }
 5684:         }
 5685:     }
 5686:     foreach my $role (keys(%allroles)) {
 5687:         last if ($is_adv);
 5688:         foreach my $item (split(/:/,$allroles{$role})) {
 5689:             if ($item ne '') {
 5690:                 my ($privilege,$restrictions)=split(/&/,$item);
 5691:                 if ($privilege eq 'adv') {
 5692:                     $is_adv = 1;
 5693:                     last;
 5694:                 }
 5695:             }
 5696:         }
 5697:     }
 5698:     if (wantarray) {
 5699:         return ($is_adv,$is_author);
 5700:     }
 5701:     return $is_adv;
 5702: }
 5703: 
 5704: sub check_can_request {
 5705:     my ($dom,$can_request,$request_domains) = @_;
 5706:     my $canreq = 0;
 5707:     my ($types,$typename) = &Apache::loncommon::course_types();
 5708:     my @options = ('approval','validate','autolimit');
 5709:     my $optregex = join('|',@options);
 5710:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5711:         foreach my $type (@{$types}) {
 5712:             if (&usertools_access($env{'user.name'},
 5713:                                   $env{'user.domain'},
 5714:                                   $type,undef,'requestcourses')) {
 5715:                 $canreq ++;
 5716:                 if (ref($request_domains) eq 'HASH') {
 5717:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5718:                 }
 5719:                 if ($dom eq $env{'user.domain'}) {
 5720:                     $can_request->{$type} = 1;
 5721:                 }
 5722:             }
 5723:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5724:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5725:                 if (@curr > 0) {
 5726:                     foreach my $item (@curr) {
 5727:                         if (ref($request_domains) eq 'HASH') {
 5728:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5729:                             if ($otherdom ne '') {
 5730:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5731:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5732:                                         push(@{$request_domains->{$type}},$otherdom);
 5733:                                     }
 5734:                                 } else {
 5735:                                     push(@{$request_domains->{$type}},$otherdom);
 5736:                                 }
 5737:                             }
 5738:                         }
 5739:                     }
 5740:                     unless($dom eq $env{'user.domain'}) {
 5741:                         $canreq ++;
 5742:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5743:                             $can_request->{$type} = 1;
 5744:                         }
 5745:                     }
 5746:                 }
 5747:             }
 5748:         }
 5749:     }
 5750:     return $canreq;
 5751: }
 5752: 
 5753: # ---------------------------------------------- Custom access rule evaluation
 5754: 
 5755: sub customaccess {
 5756:     my ($priv,$uri)=@_;
 5757:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5758:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5759:     $udom = &LONCAPA::clean_domain($udom);
 5760:     $ucrs = &LONCAPA::clean_username($ucrs);
 5761:     my $access=0;
 5762:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5763: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5764: 	if ($type eq 'user') {
 5765: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5766: 		my ($tdom,$tuname)=split(m{/},$scope);
 5767: 		if ($tdom) {
 5768: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5769: 		}
 5770: 		if ($tuname) {
 5771: 		    if ($tuname ne $env{'user.name'}) { next; }
 5772: 		}
 5773: 		$access=($effect eq 'allow');
 5774: 		last;
 5775: 	    }
 5776: 	} else {
 5777: 	    if ($role) {
 5778: 		if ($role ne $urole) { next; }
 5779: 	    }
 5780: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5781: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5782: 		if ($tdom) {
 5783: 		    if ($tdom ne $udom) { next; }
 5784: 		}
 5785: 		if ($tcrs) {
 5786: 		    if ($tcrs ne $ucrs) { next; }
 5787: 		}
 5788: 		if ($tsec) {
 5789: 		    if ($tsec ne $usec) { next; }
 5790: 		}
 5791: 		$access=($effect eq 'allow');
 5792: 		last;
 5793: 	    }
 5794: 	    if ($realm eq '' && $role eq '') {
 5795: 		$access=($effect eq 'allow');
 5796: 	    }
 5797: 	}
 5798:     }
 5799:     return $access;
 5800: }
 5801: 
 5802: # ------------------------------------------------- Check for a user privilege
 5803: 
 5804: sub allowed {
 5805:     my ($priv,$uri,$symb,$role)=@_;
 5806:     my $ver_orguri=$uri;
 5807:     $uri=&deversion($uri);
 5808:     my $orguri=$uri;
 5809:     $uri=&declutter($uri);
 5810: 
 5811:     if ($priv eq 'evb') {
 5812: # Evade communication block restrictions for specified role in a course
 5813:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5814:             return $1;
 5815:         } else {
 5816:             return;
 5817:         }
 5818:     }
 5819: 
 5820:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5821: # Free bre access to adm and meta resources
 5822:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5823: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5824: 	&& ($priv eq 'bre')) {
 5825: 	return 'F';
 5826:     }
 5827: 
 5828: # Free bre access to user's own portfolio contents
 5829:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5830:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5831: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5832:         my %setters;
 5833:         my ($startblock,$endblock) = 
 5834:             &Apache::loncommon::blockcheck(\%setters,'port');
 5835:         if ($startblock && $endblock) {
 5836:             return 'B';
 5837:         } else {
 5838:             return 'F';
 5839:         }
 5840:     }
 5841: 
 5842: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5843:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5844:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5845:         if (exists($env{'request.course.id'})) {
 5846:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5847:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5848:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5849:                 my $courseprivid=$env{'request.course.id'};
 5850:                 $courseprivid=~s/\_/\//;
 5851:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5852:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5853:                     return $1; 
 5854:                 } else {
 5855:                     if ($env{'request.course.sec'}) {
 5856:                         $courseprivid.='/'.$env{'request.course.sec'};
 5857:                     }
 5858:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5859:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5860:                         return $2;
 5861:                     }
 5862:                 }
 5863:             }
 5864:         }
 5865:     }
 5866: 
 5867: # Free bre to public access
 5868: 
 5869:     if ($priv eq 'bre') {
 5870:         my $copyright=&metadata($uri,'copyright');
 5871: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5872:            return 'F'; 
 5873:         }
 5874:         if ($copyright eq 'priv') {
 5875:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5876: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5877: 		return '';
 5878:             }
 5879:         }
 5880:         if ($copyright eq 'domain') {
 5881:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5882: 	    unless (($env{'user.domain'} eq $1) ||
 5883:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5884: 		return '';
 5885:             }
 5886:         }
 5887:         if ($env{'request.role'}=~ /li\.\//) {
 5888:             # Library role, so allow browsing of resources in this domain.
 5889:             return 'F';
 5890:         }
 5891:         if ($copyright eq 'custom') {
 5892: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5893:         }
 5894:     }
 5895:     # Domain coordinator is trying to create a course
 5896:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5897:         # uri is the requested domain in this case.
 5898:         # comparison to 'request.role.domain' shows if the user has selected
 5899:         # a role of dc for the domain in question.
 5900:         return 'F' if ($uri eq $env{'request.role.domain'});
 5901:     }
 5902: 
 5903:     my $thisallowed='';
 5904:     my $statecond=0;
 5905:     my $courseprivid='';
 5906: 
 5907:     my $ownaccess;
 5908:     # Community Coordinator or Assistant Co-author browsing resource space.
 5909:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5910:         if ($uri eq '') {
 5911:             $ownaccess = 1;
 5912:         } else {
 5913:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5914:                 my $udom = $env{'user.domain'};
 5915:                 my $uname = $env{'user.name'};
 5916:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5917:                     $ownaccess = 1;
 5918:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5919:                     unless ($uri =~ m{\.\./}) {
 5920:                         $ownaccess = 1;
 5921:                     }
 5922:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5923:                     my $now = time;
 5924:                     if ($uri =~ m{^([^/]+)/?$}) {
 5925:                         my $adom = $1;
 5926:                         foreach my $key (keys(%env)) {
 5927:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5928:                                 my ($start,$end) = split('.',$env{$key});
 5929:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5930:                                     $ownaccess = 1;
 5931:                                     last;
 5932:                                 }
 5933:                             }
 5934:                         }
 5935:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5936:                         my $adom = $1;
 5937:                         my $aname = $2;
 5938:                         foreach my $role ('ca','aa') { 
 5939:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5940:                                 my ($start,$end) =
 5941:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5942:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5943:                                     $ownaccess = 1;
 5944:                                     last;
 5945:                                 }
 5946:                             }
 5947:                         }
 5948:                     }
 5949:                 }
 5950:             }
 5951:         }
 5952:     }
 5953: 
 5954: # Course
 5955: 
 5956:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5957:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5958:             $thisallowed.=$1;
 5959:         }
 5960:     }
 5961: 
 5962: # Domain
 5963: 
 5964:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5965:        =~/\Q$priv\E\&([^\:]*)/) {
 5966:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5967:             $thisallowed.=$1;
 5968:         }
 5969:     }
 5970: 
 5971: # User who is not author or co-author might still be able to edit
 5972: # resource of an author in the domain (e.g., if Domain Coordinator).
 5973:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 5974:         (&allowed('mdc',$env{'request.course.id'}))) {
 5975:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 5976:             $thisallowed.=$1;
 5977:         }
 5978:     }
 5979: 
 5980: # Course: uri itself is a course
 5981:     my $courseuri=$uri;
 5982:     $courseuri=~s/\_(\d)/\/$1/;
 5983:     $courseuri=~s/^([^\/])/\/$1/;
 5984: 
 5985:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5986:        =~/\Q$priv\E\&([^\:]*)/) {
 5987:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5988:             $thisallowed.=$1;
 5989:         }
 5990:     }
 5991: 
 5992: # URI is an uploaded document for this course, default permissions don't matter
 5993: # not allowing 'edit' access (editupload) to uploaded course docs
 5994:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5995: 	$thisallowed='';
 5996:         my ($match)=&is_on_map($uri);
 5997:         if ($match) {
 5998:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5999:                   =~/\Q$priv\E\&([^\:]*)/) {
 6000:                 $thisallowed.=$1;
 6001:             }
 6002:         } else {
 6003:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6004:             if ($refuri) {
 6005:                 if ($refuri =~ m|^/adm/|) {
 6006:                     $thisallowed='F';
 6007:                 } else {
 6008:                     $refuri=&declutter($refuri);
 6009:                     my ($match) = &is_on_map($refuri);
 6010:                     if ($match) {
 6011:                         $thisallowed='F';
 6012:                     }
 6013:                 }
 6014:             }
 6015:         }
 6016:     }
 6017: 
 6018:     if ($priv eq 'bre'
 6019: 	&& $thisallowed ne 'F' 
 6020: 	&& $thisallowed ne '2'
 6021: 	&& &is_portfolio_url($uri)) {
 6022: 	$thisallowed = &portfolio_access($uri);
 6023:     }
 6024:     
 6025: # Full access at system, domain or course-wide level? Exit.
 6026:     if ($thisallowed=~/F/) {
 6027: 	return 'F';
 6028:     }
 6029: 
 6030: # If this is generating or modifying users, exit with special codes
 6031: 
 6032:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6033: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6034: 	    my ($audom,$auname)=split('/',$uri);
 6035: # no author name given, so this just checks on the general right to make a co-author in this domain
 6036: 	    unless ($auname) { return $thisallowed; }
 6037: # an author name is given, so we are about to actually make a co-author for a certain account
 6038: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6039: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6040: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6041: 	}
 6042: 	return $thisallowed;
 6043:     }
 6044: #
 6045: # Gathered so far: system, domain and course wide privileges
 6046: #
 6047: # Course: See if uri or referer is an individual resource that is part of 
 6048: # the course
 6049: 
 6050:     if ($env{'request.course.id'}) {
 6051: 
 6052:        $courseprivid=$env{'request.course.id'};
 6053:        if ($env{'request.course.sec'}) {
 6054:           $courseprivid.='/'.$env{'request.course.sec'};
 6055:        }
 6056:        $courseprivid=~s/\_/\//;
 6057:        my $checkreferer=1;
 6058:        my ($match,$cond)=&is_on_map($uri);
 6059:        if ($match) {
 6060:            $statecond=$cond;
 6061:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6062:                =~/\Q$priv\E\&([^\:]*)/) {
 6063:                $thisallowed.=$1;
 6064:                $checkreferer=0;
 6065:            }
 6066:        }
 6067:        
 6068:        if ($checkreferer) {
 6069: 	  my $refuri=$env{'httpref.'.$orguri};
 6070:             unless ($refuri) {
 6071:                 foreach my $key (keys(%env)) {
 6072: 		    if ($key=~/^httpref\..*\*/) {
 6073: 			my $pattern=$key;
 6074:                         $pattern=~s/^httpref\.\/res\///;
 6075:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6076:                         $pattern=~s/\//\\\//g;
 6077:                         if ($orguri=~/$pattern/) {
 6078: 			    $refuri=$env{$key};
 6079:                         }
 6080:                     }
 6081:                 }
 6082:             }
 6083: 
 6084:          if ($refuri) { 
 6085: 	  $refuri=&declutter($refuri);
 6086:           my ($match,$cond)=&is_on_map($refuri);
 6087:             if ($match) {
 6088:               my $refstatecond=$cond;
 6089:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6090:                   =~/\Q$priv\E\&([^\:]*)/) {
 6091:                   $thisallowed.=$1;
 6092:                   $uri=$refuri;
 6093:                   $statecond=$refstatecond;
 6094:               }
 6095:           }
 6096:         }
 6097:        }
 6098:    }
 6099: 
 6100: #
 6101: # Gathered now: all privileges that could apply, and condition number
 6102: # 
 6103: #
 6104: # Full or no access?
 6105: #
 6106: 
 6107:     if ($thisallowed=~/F/) {
 6108: 	return 'F';
 6109:     }
 6110: 
 6111:     unless ($thisallowed) {
 6112:         return '';
 6113:     }
 6114: 
 6115: # Restrictions exist, deal with them
 6116: #
 6117: #   C:according to course preferences
 6118: #   R:according to resource settings
 6119: #   L:unless locked
 6120: #   X:according to user session state
 6121: #
 6122: 
 6123: # Possibly locked functionality, check all courses
 6124: # Locks might take effect only after 10 minutes cache expiration for other
 6125: # courses, and 2 minutes for current course
 6126: 
 6127:     my $envkey;
 6128:     if ($thisallowed=~/L/) {
 6129:         foreach $envkey (keys(%env)) {
 6130:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6131:                my $courseid=$2;
 6132:                my $roleid=$1.'.'.$2;
 6133:                $courseid=~s/^\///;
 6134:                my $expiretime=600;
 6135:                if ($env{'request.role'} eq $roleid) {
 6136: 		  $expiretime=120;
 6137:                }
 6138: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6139:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6140:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6141: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6142:                }
 6143:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6144:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6145: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6146:                        &log($env{'user.domain'},$env{'user.name'},
 6147:                             $env{'user.home'},
 6148:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6149:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6150:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6151: 		       return '';
 6152:                    }
 6153:                }
 6154:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6155:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6156: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6157:                        &log($env{'user.domain'},$env{'user.name'},
 6158:                             $env{'user.home'},
 6159:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6160:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6161:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6162: 		       return '';
 6163:                    }
 6164:                }
 6165: 	   }
 6166:        }
 6167:     }
 6168:    
 6169: #
 6170: # Rest of the restrictions depend on selected course
 6171: #
 6172: 
 6173:     unless ($env{'request.course.id'}) {
 6174: 	if ($thisallowed eq 'A') {
 6175: 	    return 'A';
 6176:         } elsif ($thisallowed eq 'B') {
 6177:             return 'B';
 6178: 	} else {
 6179: 	    return '1';
 6180: 	}
 6181:     }
 6182: 
 6183: #
 6184: # Now user is definitely in a course
 6185: #
 6186: 
 6187: 
 6188: # Course preferences
 6189: 
 6190:    if ($thisallowed=~/C/) {
 6191:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6192:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6193:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6194: 	   =~/\Q$rolecode\E/) {
 6195: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6196: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6197: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6198: 			$env{'request.course.id'});
 6199: 	   }
 6200:            return '';
 6201:        }
 6202: 
 6203:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6204: 	   =~/\Q$unamedom\E/) {
 6205: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6206: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6207: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6208: 			$env{'request.course.id'});
 6209: 	   }
 6210:            return '';
 6211:        }
 6212:    }
 6213: 
 6214: # Resource preferences
 6215: 
 6216:    if ($thisallowed=~/R/) {
 6217:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6218:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6219: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6220: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6221: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6222: 	   }
 6223: 	   return '';
 6224:        }
 6225:    }
 6226: 
 6227: # Restricted by state or randomout?
 6228: 
 6229:    if ($thisallowed=~/X/) {
 6230:       if ($env{'acc.randomout'}) {
 6231: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6232:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6233:             return ''; 
 6234:          }
 6235:       }
 6236:       if (&condval($statecond)) {
 6237: 	 return '2';
 6238:       } else {
 6239:          return '';
 6240:       }
 6241:    }
 6242: 
 6243:     if ($thisallowed eq 'A') {
 6244: 	return 'A';
 6245:     } elsif ($thisallowed eq 'B') {
 6246:         return 'B';
 6247:     }
 6248:    return 'F';
 6249: }
 6250: #
 6251: #   Removes the versino from a URI and
 6252: #   splits it in to its filename and path to the filename.
 6253: #   Seems like File::Basename could have done this more clearly.
 6254: #   Parameters:
 6255: #      $uri   - input URI
 6256: #   Returns:
 6257: #     Two element list consisting of 
 6258: #     $pathname  - the URI up to and excluding the trailing /
 6259: #     $filename  - The part of the URI following the last /
 6260: #  NOTE:
 6261: #    Another realization of this is simply:
 6262: #    use File::Basename;
 6263: #    ...
 6264: #    $uri = shift;
 6265: #    $filename = basename($uri);
 6266: #    $path     = dirname($uri);
 6267: #    return ($filename, $path);
 6268: #
 6269: #     The implementation below is probably faster however.
 6270: #
 6271: sub split_uri_for_cond {
 6272:     my $uri=&deversion(&declutter(shift));
 6273:     my @uriparts=split(/\//,$uri);
 6274:     my $filename=pop(@uriparts);
 6275:     my $pathname=join('/',@uriparts);
 6276:     return ($pathname,$filename);
 6277: }
 6278: # --------------------------------------------------- Is a resource on the map?
 6279: 
 6280: sub is_on_map {
 6281:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6282:     #Trying to find the conditional for the file
 6283:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6284: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6285:     if ($match) {
 6286: 	return (1,$1);
 6287:     } else {
 6288: 	return (0,0);
 6289:     }
 6290: }
 6291: 
 6292: # --------------------------------------------------------- Get symb from alias
 6293: 
 6294: sub get_symb_from_alias {
 6295:     my $symb=shift;
 6296:     my ($map,$resid,$url)=&decode_symb($symb);
 6297: # Already is a symb
 6298:     if ($url) { return $symb; }
 6299: # Must be an alias
 6300:     my $aliassymb='';
 6301:     my %bighash;
 6302:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6303:                             &GDBM_READER(),0640)) {
 6304:         my $rid=$bighash{'mapalias_'.$symb};
 6305: 	if ($rid) {
 6306: 	    my ($mapid,$resid)=split(/\./,$rid);
 6307: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6308: 				    $resid,$bighash{'src_'.$rid});
 6309: 	}
 6310:         untie %bighash;
 6311:     }
 6312:     return $aliassymb;
 6313: }
 6314: 
 6315: # ----------------------------------------------------------------- Define Role
 6316: 
 6317: sub definerole {
 6318:   if (allowed('mcr','/')) {
 6319:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6320:     foreach my $role (split(':',$sysrole)) {
 6321: 	my ($crole,$cqual)=split(/\&/,$role);
 6322:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6323:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6324: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6325:                return "refused:s:$crole&$cqual"; 
 6326:             }
 6327:         }
 6328:     }
 6329:     foreach my $role (split(':',$domrole)) {
 6330: 	my ($crole,$cqual)=split(/\&/,$role);
 6331:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6332:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6333: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6334:                return "refused:d:$crole&$cqual"; 
 6335:             }
 6336:         }
 6337:     }
 6338:     foreach my $role (split(':',$courole)) {
 6339: 	my ($crole,$cqual)=split(/\&/,$role);
 6340:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6341:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6342: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6343:                return "refused:c:$crole&$cqual"; 
 6344:             }
 6345:         }
 6346:     }
 6347:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6348:                 "$env{'user.domain'}:$env{'user.name'}:".
 6349: 	        "rolesdef_$rolename=".
 6350:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6351:     return reply($command,$env{'user.home'});
 6352:   } else {
 6353:     return 'refused';
 6354:   }
 6355: }
 6356: 
 6357: # ---------------- Make a metadata query against the network of library servers
 6358: 
 6359: sub metadata_query {
 6360:     my ($query,$custom,$customshow,$server_array)=@_;
 6361:     my %rhash;
 6362:     my %libserv = &all_library();
 6363:     my @server_list = (defined($server_array) ? @$server_array
 6364:                                               : keys(%libserv) );
 6365:     for my $server (@server_list) {
 6366: 	unless ($custom or $customshow) {
 6367: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6368: 	    $rhash{$server}=$reply;
 6369: 	}
 6370: 	else {
 6371: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6372: 			     &escape($custom).':'.&escape($customshow),
 6373: 			     $server);
 6374: 	    $rhash{$server}=$reply;
 6375: 	}
 6376:     }
 6377:     return \%rhash;
 6378: }
 6379: 
 6380: # ----------------------------------------- Send log queries and wait for reply
 6381: 
 6382: sub log_query {
 6383:     my ($uname,$udom,$query,%filters)=@_;
 6384:     my $uhome=&homeserver($uname,$udom);
 6385:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6386:     my $uhost=&hostname($uhome);
 6387:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6388:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6389:                        $uhome);
 6390:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6391:     return get_query_reply($queryid);
 6392: }
 6393: 
 6394: # -------------------------- Update MySQL table for portfolio file
 6395: 
 6396: sub update_portfolio_table {
 6397:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6398:     if ($group ne '') {
 6399:         $file_name =~s /^\Q$group\E//;
 6400:     }
 6401:     my $homeserver = &homeserver($uname,$udom);
 6402:     my $queryid=
 6403:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6404:                ':'.&escape($file_name).':'.$action,$homeserver);
 6405:     my $reply = &get_query_reply($queryid);
 6406:     return $reply;
 6407: }
 6408: 
 6409: # -------------------------- Update MySQL allusers table
 6410: 
 6411: sub update_allusers_table {
 6412:     my ($uname,$udom,$names) = @_;
 6413:     my $homeserver = &homeserver($uname,$udom);
 6414:     my $queryid=
 6415:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6416:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6417:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6418:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6419:                'generation='.&escape($names->{'generation'}).'%%'.
 6420:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6421:                'id='.&escape($names->{'id'}),$homeserver);
 6422:     return;
 6423: }
 6424: 
 6425: # ------- Request retrieval of institutional classlists for course(s)
 6426: 
 6427: sub fetch_enrollment_query {
 6428:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6429:     my $homeserver;
 6430:     my $maxtries = 1;
 6431:     if ($context eq 'automated') {
 6432:         $homeserver = $perlvar{'lonHostID'};
 6433:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6434:     } else {
 6435:         $homeserver = &homeserver($cnum,$dom);
 6436:     }
 6437:     my $host=&hostname($homeserver);
 6438:     my $cmd = '';
 6439:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6440:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6441:     }
 6442:     $cmd =~ s/%%$//;
 6443:     $cmd = &escape($cmd);
 6444:     my $query = 'fetchenrollment';
 6445:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6446:     unless ($queryid=~/^\Q$host\E\_/) { 
 6447:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6448:         return 'error: '.$queryid;
 6449:     }
 6450:     my $reply = &get_query_reply($queryid);
 6451:     my $tries = 1;
 6452:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6453:         $reply = &get_query_reply($queryid);
 6454:         $tries ++;
 6455:     }
 6456:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6457:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6458:     } else {
 6459:         my @responses = split(/:/,$reply);
 6460:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6461:             foreach my $line (@responses) {
 6462:                 my ($key,$value) = split(/=/,$line,2);
 6463:                 $$replyref{$key} = $value;
 6464:             }
 6465:         } else {
 6466:             my $pathname = LONCAPA::tempdir();
 6467:             foreach my $line (@responses) {
 6468:                 my ($key,$value) = split(/=/,$line);
 6469:                 $$replyref{$key} = $value;
 6470:                 if ($value > 0) {
 6471:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6472:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6473:                         my $destname = $pathname.'/'.$filename;
 6474:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6475:                         if ($xml_classlist =~ /^error/) {
 6476:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6477:                         } else {
 6478:                             if ( open(FILE,">$destname") ) {
 6479:                                 print FILE &unescape($xml_classlist);
 6480:                                 close(FILE);
 6481:                             } else {
 6482:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6483:                             }
 6484:                         }
 6485:                     }
 6486:                 }
 6487:             }
 6488:         }
 6489:         return 'ok';
 6490:     }
 6491:     return 'error';
 6492: }
 6493: 
 6494: sub get_query_reply {
 6495:     my $queryid=shift;
 6496:     my $replyfile=LONCAPA::tempdir().$queryid;
 6497:     my $reply='';
 6498:     for (1..100) {
 6499: 	sleep 2;
 6500:         if (-e $replyfile.'.end') {
 6501: 	    if (open(my $fh,$replyfile)) {
 6502: 		$reply = join('',<$fh>);
 6503: 		close($fh);
 6504: 	   } else { return 'error: reply_file_error'; }
 6505:            return &unescape($reply);
 6506: 	}
 6507:     }
 6508:     return 'timeout:'.$queryid;
 6509: }
 6510: 
 6511: sub courselog_query {
 6512: #
 6513: # possible filters:
 6514: # url: url or symb
 6515: # username
 6516: # domain
 6517: # action: view, submit, grade
 6518: # start: timestamp
 6519: # end: timestamp
 6520: #
 6521:     my (%filters)=@_;
 6522:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6523:     if ($filters{'url'}) {
 6524: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6525:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6526:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6527:     }
 6528:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6529:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6530:     return &log_query($cname,$cdom,'courselog',%filters);
 6531: }
 6532: 
 6533: sub userlog_query {
 6534: #
 6535: # possible filters:
 6536: # action: log check role
 6537: # start: timestamp
 6538: # end: timestamp
 6539: #
 6540:     my ($uname,$udom,%filters)=@_;
 6541:     return &log_query($uname,$udom,'userlog',%filters);
 6542: }
 6543: 
 6544: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6545: 
 6546: sub auto_run {
 6547:     my ($cnum,$cdom) = @_;
 6548:     my $response = 0;
 6549:     my $settings;
 6550:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6551:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6552:         $settings = $domconfig{'autoenroll'};
 6553:         if ($settings->{'run'} eq '1') {
 6554:             $response = 1;
 6555:         }
 6556:     } else {
 6557:         my $homeserver;
 6558:         if (&is_course($cdom,$cnum)) {
 6559:             $homeserver = &homeserver($cnum,$cdom);
 6560:         } else {
 6561:             $homeserver = &domain($cdom,'primary');
 6562:         }
 6563:         if ($homeserver ne 'no_host') {
 6564:             $response = &reply('autorun:'.$cdom,$homeserver);
 6565:         }
 6566:     }
 6567:     return $response;
 6568: }
 6569: 
 6570: sub auto_get_sections {
 6571:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6572:     my $homeserver;
 6573:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6574:         $homeserver = &homeserver($cnum,$cdom);
 6575:     }
 6576:     if (!defined($homeserver)) { 
 6577:         if ($cdom =~ /^$match_domain$/) {
 6578:             $homeserver = &domain($cdom,'primary');
 6579:         }
 6580:     }
 6581:     my @secs;
 6582:     if (defined($homeserver)) {
 6583:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6584:         unless ($response eq 'refused') {
 6585:             @secs = split(/:/,$response);
 6586:         }
 6587:     }
 6588:     return @secs;
 6589: }
 6590: 
 6591: sub auto_new_course {
 6592:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6593:     my $homeserver = &homeserver($cnum,$cdom);
 6594:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6595:     return $response;
 6596: }
 6597: 
 6598: sub auto_validate_courseID {
 6599:     my ($cnum,$cdom,$inst_course_id) = @_;
 6600:     my $homeserver = &homeserver($cnum,$cdom);
 6601:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6602:     return $response;
 6603: }
 6604: 
 6605: sub auto_validate_instcode {
 6606:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6607:     my ($homeserver,$response);
 6608:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6609:         $homeserver = &homeserver($cnum,$cdom);
 6610:     }
 6611:     if (!defined($homeserver)) {
 6612:         if ($cdom =~ /^$match_domain$/) {
 6613:             $homeserver = &domain($cdom,'primary');
 6614:         }
 6615:     }
 6616:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6617:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6618:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6619:     return ($outcome,$description);
 6620: }
 6621: 
 6622: sub auto_create_password {
 6623:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6624:     my ($homeserver,$response);
 6625:     my $create_passwd = 0;
 6626:     my $authchk = '';
 6627:     if ($udom =~ /^$match_domain$/) {
 6628:         $homeserver = &domain($udom,'primary');
 6629:     }
 6630:     if ($homeserver eq '') {
 6631:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6632:             $homeserver = &homeserver($cnum,$cdom);
 6633:         }
 6634:     }
 6635:     if ($homeserver eq '') {
 6636:         $authchk = 'nodomain';
 6637:     } else {
 6638:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6639:         if ($response eq 'refused') {
 6640:             $authchk = 'refused';
 6641:         } else {
 6642:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6643:         }
 6644:     }
 6645:     return ($authparam,$create_passwd,$authchk);
 6646: }
 6647: 
 6648: sub auto_photo_permission {
 6649:     my ($cnum,$cdom,$students) = @_;
 6650:     my $homeserver = &homeserver($cnum,$cdom);
 6651:     my ($outcome,$perm_reqd,$conditions) = 
 6652: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6653:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6654: 	return (undef,undef);
 6655:     }
 6656:     return ($outcome,$perm_reqd,$conditions);
 6657: }
 6658: 
 6659: sub auto_checkphotos {
 6660:     my ($uname,$udom,$pid) = @_;
 6661:     my $homeserver = &homeserver($uname,$udom);
 6662:     my ($result,$resulttype);
 6663:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6664: 				   &escape($uname).':'.&escape($pid),
 6665: 				   $homeserver));
 6666:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6667: 	return (undef,undef);
 6668:     }
 6669:     if ($outcome) {
 6670:         ($result,$resulttype) = split(/:/,$outcome);
 6671:     } 
 6672:     return ($result,$resulttype);
 6673: }
 6674: 
 6675: sub auto_photochoice {
 6676:     my ($cnum,$cdom) = @_;
 6677:     my $homeserver = &homeserver($cnum,$cdom);
 6678:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6679: 						       &escape($cdom),
 6680: 						       $homeserver)));
 6681:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6682: 	return (undef,undef);
 6683:     }
 6684:     return ($update,$comment);
 6685: }
 6686: 
 6687: sub auto_photoupdate {
 6688:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6689:     my $homeserver = &homeserver($cnum,$dom);
 6690:     my $host=&hostname($homeserver);
 6691:     my $cmd = '';
 6692:     my $maxtries = 1;
 6693:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6694:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6695:     }
 6696:     $cmd =~ s/%%$//;
 6697:     $cmd = &escape($cmd);
 6698:     my $query = 'institutionalphotos';
 6699:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6700:     unless ($queryid=~/^\Q$host\E\_/) {
 6701:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6702:         return 'error: '.$queryid;
 6703:     }
 6704:     my $reply = &get_query_reply($queryid);
 6705:     my $tries = 1;
 6706:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6707:         $reply = &get_query_reply($queryid);
 6708:         $tries ++;
 6709:     }
 6710:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6711:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6712:     } else {
 6713:         my @responses = split(/:/,$reply);
 6714:         my $outcome = shift(@responses); 
 6715:         foreach my $item (@responses) {
 6716:             my ($key,$value) = split(/=/,$item);
 6717:             $$photo{$key} = $value;
 6718:         }
 6719:         return $outcome;
 6720:     }
 6721:     return 'error';
 6722: }
 6723: 
 6724: sub auto_instcode_format {
 6725:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6726: 	$cat_order) = @_;
 6727:     my $courses = '';
 6728:     my @homeservers;
 6729:     if ($caller eq 'global') {
 6730: 	my %servers = &get_servers($codedom,'library');
 6731: 	foreach my $tryserver (keys(%servers)) {
 6732: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6733: 		push(@homeservers,$tryserver);
 6734: 	    }
 6735:         }
 6736:     } elsif ($caller eq 'requests') {
 6737:         if ($codedom =~ /^$match_domain$/) {
 6738:             my $chome = &domain($codedom,'primary');
 6739:             unless ($chome eq 'no_host') {
 6740:                 push(@homeservers,$chome);
 6741:             }
 6742:         }
 6743:     } else {
 6744:         push(@homeservers,&homeserver($caller,$codedom));
 6745:     }
 6746:     foreach my $code (keys(%{$instcodes})) {
 6747:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6748:     }
 6749:     chop($courses);
 6750:     my $ok_response = 0;
 6751:     my $response;
 6752:     while (@homeservers > 0 && $ok_response == 0) {
 6753:         my $server = shift(@homeservers); 
 6754:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6755:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6756:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6757: 		split(/:/,$response);
 6758:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6759:             push(@{$codetitles},&str2array($codetitles_str));
 6760:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6761:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6762:             $ok_response = 1;
 6763:         }
 6764:     }
 6765:     if ($ok_response) {
 6766:         return 'ok';
 6767:     } else {
 6768:         return $response;
 6769:     }
 6770: }
 6771: 
 6772: sub auto_instcode_defaults {
 6773:     my ($domain,$returnhash,$code_order) = @_;
 6774:     my @homeservers;
 6775: 
 6776:     my %servers = &get_servers($domain,'library');
 6777:     foreach my $tryserver (keys(%servers)) {
 6778: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6779: 	    push(@homeservers,$tryserver);
 6780: 	}
 6781:     }
 6782: 
 6783:     my $response;
 6784:     foreach my $server (@homeservers) {
 6785:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6786:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6787: 	
 6788: 	foreach my $pair (split(/\&/,$response)) {
 6789: 	    my ($name,$value)=split(/\=/,$pair);
 6790: 	    if ($name eq 'code_order') {
 6791: 		@{$code_order} = split(/\&/,&unescape($value));
 6792: 	    } else {
 6793: 		$returnhash->{&unescape($name)}=&unescape($value);
 6794: 	    }
 6795: 	}
 6796: 	return 'ok';
 6797:     }
 6798: 
 6799:     return $response;
 6800: }
 6801: 
 6802: sub auto_possible_instcodes {
 6803:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6804:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6805:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6806:         return;
 6807:     }
 6808:     my (@homeservers,$uhome);
 6809:     if (defined(&domain($domain,'primary'))) {
 6810:         $uhome=&domain($domain,'primary');
 6811:         push(@homeservers,&domain($domain,'primary'));
 6812:     } else {
 6813:         my %servers = &get_servers($domain,'library');
 6814:         foreach my $tryserver (keys(%servers)) {
 6815:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6816:                 push(@homeservers,$tryserver);
 6817:             }
 6818:         }
 6819:     }
 6820:     my $response;
 6821:     foreach my $server (@homeservers) {
 6822:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6823:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6824:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6825:             split(':',$response);
 6826:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6827:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6828:         foreach my $item (split('&',$cat_title)) {   
 6829:             my ($name,$value)=split('=',$item);
 6830:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6831:         }
 6832:         foreach my $item (split('&',$cat_order)) {
 6833:             my ($name,$value)=split('=',$item);
 6834:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6835:         }
 6836:         return 'ok';
 6837:     }
 6838:     return $response;
 6839: }
 6840: 
 6841: sub auto_courserequest_checks {
 6842:     my ($dom) = @_;
 6843:     my ($homeserver,%validations);
 6844:     if ($dom =~ /^$match_domain$/) {
 6845:         $homeserver = &domain($dom,'primary');
 6846:     }
 6847:     unless ($homeserver eq 'no_host') {
 6848:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6849:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6850:             my @items = split(/&/,$response);
 6851:             foreach my $item (@items) {
 6852:                 my ($key,$value) = split('=',$item);
 6853:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6854:             }
 6855:         }
 6856:     }
 6857:     return %validations; 
 6858: }
 6859: 
 6860: sub auto_courserequest_validation {
 6861:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6862:     my ($homeserver,$response);
 6863:     if ($dom =~ /^$match_domain$/) {
 6864:         $homeserver = &domain($dom,'primary');
 6865:     }
 6866:     unless ($homeserver eq 'no_host') {  
 6867:           
 6868:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6869:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6870:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6871:                                     $homeserver));
 6872:     }
 6873:     return $response;
 6874: }
 6875: 
 6876: sub auto_validate_class_sec {
 6877:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6878:     my $homeserver = &homeserver($cnum,$cdom);
 6879:     my $ownerlist;
 6880:     if (ref($owners) eq 'ARRAY') {
 6881:         $ownerlist = join(',',@{$owners});
 6882:     } else {
 6883:         $ownerlist = $owners;
 6884:     }
 6885:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6886:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6887:     return $response;
 6888: }
 6889: 
 6890: # ------------------------------------------------------- Course Group routines
 6891: 
 6892: sub get_coursegroups {
 6893:     my ($cdom,$cnum,$group,$namespace) = @_;
 6894:     return(&dump($namespace,$cdom,$cnum,$group));
 6895: }
 6896: 
 6897: sub modify_coursegroup {
 6898:     my ($cdom,$cnum,$groupsettings) = @_;
 6899:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6900: }
 6901: 
 6902: sub toggle_coursegroup_status {
 6903:     my ($cdom,$cnum,$group,$action) = @_;
 6904:     my ($from_namespace,$to_namespace);
 6905:     if ($action eq 'delete') {
 6906:         $from_namespace = 'coursegroups';
 6907:         $to_namespace = 'deleted_groups';
 6908:     } else {
 6909:         $from_namespace = 'deleted_groups';
 6910:         $to_namespace = 'coursegroups';
 6911:     }
 6912:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6913:     if (my $tmp = &error(%curr_group)) {
 6914:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6915:         return ('read error',$tmp);
 6916:     } else {
 6917:         my %savedsettings = %curr_group; 
 6918:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6919:         my $deloutcome;
 6920:         if ($result eq 'ok') {
 6921:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6922:         } else {
 6923:             return ('write error',$result);
 6924:         }
 6925:         if ($deloutcome eq 'ok') {
 6926:             return 'ok';
 6927:         } else {
 6928:             return ('delete error',$deloutcome);
 6929:         }
 6930:     }
 6931: }
 6932: 
 6933: sub modify_group_roles {
 6934:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6935:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6936:     my $role = 'gr/'.&escape($userprivs);
 6937:     my ($uname,$udom) = split(/:/,$user);
 6938:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6939:     if ($result eq 'ok') {
 6940:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6941:     }
 6942:     return $result;
 6943: }
 6944: 
 6945: sub modify_coursegroup_membership {
 6946:     my ($cdom,$cnum,$membership) = @_;
 6947:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6948:     return $result;
 6949: }
 6950: 
 6951: sub get_active_groups {
 6952:     my ($udom,$uname,$cdom,$cnum) = @_;
 6953:     my $now = time;
 6954:     my %groups = ();
 6955:     foreach my $key (keys(%env)) {
 6956:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6957:             my ($start,$end) = split(/\./,$env{$key});
 6958:             if (($end!=0) && ($end<$now)) { next; }
 6959:             if (($start!=0) && ($start>$now)) { next; }
 6960:             if ($1 eq $cdom && $2 eq $cnum) {
 6961:                 $groups{$3} = $env{$key} ;
 6962:             }
 6963:         }
 6964:     }
 6965:     return %groups;
 6966: }
 6967: 
 6968: sub get_group_membership {
 6969:     my ($cdom,$cnum,$group) = @_;
 6970:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6971: }
 6972: 
 6973: sub get_users_groups {
 6974:     my ($udom,$uname,$courseid) = @_;
 6975:     my @usersgroups;
 6976:     my $cachetime=1800;
 6977: 
 6978:     my $hashid="$udom:$uname:$courseid";
 6979:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6980:     if (defined($cached)) {
 6981:         @usersgroups = split(/:/,$grouplist);
 6982:     } else {  
 6983:         $grouplist = '';
 6984:         my $courseurl = &courseid_to_courseurl($courseid);
 6985:         my $extra = &freeze_escape({'skipcheck' => 1});
 6986:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 6987:         my $access_end = $env{'course.'.$courseid.
 6988:                               '.default_enrollment_end_date'};
 6989:         my $now = time;
 6990:         foreach my $key (keys(%roleshash)) {
 6991:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6992:                 my $group = $1;
 6993:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6994:                     my $start = $2;
 6995:                     my $end = $1;
 6996:                     if ($start == -1) { next; } # deleted from group
 6997:                     if (($start!=0) && ($start>$now)) { next; }
 6998:                     if (($end!=0) && ($end<$now)) {
 6999:                         if ($access_end && $access_end < $now) {
 7000:                             if ($access_end - $end < 86400) {
 7001:                                 push(@usersgroups,$group);
 7002:                             }
 7003:                         }
 7004:                         next;
 7005:                     }
 7006:                     push(@usersgroups,$group);
 7007:                 }
 7008:             }
 7009:         }
 7010:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7011:         $grouplist = join(':',@usersgroups);
 7012:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7013:     }
 7014:     return @usersgroups;
 7015: }
 7016: 
 7017: sub devalidate_getgroups_cache {
 7018:     my ($udom,$uname,$cdom,$cnum)=@_;
 7019:     my $courseid = $cdom.'_'.$cnum;
 7020: 
 7021:     my $hashid="$udom:$uname:$courseid";
 7022:     &devalidate_cache_new('getgroups',$hashid);
 7023: }
 7024: 
 7025: # ------------------------------------------------------------------ Plain Text
 7026: 
 7027: sub plaintext {
 7028:     my ($short,$type,$cid,$forcedefault) = @_;
 7029:     if ($short =~ m{^cr/}) {
 7030: 	return (split('/',$short))[-1];
 7031:     }
 7032:     if (!defined($cid)) {
 7033:         $cid = $env{'request.course.id'};
 7034:     }
 7035:     my %rolenames = (
 7036:                       Course    => 'std',
 7037:                       Community => 'alt1',
 7038:                     );
 7039:     if ($cid ne '') {
 7040:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7041:             unless ($forcedefault) {
 7042:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7043:                 &Apache::lonlocal::mt_escape(\$roletext);
 7044:                 return &Apache::lonlocal::mt($roletext);
 7045:             }
 7046:         }
 7047:     }
 7048:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7049:         (defined($rolenames{$type})) && 
 7050:         (defined($prp{$short}{$rolenames{$type}}))) {
 7051:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7052:     } elsif ($cid ne '') {
 7053:         my $crstype = $env{'course.'.$cid.'.type'};
 7054:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7055:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7056:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7057:         }
 7058:     }
 7059:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7060: }
 7061: 
 7062: # ----------------------------------------------------------------- Assign Role
 7063: 
 7064: sub assignrole {
 7065:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7066:         $context)=@_;
 7067:     my $mrole;
 7068:     if ($role =~ /^cr\//) {
 7069:         my $cwosec=$url;
 7070:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7071: 	unless (&allowed('ccr',$cwosec)) {
 7072:            my $refused = 1;
 7073:            if ($context eq 'requestcourses') {
 7074:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7075:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7076:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7077:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7078:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7079:                            if ($crsenv{'internal.courseowner'} eq
 7080:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7081:                                $refused = '';
 7082:                            }
 7083:                        }
 7084:                    }
 7085:                }
 7086:            }
 7087:            if ($refused) {
 7088:                &logthis('Refused custom assignrole: '.
 7089:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7090:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7091:                return 'refused';
 7092:            }
 7093:         }
 7094:         $mrole='cr';
 7095:     } elsif ($role =~ /^gr\//) {
 7096:         my $cwogrp=$url;
 7097:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7098:         unless (&allowed('mdg',$cwogrp)) {
 7099:             &logthis('Refused group assignrole: '.
 7100:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7101:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7102:             return 'refused';
 7103:         }
 7104:         $mrole='gr';
 7105:     } else {
 7106:         my $cwosec=$url;
 7107:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7108:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7109:             my $refused;
 7110:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7111:                 if (!(&allowed('c'.$role,$url))) {
 7112:                     $refused = 1;
 7113:                 }
 7114:             } else {
 7115:                 $refused = 1;
 7116:             }
 7117:             if ($refused) {
 7118:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7119:                 if (!$selfenroll && $context eq 'course') {
 7120:                     my %crsenv;
 7121:                     if ($role eq 'cc' || $role eq 'co') {
 7122:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7123:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7124:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7125:                                 if ($crsenv{'internal.courseowner'} eq 
 7126:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7127:                                     $refused = '';
 7128:                                 }
 7129:                             }
 7130:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7131:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7132:                                 if ($crsenv{'internal.courseowner'} eq 
 7133:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7134:                                     $refused = '';
 7135:                                 }
 7136:                             }
 7137:                         }
 7138:                     }
 7139:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7140:                     $refused = '';
 7141:                 } elsif ($context eq 'requestcourses') {
 7142:                     my @possroles = ('st','ta','ep','in','cc','co');
 7143:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7144:                         my $wrongcc;
 7145:                         if ($cnum =~ /^$match_community$/) {
 7146:                             $wrongcc = 1 if ($role eq 'cc');
 7147:                         } else {
 7148:                             $wrongcc = 1 if ($role eq 'co');
 7149:                         }
 7150:                         unless ($wrongcc) {
 7151:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7152:                             if ($crsenv{'internal.courseowner'} eq 
 7153:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7154:                                 $refused = '';
 7155:                             }
 7156:                         }
 7157:                     }
 7158:                 }
 7159:                 if ($refused) {
 7160:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7161:                              ' '.$role.' '.$end.' '.$start.' by '.
 7162: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7163:                     return 'refused';
 7164:                 }
 7165:             }
 7166:         } elsif ($role eq 'au') {
 7167:             if ($url ne '/'.$udom.'/') {
 7168:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7169:                          ' to assign author role for '.$uname.':'.$udom.
 7170:                          ' in domain: '.$url.' refused (wrong domain).');
 7171:                 return 'refused';
 7172:             }
 7173:         }
 7174:         $mrole=$role;
 7175:     }
 7176:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7177:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7178:     if ($end) { $command.='_'.$end; }
 7179:     if ($start) {
 7180: 	if ($end) { 
 7181:            $command.='_'.$start; 
 7182:         } else {
 7183:            $command.='_0_'.$start;
 7184:         }
 7185:     }
 7186:     my $origstart = $start;
 7187:     my $origend = $end;
 7188:     my $delflag;
 7189: # actually delete
 7190:     if ($deleteflag) {
 7191: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7192: # modify command to delete the role
 7193:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7194:                 "$udom:$uname:$url".'_'."$mrole";
 7195: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7196: # set start and finish to negative values for userrolelog
 7197:            $start=-1;
 7198:            $end=-1;
 7199:            $delflag = 1;
 7200:         }
 7201:     }
 7202: # send command
 7203:     my $answer=&reply($command,&homeserver($uname,$udom));
 7204: # log new user role if status is ok
 7205:     if ($answer eq 'ok') {
 7206: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7207: # for course roles, perform group memberships changes triggered by role change.
 7208:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7209:         unless ($role =~ /^gr/) {
 7210:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7211:                                              $origstart,$selfenroll,$context);
 7212:         }
 7213:         if ($role eq 'cc') {
 7214:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7215:         }
 7216:     }
 7217:     return $answer;
 7218: }
 7219: 
 7220: sub autoupdate_coowners {
 7221:     my ($url,$end,$start,$uname,$udom) = @_;
 7222:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7223:     if (($cdom ne '') && ($cnum ne '')) {
 7224:         my $now = time;
 7225:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7226:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7227:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7228:             my $instcode = $coursehash{'internal.coursecode'};
 7229:             if ($instcode ne '') {
 7230:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7231:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7232:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7233:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7234:                         if ($result eq 'valid') {
 7235:                             if ($coursehash{'internal.co-owners'}) {
 7236:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7237:                                     push(@newcoowners,$coowner);
 7238:                                 }
 7239:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7240:                                     push(@newcoowners,$uname.':'.$udom);
 7241:                                 }
 7242:                                 @newcoowners = sort(@newcoowners);
 7243:                             } else {
 7244:                                 push(@newcoowners,$uname.':'.$udom);
 7245:                             }
 7246:                         } else {
 7247:                             if ($coursehash{'internal.co-owners'}) {
 7248:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7249:                                     unless ($coowner eq $uname.':'.$udom) {
 7250:                                         push(@newcoowners,$coowner);
 7251:                                     }
 7252:                                 }
 7253:                                 unless (@newcoowners > 0) {
 7254:                                     $delcoowners = 1;
 7255:                                     $coowners = '';
 7256:                                 }
 7257:                             }
 7258:                         }
 7259:                         if (@newcoowners || $delcoowners) {
 7260:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7261:                                             $delcoowners,@newcoowners);
 7262:                         }
 7263:                     }
 7264:                 }
 7265:             }
 7266:         }
 7267:     }
 7268: }
 7269: 
 7270: sub store_coowners {
 7271:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7272:     my $cid = $cdom.'_'.$cnum;
 7273:     my ($coowners,$delresult,$putresult);
 7274:     if (@newcoowners) {
 7275:         $coowners = join(',',@newcoowners);
 7276:         my %coownershash = (
 7277:                             'internal.co-owners' => $coowners,
 7278:                            );
 7279:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7280:         if ($putresult eq 'ok') {
 7281:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7282:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7283:             }
 7284:         }
 7285:     }
 7286:     if ($delcoowners) {
 7287:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7288:         if ($delresult eq 'ok') {
 7289:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7290:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7291:             }
 7292:         }
 7293:     }
 7294:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7295:         my %crsinfo =
 7296:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7297:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7298:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7299:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7300:         }
 7301:     }
 7302: }
 7303: 
 7304: # -------------------------------------------------- Modify user authentication
 7305: # Overrides without validation
 7306: 
 7307: sub modifyuserauth {
 7308:     my ($udom,$uname,$umode,$upass)=@_;
 7309:     my $uhome=&homeserver($uname,$udom);
 7310:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7311:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7312:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7313:              ' in domain '.$env{'request.role.domain'});  
 7314:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7315: 		     &escape($upass),$uhome);
 7316:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7317:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7318:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7319:     &log($udom,,$uname,$uhome,
 7320:         'Authentication changed by '.$env{'user.domain'}.', '.
 7321:                                      $env{'user.name'}.', '.$umode.
 7322:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7323:     unless ($reply eq 'ok') {
 7324:         &logthis('Authentication mode error: '.$reply);
 7325: 	return 'error: '.$reply;
 7326:     }   
 7327:     return 'ok';
 7328: }
 7329: 
 7330: # --------------------------------------------------------------- Modify a user
 7331: 
 7332: sub modifyuser {
 7333:     my ($udom,    $uname, $uid,
 7334:         $umode,   $upass, $first,
 7335:         $middle,  $last,  $gene,
 7336:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7337:     $udom= &LONCAPA::clean_domain($udom);
 7338:     $uname=&LONCAPA::clean_username($uname);
 7339:     my $showcandelete = 'none';
 7340:     if (ref($candelete) eq 'ARRAY') {
 7341:         if (@{$candelete} > 0) {
 7342:             $showcandelete = join(', ',@{$candelete});
 7343:         }
 7344:     }
 7345:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7346:              $umode.', '.$first.', '.$middle.', '.
 7347: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7348:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7349:                                      ' desiredhome not specified'). 
 7350:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7351:              ' in domain '.$env{'request.role.domain'});
 7352:     my $uhome=&homeserver($uname,$udom,'true');
 7353:     my $newuser;
 7354:     if ($uhome eq 'no_host') {
 7355:         $newuser = 1;
 7356:     }
 7357: # ----------------------------------------------------------------- Create User
 7358:     if (($uhome eq 'no_host') && 
 7359: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7360:         my $unhome='';
 7361:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7362:             $unhome = $desiredhome;
 7363: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7364: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7365:         } else { # load balancing routine for determining $unhome
 7366:             my $loadm=10000000;
 7367: 	    my %servers = &get_servers($udom,'library');
 7368: 	    foreach my $tryserver (keys(%servers)) {
 7369: 		my $answer=reply('load',$tryserver);
 7370: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7371: 		    $loadm=$answer;
 7372: 		    $unhome=$tryserver;
 7373: 		}
 7374: 	    }
 7375:         }
 7376:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7377: 	    return 'error: unable to find a home server for '.$uname.
 7378:                    ' in domain '.$udom;
 7379:         }
 7380:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7381:                          &escape($upass),$unhome);
 7382: 	unless ($reply eq 'ok') {
 7383:             return 'error: '.$reply;
 7384:         }   
 7385:         $uhome=&homeserver($uname,$udom,'true');
 7386:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7387: 	    return 'error: unable verify users home machine.';
 7388:         }
 7389:     }   # End of creation of new user
 7390: # ---------------------------------------------------------------------- Add ID
 7391:     if ($uid) {
 7392:        $uid=~tr/A-Z/a-z/;
 7393:        my %uidhash=&idrget($udom,$uname);
 7394:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7395:          && (!$forceid)) {
 7396: 	  unless ($uid eq $uidhash{$uname}) {
 7397: 	      return 'error: user id "'.$uid.'" does not match '.
 7398:                   'current user id "'.$uidhash{$uname}.'".';
 7399:           }
 7400:        } else {
 7401: 	  &idput($udom,($uname => $uid));
 7402:        }
 7403:     }
 7404: # -------------------------------------------------------------- Add names, etc
 7405:     my @tmp=&get('environment',
 7406: 		   ['firstname','middlename','lastname','generation','id',
 7407:                     'permanentemail','inststatus'],
 7408: 		   $udom,$uname);
 7409:     my (%names,%oldnames);
 7410:     if ($tmp[0] =~ m/^error:.*/) { 
 7411:         %names=(); 
 7412:     } else {
 7413:         %names = @tmp;
 7414:         %oldnames = %names;
 7415:     }
 7416: #
 7417: # If name, email and/or uid are blank (e.g., because an uploaded file
 7418: # of users did not contain them), do not overwrite existing values
 7419: # unless field is in $candelete array ref.  
 7420: #
 7421: 
 7422:     my @fields = ('firstname','middlename','lastname','generation',
 7423:                   'permanentemail','id');
 7424:     my %newvalues;
 7425:     if (ref($candelete) eq 'ARRAY') {
 7426:         foreach my $field (@fields) {
 7427:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7428:                 if ($field eq 'firstname') {
 7429:                     $names{$field} = $first;
 7430:                 } elsif ($field eq 'middlename') {
 7431:                     $names{$field} = $middle;
 7432:                 } elsif ($field eq 'lastname') {
 7433:                     $names{$field} = $last;
 7434:                 } elsif ($field eq 'generation') { 
 7435:                     $names{$field} = $gene;
 7436:                 } elsif ($field eq 'permanentemail') {
 7437:                     $names{$field} = $email;
 7438:                 } elsif ($field eq 'id') {
 7439:                     $names{$field}  = $uid;
 7440:                 }
 7441:             }
 7442:         }
 7443:     }
 7444:     if ($first)  { $names{'firstname'}  = $first; }
 7445:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7446:     if ($last)   { $names{'lastname'}   = $last; }
 7447:     if (defined($gene))   { $names{'generation'} = $gene; }
 7448:     if ($email) {
 7449:        $email=~s/[^\w\@\.\-\,]//gs;
 7450:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7451:     }
 7452:     if ($uid) { $names{'id'}  = $uid; }
 7453:     if (defined($inststatus)) {
 7454:         $names{'inststatus'} = '';
 7455:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7456:         if (ref($usertypes) eq 'HASH') {
 7457:             my @okstatuses; 
 7458:             foreach my $item (split(/:/,$inststatus)) {
 7459:                 if (defined($usertypes->{$item})) {
 7460:                     push(@okstatuses,$item);  
 7461:                 }
 7462:             }
 7463:             if (@okstatuses) {
 7464:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7465:             }
 7466:         }
 7467:     }
 7468:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7469:                  $umode.', '.$first.', '.$middle.', '.
 7470:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7471:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7472:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7473:     } else {
 7474:         $logmsg .= ' during self creation';
 7475:     }
 7476:     my $changed;
 7477:     if ($newuser) {
 7478:         $changed = 1;
 7479:     } else {
 7480:         foreach my $field (@fields) {
 7481:             if ($names{$field} ne $oldnames{$field}) {
 7482:                 $changed = 1;
 7483:                 last;
 7484:             }
 7485:         }
 7486:     }
 7487:     unless ($changed) {
 7488:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7489:         &logthis($logmsg);
 7490:         return 'ok';
 7491:     }
 7492:     my $reply = &put('environment', \%names, $udom,$uname);
 7493:     if ($reply ne 'ok') { 
 7494:         return 'error: '.$reply;
 7495:     }
 7496:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7497:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7498:     }
 7499:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7500:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7501:     $logmsg = 'Success modifying user '.$logmsg;
 7502:     &logthis($logmsg);
 7503:     return 'ok';
 7504: }
 7505: 
 7506: # -------------------------------------------------------------- Modify student
 7507: 
 7508: sub modifystudent {
 7509:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7510:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7511:         $selfenroll,$context,$inststatus)=@_;
 7512:     if (!$cid) {
 7513: 	unless ($cid=$env{'request.course.id'}) {
 7514: 	    return 'not_in_class';
 7515: 	}
 7516:     }
 7517: # --------------------------------------------------------------- Make the user
 7518:     my $reply=&modifyuser
 7519: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7520:          $desiredhome,$email,$inststatus);
 7521:     unless ($reply eq 'ok') { return $reply; }
 7522:     # This will cause &modify_student_enrollment to get the uid from the
 7523:     # students environment
 7524:     $uid = undef if (!$forceid);
 7525:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7526: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7527:     return $reply;
 7528: }
 7529: 
 7530: sub modify_student_enrollment {
 7531:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7532:     my ($cdom,$cnum,$chome);
 7533:     if (!$cid) {
 7534: 	unless ($cid=$env{'request.course.id'}) {
 7535: 	    return 'not_in_class';
 7536: 	}
 7537: 	$cdom=$env{'course.'.$cid.'.domain'};
 7538: 	$cnum=$env{'course.'.$cid.'.num'};
 7539:     } else {
 7540: 	($cdom,$cnum)=split(/_/,$cid);
 7541:     }
 7542:     $chome=$env{'course.'.$cid.'.home'};
 7543:     if (!$chome) {
 7544: 	$chome=&homeserver($cnum,$cdom);
 7545:     }
 7546:     if (!$chome) { return 'unknown_course'; }
 7547:     # Make sure the user exists
 7548:     my $uhome=&homeserver($uname,$udom);
 7549:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7550: 	return 'error: no such user';
 7551:     }
 7552:     # Get student data if we were not given enough information
 7553:     if (!defined($first)  || $first  eq '' || 
 7554:         !defined($last)   || $last   eq '' || 
 7555:         !defined($uid)    || $uid    eq '' || 
 7556:         !defined($middle) || $middle eq '' || 
 7557:         !defined($gene)   || $gene   eq '') {
 7558:         # They did not supply us with enough data to enroll the student, so
 7559:         # we need to pick up more information.
 7560:         my %tmp = &get('environment',
 7561:                        ['firstname','middlename','lastname', 'generation','id']
 7562:                        ,$udom,$uname);
 7563: 
 7564:         #foreach my $key (keys(%tmp)) {
 7565:         #    &logthis("key $key = ".$tmp{$key});
 7566:         #}
 7567:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7568:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7569:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7570:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7571:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7572:     }
 7573:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7574:     my $user = "$uname:$udom";
 7575:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7576:     my $reply=cput('classlist',
 7577: 		   {$user => 
 7578: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7579: 		   $cdom,$cnum);
 7580:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7581:         &devalidate_getsection_cache($udom,$uname,$cid);
 7582:     } else { 
 7583: 	return 'error: '.$reply;
 7584:     }
 7585:     # Add student role to user
 7586:     my $uurl='/'.$cid;
 7587:     $uurl=~s/\_/\//g;
 7588:     if ($usec) {
 7589: 	$uurl.='/'.$usec;
 7590:     }
 7591:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7592:                              $selfenroll,$context);
 7593:     if ($result ne 'ok') {
 7594:         if ($old_entry{$user} ne '') {
 7595:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7596:         } else {
 7597:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7598:         }
 7599:     }
 7600:     return $result; 
 7601: }
 7602: 
 7603: sub format_name {
 7604:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7605:     my $name;
 7606:     if ($first ne 'lastname') {
 7607: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7608:     } else {
 7609: 	if ($lastname=~/\S/) {
 7610: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7611: 	    $name=~s/\s+,/,/;
 7612: 	} else {
 7613: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7614: 	}
 7615:     }
 7616:     $name=~s/^\s+//;
 7617:     $name=~s/\s+$//;
 7618:     $name=~s/\s+/ /g;
 7619:     return $name;
 7620: }
 7621: 
 7622: # ------------------------------------------------- Write to course preferences
 7623: 
 7624: sub writecoursepref {
 7625:     my ($courseid,%prefs)=@_;
 7626:     $courseid=~s/^\///;
 7627:     $courseid=~s/\_/\//g;
 7628:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7629:     my $chome=homeserver($cnum,$cdomain);
 7630:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7631: 	return 'error: no such course';
 7632:     }
 7633:     my $cstring='';
 7634:     foreach my $pref (keys(%prefs)) {
 7635: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7636:     }
 7637:     $cstring=~s/\&$//;
 7638:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7639: }
 7640: 
 7641: # ---------------------------------------------------------- Make/modify course
 7642: 
 7643: sub createcourse {
 7644:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7645:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7646:     $url=&declutter($url);
 7647:     my $cid='';
 7648:     if ($context eq 'requestcourses') {
 7649:         my $can_create = 0;
 7650:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7651:         if ($udom eq $ownerdom) {
 7652:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7653:                                   $context)) {
 7654:                 $can_create = 1;
 7655:             }
 7656:         } else {
 7657:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7658:                                            $category);
 7659:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7660:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7661:                 if (@curr > 0) {
 7662:                     my @options = qw(approval validate autolimit);
 7663:                     my $optregex = join('|',@options);
 7664:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7665:                         $can_create = 1;
 7666:                     }
 7667:                 }
 7668:             }
 7669:         }
 7670:         if ($can_create) {
 7671:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7672:                 unless (&allowed('ccc',$udom)) {
 7673:                     return 'refused'; 
 7674:                 }
 7675:             }
 7676:         } else {
 7677:             return 'refused';
 7678:         }
 7679:     } elsif (!&allowed('ccc',$udom)) {
 7680:         return 'refused';
 7681:     }
 7682: # --------------------------------------------------------------- Get Unique ID
 7683:     my $uname;
 7684:     if ($cnum =~ /^$match_courseid$/) {
 7685:         my $chome=&homeserver($cnum,$udom,'true');
 7686:         if (($chome eq '') || ($chome eq 'no_host')) {
 7687:             $uname = $cnum;
 7688:         } else {
 7689:             $uname = &generate_coursenum($udom,$crstype);
 7690:         }
 7691:     } else {
 7692:         $uname = &generate_coursenum($udom,$crstype);
 7693:     }
 7694:     return $uname if ($uname =~ /^error/);
 7695: # -------------------------------------------------- Check supplied server name
 7696:     if (!defined($course_server)) {
 7697:         if (defined(&domain($udom,'primary'))) {
 7698:             $course_server = &domain($udom,'primary');
 7699:         } else {
 7700:             $course_server = $env{'user.home'}; 
 7701:         }
 7702:     }
 7703:     my %host_servers =
 7704:         &Apache::lonnet::get_servers($udom,'library');
 7705:     unless ($host_servers{$course_server}) {
 7706:         return 'error: invalid home server for course: '.$course_server;
 7707:     }
 7708: # ------------------------------------------------------------- Make the course
 7709:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 7710:                       $course_server);
 7711:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 7712:     my $uhome=&homeserver($uname,$udom,'true');
 7713:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7714: 	return 'error: no such course';
 7715:     }
 7716: # ----------------------------------------------------------------- Course made
 7717: # log existence
 7718:     my $now = time;
 7719:     my $newcourse = {
 7720:                     $udom.'_'.$uname => {
 7721:                                      description => $description,
 7722:                                      inst_code   => $inst_code,
 7723:                                      owner       => $course_owner,
 7724:                                      type        => $crstype,
 7725:                                      creator     => $env{'user.name'}.':'.
 7726:                                                     $env{'user.domain'},
 7727:                                      created     => $now,
 7728:                                      context     => $context,
 7729:                                                 },
 7730:                     };
 7731:     &courseidput($udom,$newcourse,$uhome,'notime');
 7732: # set toplevel url
 7733:     my $topurl=$url;
 7734:     unless ($nonstandard) {
 7735: # ------------------------------------------ For standard courses, make top url
 7736:         my $mapurl=&clutter($url);
 7737:         if ($mapurl eq '/res/') { $mapurl=''; }
 7738:         $env{'form.initmap'}=(<<ENDINITMAP);
 7739: <map>
 7740: <resource id="1" type="start"></resource>
 7741: <resource id="2" src="$mapurl"></resource>
 7742: <resource id="3" type="finish"></resource>
 7743: <link index="1" from="1" to="2"></link>
 7744: <link index="2" from="2" to="3"></link>
 7745: </map>
 7746: ENDINITMAP
 7747:         $topurl=&declutter(
 7748:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7749:                           );
 7750:     }
 7751: # ----------------------------------------------------------- Write preferences
 7752:     &writecoursepref($udom.'_'.$uname,
 7753:                      ('description'              => $description,
 7754:                       'url'                      => $topurl,
 7755:                       'internal.creator'         => $env{'user.name'}.':'.
 7756:                                                     $env{'user.domain'},
 7757:                       'internal.created'         => $now,
 7758:                       'internal.creationcontext' => $context)
 7759:                     );
 7760:     return '/'.$udom.'/'.$uname;
 7761: }
 7762: 
 7763: # ------------------------------------------------------------------- Create ID
 7764: sub generate_coursenum {
 7765:     my ($udom,$crstype) = @_;
 7766:     my $domdesc = &domain($udom);
 7767:     return 'error: invalid domain' if ($domdesc eq '');
 7768:     my $first;
 7769:     if ($crstype eq 'Community') {
 7770:         $first = '0';
 7771:     } else {
 7772:         $first = int(1+rand(9)); 
 7773:     } 
 7774:     my $uname=$first.
 7775:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7776:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7777:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7778: # ----------------------------------------------- Make sure that does not exist
 7779:     my $uhome=&homeserver($uname,$udom,'true');
 7780:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7781:         if ($crstype eq 'Community') {
 7782:             $first = '0';
 7783:         } else {
 7784:             $first = int(1+rand(9));
 7785:         }
 7786:         $uname=$first.
 7787:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7788:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7789:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7790:         $uhome=&homeserver($uname,$udom,'true');
 7791:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7792:             return 'error: unable to generate unique course-ID';
 7793:         }
 7794:     }
 7795:     return $uname;
 7796: }
 7797: 
 7798: sub is_course {
 7799:     my ($cdom,$cnum) = @_;
 7800:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7801: 				undef,'.');
 7802:     if (exists($courses{$cdom.'_'.$cnum})) {
 7803:         return 1;
 7804:     }
 7805:     return 0;
 7806: }
 7807: 
 7808: sub store_userdata {
 7809:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7810:     my $result;
 7811:     if ($datakey ne '') {
 7812:         if (ref($storehash) eq 'HASH') {
 7813:             if ($udom eq '' || $uname eq '') {
 7814:                 $udom = $env{'user.domain'};
 7815:                 $uname = $env{'user.name'};
 7816:             }
 7817:             my $uhome=&homeserver($uname,$udom);
 7818:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7819:                 $result = 'error: no_host';
 7820:             } else {
 7821:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7822:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7823: 
 7824:                 my $namevalue='';
 7825:                 foreach my $key (keys(%{$storehash})) {
 7826:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7827:                 }
 7828:                 $namevalue=~s/\&$//;
 7829:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 7830:                                   $namevalue,$uhome);
 7831:             }
 7832:         } else {
 7833:             $result = 'error: data to store was not a hash reference'; 
 7834:         }
 7835:     } else {
 7836:         $result= 'error: invalid requestkey'; 
 7837:     }
 7838:     return $result;
 7839: }
 7840: 
 7841: # ---------------------------------------------------------- Assign Custom Role
 7842: 
 7843: sub assigncustomrole {
 7844:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7845:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7846:                        $end,$start,$deleteflag,$selfenroll,$context);
 7847: }
 7848: 
 7849: # ----------------------------------------------------------------- Revoke Role
 7850: 
 7851: sub revokerole {
 7852:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7853:     my $now=time;
 7854:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7855: }
 7856: 
 7857: # ---------------------------------------------------------- Revoke Custom Role
 7858: 
 7859: sub revokecustomrole {
 7860:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7861:     my $now=time;
 7862:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7863:            $deleteflag,$selfenroll,$context);
 7864: }
 7865: 
 7866: # ------------------------------------------------------------ Disk usage
 7867: sub diskusage {
 7868:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7869:     $directorypath =~ s/\/$//;
 7870:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7871:                        .&escape($getpropath).':'.&escape($uname).':'
 7872:                        .&escape($udom),homeserver($uname,$udom));
 7873:     if ($listing eq 'unknown_cmd') {
 7874:         if ($getpropath) {
 7875:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7876:         }
 7877:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7878:     }
 7879:     return $listing;
 7880: }
 7881: 
 7882: sub is_locked {
 7883:     my ($file_name, $domain, $user, $which) = @_;
 7884:     my @check;
 7885:     my $is_locked;
 7886:     push (@check,$file_name);
 7887:     my %locked = &get('file_permissions',\@check,
 7888: 		      $env{'user.domain'},$env{'user.name'});
 7889:     my ($tmp)=keys(%locked);
 7890:     if ($tmp=~/^error:/) { undef(%locked); }
 7891:     
 7892:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7893:         $is_locked = 'false';
 7894:         foreach my $entry (@{$locked{$file_name}}) {
 7895:            if (ref($entry) eq 'ARRAY') {
 7896:                $is_locked = 'true';
 7897:                if (ref($which) eq 'ARRAY') {
 7898:                    push(@{$which},$entry);
 7899:                } else {
 7900:                    last;
 7901:                }
 7902:            }
 7903:        }
 7904:     } else {
 7905:         $is_locked = 'false';
 7906:     }
 7907:     return $is_locked;
 7908: }
 7909: 
 7910: sub declutter_portfile {
 7911:     my ($file) = @_;
 7912:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7913:     return $file;
 7914: }
 7915: 
 7916: # ------------------------------------------------------------- Mark as Read Only
 7917: 
 7918: sub mark_as_readonly {
 7919:     my ($domain,$user,$files,$what) = @_;
 7920:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7921:     my ($tmp)=keys(%current_permissions);
 7922:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7923:     foreach my $file (@{$files}) {
 7924: 	$file = &declutter_portfile($file);
 7925:         push(@{$current_permissions{$file}},$what);
 7926:     }
 7927:     &put('file_permissions',\%current_permissions,$domain,$user);
 7928:     return;
 7929: }
 7930: 
 7931: # ------------------------------------------------------------Save Selected Files
 7932: 
 7933: sub save_selected_files {
 7934:     my ($user, $path, @files) = @_;
 7935:     my $filename = $user."savedfiles";
 7936:     my @other_files = &files_not_in_path($user, $path);
 7937:     open (OUT, '>'.$tmpdir.$filename);
 7938:     foreach my $file (@files) {
 7939:         print (OUT $env{'form.currentpath'}.$file."\n");
 7940:     }
 7941:     foreach my $file (@other_files) {
 7942:         print (OUT $file."\n");
 7943:     }
 7944:     close (OUT);
 7945:     return 'ok';
 7946: }
 7947: 
 7948: sub clear_selected_files {
 7949:     my ($user) = @_;
 7950:     my $filename = $user."savedfiles";
 7951:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 7952:     print (OUT undef);
 7953:     close (OUT);
 7954:     return ("ok");    
 7955: }
 7956: 
 7957: sub files_in_path {
 7958:     my ($user, $path) = @_;
 7959:     my $filename = $user."savedfiles";
 7960:     my %return_files;
 7961:     open (IN, '<'.LONCAPA::tempdir().$filename);
 7962:     while (my $line_in = <IN>) {
 7963:         chomp ($line_in);
 7964:         my @paths_and_file = split (m!/!, $line_in);
 7965:         my $file_part = pop (@paths_and_file);
 7966:         my $path_part = join ('/', @paths_and_file);
 7967:         $path_part.='/';
 7968:         my $path_and_file = $path_part.$file_part;
 7969:         if ($path_part eq $path) {
 7970:             $return_files{$file_part}= 'selected';
 7971:         }
 7972:     }
 7973:     close (IN);
 7974:     return (\%return_files);
 7975: }
 7976: 
 7977: # called in portfolio select mode, to show files selected NOT in current directory
 7978: sub files_not_in_path {
 7979:     my ($user, $path) = @_;
 7980:     my $filename = $user."savedfiles";
 7981:     my @return_files;
 7982:     my $path_part;
 7983:     open(IN, '<'.LONCAPA::.$filename);
 7984:     while (my $line = <IN>) {
 7985:         #ok, I know it's clunky, but I want it to work
 7986:         my @paths_and_file = split(m|/|, $line);
 7987:         my $file_part = pop(@paths_and_file);
 7988:         chomp($file_part);
 7989:         my $path_part = join('/', @paths_and_file);
 7990:         $path_part .= '/';
 7991:         my $path_and_file = $path_part.$file_part;
 7992:         if ($path_part ne $path) {
 7993:             push(@return_files, ($path_and_file));
 7994:         }
 7995:     }
 7996:     close(OUT);
 7997:     return (@return_files);
 7998: }
 7999: 
 8000: #----------------------------------------------Get portfolio file permissions
 8001: 
 8002: sub get_portfile_permissions {
 8003:     my ($domain,$user) = @_;
 8004:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8005:     my ($tmp)=keys(%current_permissions);
 8006:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8007:     return \%current_permissions;
 8008: }
 8009: 
 8010: #---------------------------------------------Get portfolio file access controls
 8011: 
 8012: sub get_access_controls {
 8013:     my ($current_permissions,$group,$file) = @_;
 8014:     my %access;
 8015:     my $real_file = $file;
 8016:     $file =~ s/\.meta$//;
 8017:     if (defined($file)) {
 8018:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8019:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8020:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8021:             }
 8022:         }
 8023:     } else {
 8024:         foreach my $key (keys(%{$current_permissions})) {
 8025:             if ($key =~ /\0accesscontrol$/) {
 8026:                 if (defined($group)) {
 8027:                     if ($key !~ m-^\Q$group\E/-) {
 8028:                         next;
 8029:                     }
 8030:                 }
 8031:                 my ($fullpath) = split(/\0/,$key);
 8032:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8033:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8034:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8035:                     }
 8036:                 }
 8037:             }
 8038:         }
 8039:     }
 8040:     return %access;
 8041: }
 8042: 
 8043: sub modify_access_controls {
 8044:     my ($file_name,$changes,$domain,$user)=@_;
 8045:     my ($outcome,$deloutcome);
 8046:     my %store_permissions;
 8047:     my %new_values;
 8048:     my %new_control;
 8049:     my %translation;
 8050:     my @deletions = ();
 8051:     my $now = time;
 8052:     if (exists($$changes{'activate'})) {
 8053:         if (ref($$changes{'activate'}) eq 'HASH') {
 8054:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8055:             my $numnew = scalar(@newitems);
 8056:             for (my $i=0; $i<$numnew; $i++) {
 8057:                 my $newkey = $newitems[$i];
 8058:                 my $newid = &Apache::loncommon::get_cgi_id();
 8059:                 if ($newkey =~ /^\d+:/) { 
 8060:                     $newkey =~ s/^(\d+)/$newid/;
 8061:                     $translation{$1} = $newid;
 8062:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8063:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8064:                     $translation{$1} = $newid;
 8065:                 }
 8066:                 $new_values{$file_name."\0".$newkey} = 
 8067:                                           $$changes{'activate'}{$newitems[$i]};
 8068:                 $new_control{$newkey} = $now;
 8069:             }
 8070:         }
 8071:     }
 8072:     my %todelete;
 8073:     my %changed_items;
 8074:     foreach my $action ('delete','update') {
 8075:         if (exists($$changes{$action})) {
 8076:             if (ref($$changes{$action}) eq 'HASH') {
 8077:                 foreach my $key (keys(%{$$changes{$action}})) {
 8078:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8079:                     if ($action eq 'delete') { 
 8080:                         $todelete{$itemnum} = 1;
 8081:                     } else {
 8082:                         $changed_items{$itemnum} = $key;
 8083:                     }
 8084:                 }
 8085:             }
 8086:         }
 8087:     }
 8088:     # get lock on access controls for file.
 8089:     my $lockhash = {
 8090:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8091:                                                        ':'.$env{'user.domain'},
 8092:                    }; 
 8093:     my $tries = 0;
 8094:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8095:    
 8096:     while (($gotlock ne 'ok') && $tries <3) {
 8097:         $tries ++;
 8098:         sleep 1;
 8099:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8100:     }
 8101:     if ($gotlock eq 'ok') {
 8102:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8103:         my ($tmp)=keys(%curr_permissions);
 8104:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8105:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8106:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8107:             if (ref($curr_controls) eq 'HASH') {
 8108:                 foreach my $control_item (keys(%{$curr_controls})) {
 8109:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8110:                     if (defined($todelete{$itemnum})) {
 8111:                         push(@deletions,$file_name."\0".$control_item);
 8112:                     } else {
 8113:                         if (defined($changed_items{$itemnum})) {
 8114:                             $new_control{$changed_items{$itemnum}} = $now;
 8115:                             push(@deletions,$file_name."\0".$control_item);
 8116:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8117:                         } else {
 8118:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8119:                         }
 8120:                     }
 8121:                 }
 8122:             }
 8123:         }
 8124:         my ($group);
 8125:         if (&is_course($domain,$user)) {
 8126:             ($group,my $file) = split(/\//,$file_name,2);
 8127:         }
 8128:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8129:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8130:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8131:         #  remove lock
 8132:         my @del_lock = ($file_name."\0".'locked_access_records');
 8133:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8134:         my $sqlresult =
 8135:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8136:                                     $group);
 8137:     } else {
 8138:         $outcome = "error: could not obtain lockfile\n";  
 8139:     }
 8140:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8141: }
 8142: 
 8143: sub make_public_indefinitely {
 8144:     my ($requrl) = @_;
 8145:     my $now = time;
 8146:     my $action = 'activate';
 8147:     my $aclnum = 0;
 8148:     if (&is_portfolio_url($requrl)) {
 8149:         my (undef,$udom,$unum,$file_name,$group) =
 8150:             &parse_portfolio_url($requrl);
 8151:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8152:         my %access_controls = &get_access_controls($current_perms,
 8153:                                                    $group,$file_name);
 8154:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8155:             my ($num,$scope,$end,$start) = 
 8156:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8157:             if ($scope eq 'public') {
 8158:                 if ($start <= $now && $end == 0) {
 8159:                     $action = 'none';
 8160:                 } else {
 8161:                     $action = 'update';
 8162:                     $aclnum = $num;
 8163:                 }
 8164:                 last;
 8165:             }
 8166:         }
 8167:         if ($action eq 'none') {
 8168:              return 'ok';
 8169:         } else {
 8170:             my %changes;
 8171:             my $newend = 0;
 8172:             my $newstart = $now;
 8173:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8174:             $changes{$action}{$newkey} = {
 8175:                 type => 'public',
 8176:                 time => {
 8177:                     start => $newstart,
 8178:                     end   => $newend,
 8179:                 },
 8180:             };
 8181:             my ($outcome,$deloutcome,$new_values,$translation) =
 8182:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8183:             return $outcome;
 8184:         }
 8185:     } else {
 8186:         return 'invalid';
 8187:     }
 8188: }
 8189: 
 8190: #------------------------------------------------------Get Marked as Read Only
 8191: 
 8192: sub get_marked_as_readonly {
 8193:     my ($domain,$user,$what,$group) = @_;
 8194:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8195:     my @readonly_files;
 8196:     my $cmp1=$what;
 8197:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8198:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8199:         if (defined($group)) {
 8200:             if ($file_name !~ m-^\Q$group\E/-) {
 8201:                 next;
 8202:             }
 8203:         }
 8204:         if (ref($value) eq "ARRAY"){
 8205:             foreach my $stored_what (@{$value}) {
 8206:                 my $cmp2=$stored_what;
 8207:                 if (ref($stored_what) eq 'ARRAY') {
 8208:                     $cmp2=join('',@{$stored_what});
 8209:                 }
 8210:                 if ($cmp1 eq $cmp2) {
 8211:                     push(@readonly_files, $file_name);
 8212:                     last;
 8213:                 } elsif (!defined($what)) {
 8214:                     push(@readonly_files, $file_name);
 8215:                     last;
 8216:                 }
 8217:             }
 8218:         }
 8219:     }
 8220:     return @readonly_files;
 8221: }
 8222: #-----------------------------------------------------------Get Marked as Read Only Hash
 8223: 
 8224: sub get_marked_as_readonly_hash {
 8225:     my ($current_permissions,$group,$what) = @_;
 8226:     my %readonly_files;
 8227:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8228:         if (defined($group)) {
 8229:             if ($file_name !~ m-^\Q$group\E/-) {
 8230:                 next;
 8231:             }
 8232:         }
 8233:         if (ref($value) eq "ARRAY"){
 8234:             foreach my $stored_what (@{$value}) {
 8235:                 if (ref($stored_what) eq 'ARRAY') {
 8236:                     foreach my $lock_descriptor(@{$stored_what}) {
 8237:                         if ($lock_descriptor eq 'graded') {
 8238:                             $readonly_files{$file_name} = 'graded';
 8239:                         } elsif ($lock_descriptor eq 'handback') {
 8240:                             $readonly_files{$file_name} = 'handback';
 8241:                         } else {
 8242:                             if (!exists($readonly_files{$file_name})) {
 8243:                                 $readonly_files{$file_name} = 'locked';
 8244:                             }
 8245:                         }
 8246:                     }
 8247:                 } 
 8248:             }
 8249:         } 
 8250:     }
 8251:     return %readonly_files;
 8252: }
 8253: # ------------------------------------------------------------ Unmark as Read Only
 8254: 
 8255: sub unmark_as_readonly {
 8256:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8257:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8258:     my ($domain,$user,$what,$file_name,$group) = @_;
 8259:     $file_name = &declutter_portfile($file_name);
 8260:     my $symb_crs = $what;
 8261:     if (ref($what)) { $symb_crs=join('',@$what); }
 8262:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8263:     my ($tmp)=keys(%current_permissions);
 8264:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8265:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8266:     foreach my $file (@readonly_files) {
 8267: 	my $clean_file = &declutter_portfile($file);
 8268: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8269: 	my $current_locks = $current_permissions{$file};
 8270:         my @new_locks;
 8271:         my @del_keys;
 8272:         if (ref($current_locks) eq "ARRAY"){
 8273:             foreach my $locker (@{$current_locks}) {
 8274:                 my $compare=$locker;
 8275:                 if (ref($locker) eq 'ARRAY') {
 8276:                     $compare=join('',@{$locker});
 8277:                     if ($compare ne $symb_crs) {
 8278:                         push(@new_locks, $locker);
 8279:                     }
 8280:                 }
 8281:             }
 8282:             if (scalar(@new_locks) > 0) {
 8283:                 $current_permissions{$file} = \@new_locks;
 8284:             } else {
 8285:                 push(@del_keys, $file);
 8286:                 &del('file_permissions',\@del_keys, $domain, $user);
 8287:                 delete($current_permissions{$file});
 8288:             }
 8289:         }
 8290:     }
 8291:     &put('file_permissions',\%current_permissions,$domain,$user);
 8292:     return;
 8293: }
 8294: 
 8295: # ------------------------------------------------------------ Directory lister
 8296: 
 8297: sub dirlist {
 8298:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8299:     $uri=~s/^\///;
 8300:     $uri=~s/\/$//;
 8301:     my ($udom, $uname);
 8302:     if ($getuserdir) {
 8303:         $udom = $userdomain;
 8304:         $uname = $username;
 8305:     } else {
 8306:         (undef,$udom,$uname)=split(/\//,$uri);
 8307:         if(defined($userdomain)) {
 8308:             $udom = $userdomain;
 8309:         }
 8310:         if(defined($username)) {
 8311:             $uname = $username;
 8312:         }
 8313:     }
 8314:     my ($dirRoot,$listing,@listing_results);
 8315: 
 8316:     $dirRoot = $perlvar{'lonDocRoot'};
 8317:     if (defined($getpropath)) {
 8318:         $dirRoot = &propath($udom,$uname);
 8319:         $dirRoot =~ s/\/$//;
 8320:     } elsif (defined($getuserdir)) {
 8321:         my $subdir=$uname.'__';
 8322:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8323:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8324:                    ."/$udom/$subdir/$uname";
 8325:     } elsif (defined($alternateRoot)) {
 8326:         $dirRoot = $alternateRoot;
 8327:     }
 8328: 
 8329:     if($udom) {
 8330:         if($uname) {
 8331:             my $uhome = &homeserver($uname,$udom);
 8332:             if ($uhome eq 'no_host') {
 8333:                 return ([],'no_host');
 8334:             }
 8335:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8336:                               .$getuserdir.':'.&escape($dirRoot)
 8337:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8338:             if ($listing eq 'unknown_cmd') {
 8339:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8340:             } else {
 8341:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8342:             }
 8343:             if ($listing eq 'unknown_cmd') {
 8344:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8345:                 @listing_results = split(/:/,$listing);
 8346:             } else {
 8347:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8348:             }
 8349:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8350:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8351:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8352:                 return ([],$listing);
 8353:             } else {
 8354:                 return (\@listing_results);
 8355:             }
 8356:         } elsif(!$alternateRoot) {
 8357:             my (%allusers,%listerror);
 8358: 	    my %servers = &get_servers($udom,'library');
 8359:  	    foreach my $tryserver (keys(%servers)) {
 8360:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8361:                                   &escape($udom),$tryserver);
 8362:                 if ($listing eq 'unknown_cmd') {
 8363: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8364: 				      $udom, $tryserver);
 8365:                 } else {
 8366:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8367:                 }
 8368: 		if ($listing eq 'unknown_cmd') {
 8369: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8370: 				      $udom, $tryserver);
 8371: 		    @listing_results = split(/:/,$listing);
 8372: 		} else {
 8373: 		    @listing_results =
 8374: 			map { &unescape($_); } split(/:/,$listing);
 8375: 		}
 8376:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8377:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8378:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8379:                     $listerror{$tryserver} = $listing;
 8380:                 } else {
 8381: 		    foreach my $line (@listing_results) {
 8382: 			my ($entry) = split(/&/,$line,2);
 8383: 			$allusers{$entry} = 1;
 8384: 		    }
 8385: 		}
 8386:             }
 8387:             my @alluserslist=();
 8388:             foreach my $user (sort(keys(%allusers))) {
 8389:                 push(@alluserslist,$user.'&user');
 8390:             }
 8391:             return (\@alluserslist);
 8392:         } else {
 8393:             return ([],'missing username');
 8394:         }
 8395:     } elsif(!defined($getpropath)) {
 8396:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8397:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8398:         return (\@all_domains);
 8399:     } else {
 8400:         return ([],'missing domain');
 8401:     }
 8402: }
 8403: 
 8404: # --------------------------------------------- GetFileTimestamp
 8405: # This function utilizes dirlist and returns the date stamp for
 8406: # when it was last modified.  It will also return an error of -1
 8407: # if an error occurs
 8408: 
 8409: sub GetFileTimestamp {
 8410:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8411:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8412:     $studentName   = &LONCAPA::clean_username($studentName);
 8413:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8414:                                     undef,$getuserdir);
 8415:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8416:         return -1;
 8417:     }
 8418:     if (ref($fileref) eq 'ARRAY') {
 8419:         my @stats = split('&',$fileref->[0]);
 8420:         # @stats contains first the filename, then the stat output
 8421:         return $stats[10]; # so this is 10 instead of 9.
 8422:     } else {
 8423:         return -1;
 8424:     }
 8425: }
 8426: 
 8427: sub stat_file {
 8428:     my ($uri) = @_;
 8429:     $uri = &clutter_with_no_wrapper($uri);
 8430: 
 8431:     my ($udom,$uname,$file);
 8432:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8433: 	($udom,$uname,$file) =
 8434: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8435: 	$file = 'userfiles/'.$file;
 8436:     }
 8437:     if ($uri =~ m-^/res/-) {
 8438: 	($udom,$uname) = 
 8439: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8440: 	$file = $uri;
 8441:     }
 8442: 
 8443:     if (!$udom || !$uname || !$file) {
 8444: 	# unable to handle the uri
 8445: 	return ();
 8446:     }
 8447:     my $getpropath;
 8448:     if ($file =~ /^userfiles\//) {
 8449:         $getpropath = 1;
 8450:     }
 8451:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8452:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8453:         return ();
 8454:     } else {
 8455:         if (ref($listref) eq 'ARRAY') {
 8456:             my @stats = split('&',$listref->[0]);
 8457: 	    shift(@stats); #filename is first
 8458: 	    return @stats;
 8459:         }
 8460:     }
 8461:     return ();
 8462: }
 8463: 
 8464: # -------------------------------------------------------- Value of a Condition
 8465: 
 8466: # gets the value of a specific preevaluated condition
 8467: #    stored in the string  $env{user.state.<cid>}
 8468: # or looks up a condition reference in the bighash and if if hasn't
 8469: # already been evaluated recurses into docondval to get the value of
 8470: # the condition, then memoizing it to 
 8471: #   $env{user.state.<cid>.<condition>}
 8472: sub directcondval {
 8473:     my $number=shift;
 8474:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8475: 	&Apache::lonuserstate::evalstate();
 8476:     }
 8477:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8478: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8479:     } elsif ($number =~ /^_/) {
 8480: 	my $sub_condition;
 8481: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8482: 		&GDBM_READER(),0640)) {
 8483: 	    $sub_condition=$bighash{'conditions'.$number};
 8484: 	    untie(%bighash);
 8485: 	}
 8486: 	my $value = &docondval($sub_condition);
 8487: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8488: 	return $value;
 8489:     }
 8490:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8491:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8492:     } else {
 8493:        return 2;
 8494:     }
 8495: }
 8496: 
 8497: # get the collection of conditions for this resource
 8498: sub condval {
 8499:     my $condidx=shift;
 8500:     my $allpathcond='';
 8501:     foreach my $cond (split(/\|/,$condidx)) {
 8502: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8503: 	    $allpathcond.=
 8504: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8505: 	}
 8506:     }
 8507:     $allpathcond=~s/\|$//;
 8508:     return &docondval($allpathcond);
 8509: }
 8510: 
 8511: #evaluates an expression of conditions
 8512: sub docondval {
 8513:     my ($allpathcond) = @_;
 8514:     my $result=0;
 8515:     if ($env{'request.course.id'}
 8516: 	&& defined($allpathcond)) {
 8517: 	my $operand='|';
 8518: 	my @stack;
 8519: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8520: 	    if ($chunk eq '(') {
 8521: 		push @stack,($operand,$result);
 8522: 	    } elsif ($chunk eq ')') {
 8523: 		my $before=pop @stack;
 8524: 		if (pop @stack eq '&') {
 8525: 		    $result=$result>$before?$before:$result;
 8526: 		} else {
 8527: 		    $result=$result>$before?$result:$before;
 8528: 		}
 8529: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8530: 		$operand=$chunk;
 8531: 	    } else {
 8532: 		my $new=directcondval($chunk);
 8533: 		if ($operand eq '&') {
 8534: 		    $result=$result>$new?$new:$result;
 8535: 		} else {
 8536: 		    $result=$result>$new?$result:$new;
 8537: 		}
 8538: 	    }
 8539: 	}
 8540:     }
 8541:     return $result;
 8542: }
 8543: 
 8544: # ---------------------------------------------------- Devalidate courseresdata
 8545: 
 8546: sub devalidatecourseresdata {
 8547:     my ($coursenum,$coursedomain)=@_;
 8548:     my $hashid=$coursenum.':'.$coursedomain;
 8549:     &devalidate_cache_new('courseres',$hashid);
 8550: }
 8551: 
 8552: 
 8553: # --------------------------------------------------- Course Resourcedata Query
 8554: #
 8555: #  Parameters:
 8556: #      $coursenum    - Number of the course.
 8557: #      $coursedomain - Domain at which the course was created.
 8558: #  Returns:
 8559: #     A hash of the course parameters along (I think) with timestamps
 8560: #     and version info.
 8561: 
 8562: sub get_courseresdata {
 8563:     my ($coursenum,$coursedomain)=@_;
 8564:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8565:     my $hashid=$coursenum.':'.$coursedomain;
 8566:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8567:     my %dumpreply;
 8568:     unless (defined($cached)) {
 8569: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8570: 	$result=\%dumpreply;
 8571: 	my ($tmp) = keys(%dumpreply);
 8572: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8573: 	    &do_cache_new('courseres',$hashid,$result,600);
 8574: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8575: 	    return $tmp;
 8576: 	} elsif ($tmp =~ /^(error)/) {
 8577: 	    $result=undef;
 8578: 	    &do_cache_new('courseres',$hashid,$result,600);
 8579: 	}
 8580:     }
 8581:     return $result;
 8582: }
 8583: 
 8584: sub devalidateuserresdata {
 8585:     my ($uname,$udom)=@_;
 8586:     my $hashid="$udom:$uname";
 8587:     &devalidate_cache_new('userres',$hashid);
 8588: }
 8589: 
 8590: sub get_userresdata {
 8591:     my ($uname,$udom)=@_;
 8592:     #most student don\'t have any data set, check if there is some data
 8593:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8594: 
 8595:     my $hashid="$udom:$uname";
 8596:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8597:     if (!defined($cached)) {
 8598: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8599: 	$result=\%resourcedata;
 8600: 	&do_cache_new('userres',$hashid,$result,600);
 8601:     }
 8602:     my ($tmp)=keys(%$result);
 8603:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8604: 	return $result;
 8605:     }
 8606:     #error 2 occurs when the .db doesn't exist
 8607:     if ($tmp!~/error: 2 /) {
 8608: 	&logthis("<font color=\"blue\">WARNING:".
 8609: 		 " Trying to get resource data for ".
 8610: 		 $uname." at ".$udom.": ".
 8611: 		 $tmp."</font>");
 8612:     } elsif ($tmp=~/error: 2 /) {
 8613: 	#&EXT_cache_set($udom,$uname);
 8614: 	&do_cache_new('userres',$hashid,undef,600);
 8615: 	undef($tmp); # not really an error so don't send it back
 8616:     }
 8617:     return $tmp;
 8618: }
 8619: #----------------------------------------------- resdata - return resource data
 8620: #  Purpose:
 8621: #    Return resource data for either users or for a course.
 8622: #  Parameters:
 8623: #     $name      - Course/user name.
 8624: #     $domain    - Name of the domain the user/course is registered on.
 8625: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8626: #     @which     - Array of names of resources desired.
 8627: #  Returns:
 8628: #     The value of the first reasource in @which that is found in the
 8629: #     resource hash.
 8630: #  Exceptional Conditions:
 8631: #     If the $type passed in is not valid (not the string 'course' or 
 8632: #     'user', an undefined  reference is returned.
 8633: #     If none of the resources are found, an undef is returned
 8634: sub resdata {
 8635:     my ($name,$domain,$type,@which)=@_;
 8636:     my $result;
 8637:     if ($type eq 'course') {
 8638: 	$result=&get_courseresdata($name,$domain);
 8639:     } elsif ($type eq 'user') {
 8640: 	$result=&get_userresdata($name,$domain);
 8641:     }
 8642:     if (!ref($result)) { return $result; }    
 8643:     foreach my $item (@which) {
 8644: 	if (defined($result->{$item->[0]})) {
 8645: 	    return [$result->{$item->[0]},$item->[1]];
 8646: 	}
 8647:     }
 8648:     return undef;
 8649: }
 8650: 
 8651: #
 8652: # EXT resource caching routines
 8653: #
 8654: 
 8655: sub clear_EXT_cache_status {
 8656:     &delenv('cache.EXT.');
 8657: }
 8658: 
 8659: sub EXT_cache_status {
 8660:     my ($target_domain,$target_user) = @_;
 8661:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8662:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8663:         # We know already the user has no data
 8664:         return 1;
 8665:     } else {
 8666:         return 0;
 8667:     }
 8668: }
 8669: 
 8670: sub EXT_cache_set {
 8671:     my ($target_domain,$target_user) = @_;
 8672:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8673:     #&appenv({$cachename => time});
 8674: }
 8675: 
 8676: # --------------------------------------------------------- Value of a Variable
 8677: sub EXT {
 8678: 
 8679:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8680:     unless ($varname) { return ''; }
 8681:     #get real user name/domain, courseid and symb
 8682:     my $courseid;
 8683:     my $publicuser;
 8684:     if ($symbparm) {
 8685: 	$symbparm=&get_symb_from_alias($symbparm);
 8686:     }
 8687:     if (!($uname && $udom)) {
 8688:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8689:       if (!$symbparm) {	$symbparm=$cursymb; }
 8690:     } else {
 8691: 	$courseid=$env{'request.course.id'};
 8692:     }
 8693:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8694:     my $rest;
 8695:     if (defined($therest[0])) {
 8696:        $rest=join('.',@therest);
 8697:     } else {
 8698:        $rest='';
 8699:     }
 8700: 
 8701:     my $qualifierrest=$qualifier;
 8702:     if ($rest) { $qualifierrest.='.'.$rest; }
 8703:     my $spacequalifierrest=$space;
 8704:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 8705:     if ($realm eq 'user') {
 8706: # --------------------------------------------------------------- user.resource
 8707: 	if ($space eq 'resource') {
 8708: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 8709: 		  || defined($Apache::lonhomework::parsing_a_task))
 8710: 		 &&
 8711: 		 ($symbparm eq &symbread()) ) {	
 8712: 		# if we are in the middle of processing the resource the
 8713: 		# get the value we are planning on committing
 8714:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 8715:                     return $Apache::lonhomework::results{$qualifierrest};
 8716:                 } else {
 8717:                     return $Apache::lonhomework::history{$qualifierrest};
 8718:                 }
 8719: 	    } else {
 8720: 		my %restored;
 8721: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 8722: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 8723: 		} else {
 8724: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 8725: 		}
 8726: 		return $restored{$qualifierrest};
 8727: 	    }
 8728: # ----------------------------------------------------------------- user.access
 8729:         } elsif ($space eq 'access') {
 8730: 	    # FIXME - not supporting calls for a specific user
 8731:             return &allowed($qualifier,$rest);
 8732: # ------------------------------------------ user.preferences, user.environment
 8733:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 8734: 	    if (($uname eq $env{'user.name'}) &&
 8735: 		($udom eq $env{'user.domain'})) {
 8736: 		return $env{join('.',('environment',$qualifierrest))};
 8737: 	    } else {
 8738: 		my %returnhash;
 8739: 		if (!$publicuser) {
 8740: 		    %returnhash=&userenvironment($udom,$uname,
 8741: 						 $qualifierrest);
 8742: 		}
 8743: 		return $returnhash{$qualifierrest};
 8744: 	    }
 8745: # ----------------------------------------------------------------- user.course
 8746:         } elsif ($space eq 'course') {
 8747: 	    # FIXME - not supporting calls for a specific user
 8748:             return $env{join('.',('request.course',$qualifier))};
 8749: # ------------------------------------------------------------------- user.role
 8750:         } elsif ($space eq 'role') {
 8751: 	    # FIXME - not supporting calls for a specific user
 8752:             my ($role,$where)=split(/\./,$env{'request.role'});
 8753:             if ($qualifier eq 'value') {
 8754: 		return $role;
 8755:             } elsif ($qualifier eq 'extent') {
 8756:                 return $where;
 8757:             }
 8758: # ----------------------------------------------------------------- user.domain
 8759:         } elsif ($space eq 'domain') {
 8760:             return $udom;
 8761: # ------------------------------------------------------------------- user.name
 8762:         } elsif ($space eq 'name') {
 8763:             return $uname;
 8764: # ---------------------------------------------------- Any other user namespace
 8765:         } else {
 8766: 	    my %reply;
 8767: 	    if (!$publicuser) {
 8768: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8769: 	    }
 8770: 	    return $reply{$qualifierrest};
 8771:         }
 8772:     } elsif ($realm eq 'query') {
 8773: # ---------------------------------------------- pull stuff out of query string
 8774:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8775: 						[$spacequalifierrest]);
 8776: 	return $env{'form.'.$spacequalifierrest}; 
 8777:    } elsif ($realm eq 'request') {
 8778: # ------------------------------------------------------------- request.browser
 8779:         if ($space eq 'browser') {
 8780:             return $env{'browser.'.$qualifier};
 8781: # ------------------------------------------------------------ request.filename
 8782:         } else {
 8783:             return $env{'request.'.$spacequalifierrest};
 8784:         }
 8785:     } elsif ($realm eq 'course') {
 8786: # ---------------------------------------------------------- course.description
 8787:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8788:     } elsif ($realm eq 'resource') {
 8789: 
 8790: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8791: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8792: 	}
 8793: 
 8794: 	if ($space eq 'title') {
 8795: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8796: 	    return &gettitle($symbparm);
 8797: 	}
 8798: 	
 8799: 	if ($space eq 'map') {
 8800: 	    my ($map) = &decode_symb($symbparm);
 8801: 	    return &symbread($map);
 8802: 	}
 8803: 	if ($space eq 'filename') {
 8804: 	    if ($symbparm) {
 8805: 		return &clutter((&decode_symb($symbparm))[2]);
 8806: 	    }
 8807: 	    return &hreflocation('',$env{'request.filename'});
 8808: 	}
 8809: 
 8810: 	my ($section, $group, @groups);
 8811: 	my ($courselevelm,$courselevel);
 8812: 	if ($symbparm && defined($courseid) && 
 8813: 	    $courseid eq $env{'request.course.id'}) {
 8814: 
 8815: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8816: 
 8817: # ----------------------------------------------------- Cascading lookup scheme
 8818: 	    my $symbp=$symbparm;
 8819: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8820: 
 8821: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8822: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8823: 
 8824: 	    if (($env{'user.name'} eq $uname) &&
 8825: 		($env{'user.domain'} eq $udom)) {
 8826: 		$section=$env{'request.course.sec'};
 8827:                 @groups = split(/:/,$env{'request.course.groups'});  
 8828:                 @groups=&sort_course_groups($courseid,@groups); 
 8829: 	    } else {
 8830: 		if (! defined($usection)) {
 8831: 		    $section=&getsection($udom,$uname,$courseid);
 8832: 		} else {
 8833: 		    $section = $usection;
 8834: 		}
 8835:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8836: 	    }
 8837: 
 8838: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8839: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8840: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8841: 
 8842: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8843: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8844: 	    $courselevelm=$courseid.'.'.$mapparm;
 8845: 
 8846: # ----------------------------------------------------------- first, check user
 8847: 
 8848: 	    my $userreply=&resdata($uname,$udom,'user',
 8849: 				       ([$courselevelr,'resource'],
 8850: 					[$courselevelm,'map'     ],
 8851: 					[$courselevel, 'course'  ]));
 8852: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8853: 
 8854: # ------------------------------------------------ second, check some of course
 8855:             my $coursereply;
 8856:             if (@groups > 0) {
 8857:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8858:                                        $mapparm,$spacequalifierrest);
 8859:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8860:             }
 8861: 
 8862: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8863: 				  $env{'course.'.$courseid.'.domain'},
 8864: 				  'course',
 8865: 				  ([$seclevelr,   'resource'],
 8866: 				   [$seclevelm,   'map'     ],
 8867: 				   [$seclevel,    'course'  ],
 8868: 				   [$courselevelr,'resource']));
 8869: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8870: 
 8871: # ------------------------------------------------------ third, check map parms
 8872: 	    my %parmhash=();
 8873: 	    my $thisparm='';
 8874: 	    if (tie(%parmhash,'GDBM_File',
 8875: 		    $env{'request.course.fn'}.'_parms.db',
 8876: 		    &GDBM_READER(),0640)) {
 8877: 		$thisparm=$parmhash{$symbparm};
 8878: 		untie(%parmhash);
 8879: 	    }
 8880: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8881: 	}
 8882: # ------------------------------------------ fourth, look in resource metadata
 8883: 
 8884: 	$spacequalifierrest=~s/\./\_/;
 8885: 	my $filename;
 8886: 	if (!$symbparm) { $symbparm=&symbread(); }
 8887: 	if ($symbparm) {
 8888: 	    $filename=(&decode_symb($symbparm))[2];
 8889: 	} else {
 8890: 	    $filename=$env{'request.filename'};
 8891: 	}
 8892: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8893: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8894: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8895: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8896: 
 8897: # ---------------------------------------------- fourth, look in rest of course
 8898: 	if ($symbparm && defined($courseid) && 
 8899: 	    $courseid eq $env{'request.course.id'}) {
 8900: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8901: 				     $env{'course.'.$courseid.'.domain'},
 8902: 				     'course',
 8903: 				     ([$courselevelm,'map'   ],
 8904: 				      [$courselevel, 'course']));
 8905: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8906: 	}
 8907: # ------------------------------------------------------------------ Cascade up
 8908: 	unless ($space eq '0') {
 8909: 	    my @parts=split(/_/,$space);
 8910: 	    my $id=pop(@parts);
 8911: 	    my $part=join('_',@parts);
 8912: 	    if ($part eq '') { $part='0'; }
 8913: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8914: 				 $symbparm,$udom,$uname,$section,1);
 8915: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8916: 	}
 8917: 	if ($recurse) { return undef; }
 8918: 	my $pack_def=&packages_tab_default($filename,$varname);
 8919: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8920: # ---------------------------------------------------- Any other user namespace
 8921:     } elsif ($realm eq 'environment') {
 8922: # ----------------------------------------------------------------- environment
 8923: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8924: 	    return $env{'environment.'.$spacequalifierrest};
 8925: 	} else {
 8926: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8927: 		return '';
 8928: 	    }
 8929: 	    my %returnhash=&userenvironment($udom,$uname,
 8930: 					    $spacequalifierrest);
 8931: 	    return $returnhash{$spacequalifierrest};
 8932: 	}
 8933:     } elsif ($realm eq 'system') {
 8934: # ----------------------------------------------------------------- system.time
 8935: 	if ($space eq 'time') {
 8936: 	    return time;
 8937:         }
 8938:     } elsif ($realm eq 'server') {
 8939: # ----------------------------------------------------------------- system.time
 8940: 	if ($space eq 'name') {
 8941: 	    return $ENV{'SERVER_NAME'};
 8942:         }
 8943:     }
 8944:     return '';
 8945: }
 8946: 
 8947: sub get_reply {
 8948:     my ($reply_value) = @_;
 8949:     if (ref($reply_value) eq 'ARRAY') {
 8950:         if (wantarray) {
 8951: 	    return @$reply_value;
 8952:         }
 8953:         return $reply_value->[0];
 8954:     } else {
 8955:         return $reply_value;
 8956:     }
 8957: }
 8958: 
 8959: sub check_group_parms {
 8960:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8961:     my @groupitems = ();
 8962:     my $resultitem;
 8963:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8964:     foreach my $group (@{$groups}) {
 8965:         foreach my $level (@levels) {
 8966:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8967:              push(@groupitems,[$item,$level->[1]]);
 8968:         }
 8969:     }
 8970:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8971:                             $env{'course.'.$courseid.'.domain'},
 8972:                                      'course',@groupitems);
 8973:     return $coursereply;
 8974: }
 8975: 
 8976: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8977:     my ($courseid,@groups) = @_;
 8978:     @groups = sort(@groups);
 8979:     return @groups;
 8980: }
 8981: 
 8982: sub packages_tab_default {
 8983:     my ($uri,$varname)=@_;
 8984:     my (undef,$part,$name)=split(/\./,$varname);
 8985: 
 8986:     my (@extension,@specifics,$do_default);
 8987:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8988: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8989: 	if ($pack_type eq 'default') {
 8990: 	    $do_default=1;
 8991: 	} elsif ($pack_type eq 'extension') {
 8992: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8993: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8994: 	    # only look at packages defaults for packages that this id is
 8995: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8996: 	}
 8997:     }
 8998:     # first look for a package that matches the requested part id
 8999:     foreach my $package (@specifics) {
 9000: 	my (undef,$pack_type,$pack_part)=@{$package};
 9001: 	next if ($pack_part ne $part);
 9002: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9003: 	    return $packagetab{"$pack_type&$name&default"};
 9004: 	}
 9005:     }
 9006:     # look for any possible matching non extension_ package
 9007:     foreach my $package (@specifics) {
 9008: 	my (undef,$pack_type,$pack_part)=@{$package};
 9009: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9010: 	    return $packagetab{"$pack_type&$name&default"};
 9011: 	}
 9012: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9013: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9014: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9015: 	}
 9016:     }
 9017:     # look for any posible extension_ match
 9018:     foreach my $package (@extension) {
 9019: 	my ($package,$pack_type)=@{$package};
 9020: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9021: 	    return $packagetab{"$pack_type&$name&default"};
 9022: 	}
 9023: 	if (defined($packagetab{$package."&$name&default"})) {
 9024: 	    return $packagetab{$package."&$name&default"};
 9025: 	}
 9026:     }
 9027:     # look for a global default setting
 9028:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9029: 	return $packagetab{"default&$name&default"};
 9030:     }
 9031:     return undef;
 9032: }
 9033: 
 9034: sub add_prefix_and_part {
 9035:     my ($prefix,$part)=@_;
 9036:     my $keyroot;
 9037:     if (defined($prefix) && $prefix !~ /^__/) {
 9038: 	# prefix that has a part already
 9039: 	$keyroot=$prefix;
 9040:     } elsif (defined($prefix)) {
 9041: 	# prefix that is missing a part
 9042: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9043:     } else {
 9044: 	# no prefix at all
 9045: 	if (defined($part)) { $keyroot='_'.$part; }
 9046:     }
 9047:     return $keyroot;
 9048: }
 9049: 
 9050: # ---------------------------------------------------------------- Get metadata
 9051: 
 9052: my %metaentry;
 9053: my %importedpartids;
 9054: sub metadata {
 9055:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9056:     $uri=&declutter($uri);
 9057:     # if it is a non metadata possible uri return quickly
 9058:     if (($uri eq '') || 
 9059: 	(($uri =~ m|^/*adm/|) && 
 9060: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9061:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9062: 	return undef;
 9063:     }
 9064:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9065: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9066: 	return undef;
 9067:     }
 9068:     my $filename=$uri;
 9069:     $uri=~s/\.meta$//;
 9070: #
 9071: # Is the metadata already cached?
 9072: # Look at timestamp of caching
 9073: # Everything is cached by the main uri, libraries are never directly cached
 9074: #
 9075:     if (!defined($liburi)) {
 9076: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9077: 	if (defined($cached)) { return $result->{':'.$what}; }
 9078:     }
 9079:     {
 9080: # Imported parts would go here
 9081:         my %importedids=();
 9082:         my @origfileimportpartids=();
 9083:         my $importedparts=0;
 9084: #
 9085: # Is this a recursive call for a library?
 9086: #
 9087: #	if (! exists($metacache{$uri})) {
 9088: #	    $metacache{$uri}={};
 9089: #	}
 9090: 	my $cachetime = 60*60;
 9091:         if ($liburi) {
 9092: 	    $liburi=&declutter($liburi);
 9093:             $filename=$liburi;
 9094:         } else {
 9095: 	    &devalidate_cache_new('meta',$uri);
 9096: 	    undef(%metaentry);
 9097: 	}
 9098:         my %metathesekeys=();
 9099:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9100: 	my $metastring;
 9101: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9102: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9103: 	    $metastring = 
 9104: 		&Apache::lonnet::ssi_body($which,
 9105: 					  ('grade_target' => 'meta'));
 9106: 	    $cachetime = 1; # only want this cached in the child not long term
 9107: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9108:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9109: 	    my $file=&filelocation('',&clutter($filename));
 9110: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9111: 	    $metastring=&getfile($file);
 9112: 	}
 9113:         my $parser=HTML::LCParser->new(\$metastring);
 9114:         my $token;
 9115:         undef %metathesekeys;
 9116:         while ($token=$parser->get_token) {
 9117: 	    if ($token->[0] eq 'S') {
 9118: 		if (defined($token->[2]->{'package'})) {
 9119: #
 9120: # This is a package - get package info
 9121: #
 9122: 		    my $package=$token->[2]->{'package'};
 9123: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9124: 		    if (defined($token->[2]->{'id'})) { 
 9125: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9126: 		    }
 9127: 		    if ($metaentry{':packages'}) {
 9128: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9129: 		    } else {
 9130: 			$metaentry{':packages'}=$package.$keyroot;
 9131: 		    }
 9132: 		    foreach my $pack_entry (keys(%packagetab)) {
 9133: 			my $part=$keyroot;
 9134: 			$part=~s/^\_//;
 9135: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9136: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9137: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9138: 			    # ignore package.tab specified default values
 9139:                             # here &package_tab_default() will fetch those
 9140: 			    if ($subp eq 'default') { next; }
 9141: 			    my $value=$packagetab{$pack_entry};
 9142: 			    my $unikey;
 9143: 			    if ($pack =~ /_0$/) {
 9144: 				$unikey='parameter_0_'.$name;
 9145: 				$part=0;
 9146: 			    } else {
 9147: 				$unikey='parameter'.$keyroot.'_'.$name;
 9148: 			    }
 9149: 			    if ($subp eq 'display') {
 9150: 				$value.=' [Part: '.$part.']';
 9151: 			    }
 9152: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9153: 			    $metathesekeys{$unikey}=1;
 9154: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9155: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9156: 			    }
 9157: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9158: 				$metaentry{':'.$unikey}=
 9159: 				    $metaentry{':'.$unikey.'.default'};
 9160: 			    }
 9161: 			}
 9162: 		    }
 9163: 		} else {
 9164: #
 9165: # This is not a package - some other kind of start tag
 9166: #
 9167: 		    my $entry=$token->[1];
 9168: 		    my $unikey='';
 9169: 
 9170: 		    if ($entry eq 'import') {
 9171: #
 9172: # Importing a library here
 9173: #
 9174:                         my $location=$parser->get_text('/import');
 9175:                         my $dir=$filename;
 9176:                         $dir=~s|[^/]*$||;
 9177:                         $location=&filelocation($dir,$location);
 9178:                        
 9179:                         my $importmode=$token->[2]->{'importmode'};
 9180:                         if ($importmode eq 'problem') {
 9181: # Import as problem/response
 9182:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9183:                         } elsif ($importmode eq 'part') {
 9184: # Import as part(s)
 9185:                            $importedparts=1;
 9186: # We need to get the original file and the imported file to get the part order correct
 9187: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9188: # Load and inspect original file
 9189:                            if ($#origfileimportpartids<0) {
 9190:                               undef(%importedpartids);
 9191:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9192:                               my $origfile=&getfile($origfilelocation);
 9193:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9194:                            }
 9195: 
 9196: # Load and inspect imported file
 9197:                            my $impfile=&getfile($location);
 9198:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9199:                            if ($#impfilepartids>=0) {
 9200: # This problem had parts
 9201:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9202:                            } else {
 9203: # Importing by turning a single problem into a problem part
 9204: # It gets the import-tags ID as part-ID
 9205:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9206:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9207:                            }
 9208:                         } else {
 9209: # Normal import
 9210:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9211:                            if (defined($token->[2]->{'id'})) {
 9212:                               $unikey.='_'.$token->[2]->{'id'};
 9213:                            }
 9214:                         }
 9215: 
 9216: 			if ($depthcount<20) {
 9217: 			    my $metadata = 
 9218: 				&metadata($uri,'keys', $location,$unikey,
 9219: 					  $depthcount+1);
 9220: 			    foreach my $meta (split(',',$metadata)) {
 9221: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9222: 				$metathesekeys{$meta}=1;
 9223: 			    }
 9224: 			
 9225:                         }
 9226: 		    } else {
 9227: #
 9228: # Not importing, some other kind of non-package, non-library start tag
 9229: # 
 9230:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9231:                         if (defined($token->[2]->{'id'})) {
 9232:                             $unikey.='_'.$token->[2]->{'id'};
 9233:                         }
 9234: 			if (defined($token->[2]->{'name'})) { 
 9235: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9236: 			}
 9237: 			$metathesekeys{$unikey}=1;
 9238: 			foreach my $param (@{$token->[3]}) {
 9239: 			    $metaentry{':'.$unikey.'.'.$param} =
 9240: 				$token->[2]->{$param};
 9241: 			}
 9242: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9243: 			my $default=$metaentry{':'.$unikey.'.default'};
 9244: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9245: 		 # only ws inside the tag, and not in default, so use default
 9246: 		 # as value
 9247: 			    $metaentry{':'.$unikey}=$default;
 9248: 			} elsif ( $internaltext =~ /\S/ ) {
 9249: 		  # something interesting inside the tag
 9250: 			    $metaentry{':'.$unikey}=$internaltext;
 9251: 			} else {
 9252: 		  # no interesting values, don't set a default
 9253: 			}
 9254: # end of not-a-package not-a-library import
 9255: 		    }
 9256: # end of not-a-package start tag
 9257: 		}
 9258: # the next is the end of "start tag"
 9259: 	    }
 9260: 	}
 9261: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9262: 	$extension = lc($extension);
 9263: 	if ($extension eq 'htm') { $extension='html'; }
 9264: 
 9265: 	foreach my $key (keys(%packagetab)) {
 9266: 	    #no specific packages #how's our extension
 9267: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9268: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9269: 					 \%metathesekeys);
 9270: 	}
 9271: 
 9272: 	if (!exists($metaentry{':packages'})
 9273: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9274: 	    foreach my $key (keys(%packagetab)) {
 9275: 		#no specific packages well let's get default then
 9276: 		if ($key!~/^default&/) { next; }
 9277: 		&metadata_create_package_def($uri,$key,'default',
 9278: 					     \%metathesekeys);
 9279: 	    }
 9280: 	}
 9281: # are there custom rights to evaluate
 9282: 	if ($metaentry{':copyright'} eq 'custom') {
 9283: 
 9284:     #
 9285:     # Importing a rights file here
 9286:     #
 9287: 	    unless ($depthcount) {
 9288: 		my $location=$metaentry{':customdistributionfile'};
 9289: 		my $dir=$filename;
 9290: 		$dir=~s|[^/]*$||;
 9291: 		$location=&filelocation($dir,$location);
 9292: 		my $rights_metadata =
 9293: 		    &metadata($uri,'keys',$location,'_rights',
 9294: 			      $depthcount+1);
 9295: 		foreach my $rights (split(',',$rights_metadata)) {
 9296: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9297: 		    $metathesekeys{$rights}=1;
 9298: 		}
 9299: 	    }
 9300: 	}
 9301: 	# uniqifiy package listing
 9302: 	my %seen;
 9303: 	my @uniq_packages =
 9304: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9305: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9306: 
 9307:         if ($importedparts) {
 9308: # We had imported parts and need to rebuild partorder
 9309:            $metaentry{':partorder'}='';
 9310:            $metathesekeys{'partorder'}=1;
 9311:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9312:                if ($origfileimportpartids[$index] eq 'part') {
 9313: # original part, part of the problem
 9314:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9315:                } else {
 9316: # we have imported parts at this position
 9317:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9318:                }
 9319:            }
 9320:            $metaentry{':partorder'}=~s/^\,//;
 9321:         }
 9322: 
 9323: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9324: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9325: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9326: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9327: # this is the end of "was not already recently cached
 9328:     }
 9329:     return $metaentry{':'.$what};
 9330: }
 9331: 
 9332: sub metadata_create_package_def {
 9333:     my ($uri,$key,$package,$metathesekeys)=@_;
 9334:     my ($pack,$name,$subp)=split(/\&/,$key);
 9335:     if ($subp eq 'default') { next; }
 9336:     
 9337:     if (defined($metaentry{':packages'})) {
 9338: 	$metaentry{':packages'}.=','.$package;
 9339:     } else {
 9340: 	$metaentry{':packages'}=$package;
 9341:     }
 9342:     my $value=$packagetab{$key};
 9343:     my $unikey;
 9344:     $unikey='parameter_0_'.$name;
 9345:     $metaentry{':'.$unikey.'.part'}=0;
 9346:     $$metathesekeys{$unikey}=1;
 9347:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9348: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9349:     }
 9350:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9351: 	$metaentry{':'.$unikey}=
 9352: 	    $metaentry{':'.$unikey.'.default'};
 9353:     }
 9354: }
 9355: 
 9356: sub metadata_generate_part0 {
 9357:     my ($metadata,$metacache,$uri) = @_;
 9358:     my %allnames;
 9359:     foreach my $metakey (keys(%$metadata)) {
 9360: 	if ($metakey=~/^parameter\_(.*)/) {
 9361: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9362: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9363: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9364: 	    $allnames{$name}=$part;
 9365: 	  }
 9366: 	}
 9367:     }
 9368:     foreach my $name (keys(%allnames)) {
 9369:       $$metadata{"parameter_0_$name"}=1;
 9370:       my $key=":parameter_0_$name";
 9371:       $$metacache{"$key.part"}='0';
 9372:       $$metacache{"$key.name"}=$name;
 9373:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9374: 					   $allnames{$name}.'_'.$name.
 9375: 					   '.type'};
 9376:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9377: 			     '.display'};
 9378:       my $expr='[Part: '.$allnames{$name}.']';
 9379:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9380:       $$metacache{"$key.display"}=$olddis;
 9381:     }
 9382: }
 9383: 
 9384: # ------------------------------------------------------ Devalidate title cache
 9385: 
 9386: sub devalidate_title_cache {
 9387:     my ($url)=@_;
 9388:     if (!$env{'request.course.id'}) { return; }
 9389:     my $symb=&symbread($url);
 9390:     if (!$symb) { return; }
 9391:     my $key=$env{'request.course.id'}."\0".$symb;
 9392:     &devalidate_cache_new('title',$key);
 9393: }
 9394: 
 9395: # ------------------------------------------------- Get the title of a course
 9396: 
 9397: sub current_course_title {
 9398:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9399: }
 9400: # ------------------------------------------------- Get the title of a resource
 9401: 
 9402: sub gettitle {
 9403:     my $urlsymb=shift;
 9404:     my $symb=&symbread($urlsymb);
 9405:     if ($symb) {
 9406: 	my $key=$env{'request.course.id'}."\0".$symb;
 9407: 	my ($result,$cached)=&is_cached_new('title',$key);
 9408: 	if (defined($cached)) { 
 9409: 	    return $result;
 9410: 	}
 9411: 	my ($map,$resid,$url)=&decode_symb($symb);
 9412: 	my $title='';
 9413: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9414: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9415: 	} else {
 9416: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9417: 		    &GDBM_READER(),0640)) {
 9418: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9419: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9420: 		untie(%bighash);
 9421: 	    }
 9422: 	}
 9423: 	$title=~s/\&colon\;/\:/gs;
 9424: 	if ($title) {
 9425: # Remember both $symb and $title for dynamic metadata
 9426:             $accesshash{$symb.'___crstitle'}=$title;
 9427: # Cache this title and then return it
 9428: 	    return &do_cache_new('title',$key,$title,600);
 9429: 	}
 9430: 	$urlsymb=$url;
 9431:     }
 9432:     my $title=&metadata($urlsymb,'title');
 9433:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9434:     return $title;
 9435: }
 9436: 
 9437: sub get_slot {
 9438:     my ($which,$cnum,$cdom)=@_;
 9439:     if (!$cnum || !$cdom) {
 9440: 	(undef,my $courseid)=&whichuser();
 9441: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9442: 	$cnum=$env{'course.'.$courseid.'.num'};
 9443:     }
 9444:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9445:     my %slotinfo;
 9446:     if (exists($remembered{$key})) {
 9447: 	$slotinfo{$which} = $remembered{$key};
 9448:     } else {
 9449: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9450: 	&Apache::lonhomework::showhash(%slotinfo);
 9451: 	my ($tmp)=keys(%slotinfo);
 9452: 	if ($tmp=~/^error:/) { return (); }
 9453: 	$remembered{$key} = $slotinfo{$which};
 9454:     }
 9455:     if (ref($slotinfo{$which}) eq 'HASH') {
 9456: 	return %{$slotinfo{$which}};
 9457:     }
 9458:     return $slotinfo{$which};
 9459: }
 9460: 
 9461: sub get_reservable_slots {
 9462:     my ($cnum,$cdom,$uname,$udom) = @_;
 9463:     my $now = time;
 9464:     my $reservable_info;
 9465:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9466:     if (exists($remembered{$key})) {
 9467:         $reservable_info = $remembered{$key};
 9468:     } else {
 9469:         my %resv;
 9470:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9471:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9472:         $reservable_info = \%resv;
 9473:         $remembered{$key} = $reservable_info;
 9474:     }
 9475:     return $reservable_info;
 9476: }
 9477: 
 9478: sub get_course_slots {
 9479:     my ($cnum,$cdom) = @_;
 9480:     my $hashid=$cnum.':'.$cdom;
 9481:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9482:     if (defined($cached)) {
 9483:         if (ref($result) eq 'HASH') {
 9484:             return %{$result};
 9485:         }
 9486:     } else {
 9487:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9488:         my ($tmp) = keys(%slots);
 9489:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9490:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9491:             return %slots;
 9492:         }
 9493:     }
 9494:     return;
 9495: }
 9496: 
 9497: sub devalidate_slots_cache {
 9498:     my ($cnum,$cdom)=@_;
 9499:     my $hashid=$cnum.':'.$cdom;
 9500:     &devalidate_cache_new('allslots',$hashid);
 9501: }
 9502: 
 9503: # ------------------------------------------------- Update symbolic store links
 9504: 
 9505: sub symblist {
 9506:     my ($mapname,%newhash)=@_;
 9507:     $mapname=&deversion(&declutter($mapname));
 9508:     my %hash;
 9509:     if (($env{'request.course.fn'}) && (%newhash)) {
 9510:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9511:                       &GDBM_WRCREAT(),0640)) {
 9512: 	    foreach my $url (keys(%newhash)) {
 9513: 		next if ($url eq 'last_known'
 9514: 			 && $env{'form.no_update_last_known'});
 9515: 		$hash{declutter($url)}=&encode_symb($mapname,
 9516: 						    $newhash{$url}->[1],
 9517: 						    $newhash{$url}->[0]);
 9518:             }
 9519:             if (untie(%hash)) {
 9520: 		return 'ok';
 9521:             }
 9522:         }
 9523:     }
 9524:     return 'error';
 9525: }
 9526: 
 9527: # --------------------------------------------------------------- Verify a symb
 9528: 
 9529: sub symbverify {
 9530:     my ($symb,$thisurl)=@_;
 9531:     my $thisfn=$thisurl;
 9532:     $thisfn=&declutter($thisfn);
 9533: # direct jump to resource in page or to a sequence - will construct own symbs
 9534:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9535: # check URL part
 9536:     my ($map,$resid,$url)=&decode_symb($symb);
 9537: 
 9538:     unless ($url eq $thisfn) { return 0; }
 9539: 
 9540:     $symb=&symbclean($symb);
 9541:     $thisurl=&deversion($thisurl);
 9542:     $thisfn=&deversion($thisfn);
 9543: 
 9544:     my %bighash;
 9545:     my $okay=0;
 9546: 
 9547:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9548:                             &GDBM_READER(),0640)) {
 9549:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9550:             $thisurl =~ s/\?.+$//;
 9551:         }
 9552:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9553:         unless ($ids) {
 9554:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9555:             $ids=$bighash{$idkey};
 9556:         }
 9557:         if ($ids) {
 9558: # ------------------------------------------------------------------- Has ID(s)
 9559: 	    foreach my $id (split(/\,/,$ids)) {
 9560: 	       my ($mapid,$resid)=split(/\./,$id);
 9561:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9562:                    $symb =~ s/\?.+$//;
 9563:                }
 9564:                if (
 9565:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9566:    eq $symb) { 
 9567: 		   if (($env{'request.role.adv'}) ||
 9568: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9569:                        ($thisurl eq '/adm/navmaps')) {
 9570: 		       $okay=1; 
 9571: 		   }
 9572: 	       }
 9573: 	   }
 9574:         }
 9575: 	untie(%bighash);
 9576:     }
 9577:     return $okay;
 9578: }
 9579: 
 9580: # --------------------------------------------------------------- Clean-up symb
 9581: 
 9582: sub symbclean {
 9583:     my $symb=shift;
 9584:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9585: # remove version from map
 9586:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9587: 
 9588: # remove version from URL
 9589:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9590: 
 9591: # remove wrapper
 9592: 
 9593:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9594:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9595:     return $symb;
 9596: }
 9597: 
 9598: # ---------------------------------------------- Split symb to find map and url
 9599: 
 9600: sub encode_symb {
 9601:     my ($map,$resid,$url)=@_;
 9602:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9603: }
 9604: 
 9605: sub decode_symb {
 9606:     my $symb=shift;
 9607:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9608:     my ($map,$resid,$url)=split(/___/,$symb);
 9609:     return (&fixversion($map),$resid,&fixversion($url));
 9610: }
 9611: 
 9612: sub fixversion {
 9613:     my $fn=shift;
 9614:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9615:     my %bighash;
 9616:     my $uri=&clutter($fn);
 9617:     my $key=$env{'request.course.id'}.'_'.$uri;
 9618: # is this cached?
 9619:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9620:     if (defined($cached)) { return $result; }
 9621: # unfortunately not cached, or expired
 9622:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9623: 	    &GDBM_READER(),0640)) {
 9624:  	if ($bighash{'version_'.$uri}) {
 9625:  	    my $version=$bighash{'version_'.$uri};
 9626:  	    unless (($version eq 'mostrecent') || 
 9627: 		    ($version==&getversion($uri))) {
 9628:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9629:  	    }
 9630:  	}
 9631:  	untie %bighash;
 9632:     }
 9633:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9634: }
 9635: 
 9636: sub deversion {
 9637:     my $url=shift;
 9638:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9639:     return $url;
 9640: }
 9641: 
 9642: # ------------------------------------------------------ Return symb list entry
 9643: 
 9644: sub symbread {
 9645:     my ($thisfn,$donotrecurse)=@_;
 9646:     my $cache_str='request.symbread.cached.'.$thisfn;
 9647:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9648: # no filename provided? try from environment
 9649:     unless ($thisfn) {
 9650:         if ($env{'request.symb'}) {
 9651: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9652: 	}
 9653: 	$thisfn=$env{'request.filename'};
 9654:     }
 9655:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9656: # is that filename actually a symb? Verify, clean, and return
 9657:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9658: 	if (&symbverify($thisfn,$1)) {
 9659: 	    return $env{$cache_str}=&symbclean($thisfn);
 9660: 	}
 9661:     }
 9662:     $thisfn=declutter($thisfn);
 9663:     my %hash;
 9664:     my %bighash;
 9665:     my $syval='';
 9666:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9667:         my $targetfn = $thisfn;
 9668:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9669:             $targetfn = 'adm/wrapper/'.$thisfn;
 9670:         }
 9671: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9672: 	    $targetfn=$1;
 9673: 	}
 9674:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9675:                       &GDBM_READER(),0640)) {
 9676: 	    $syval=$hash{$targetfn};
 9677:             untie(%hash);
 9678:         }
 9679: # ---------------------------------------------------------- There was an entry
 9680:         if ($syval) {
 9681: 	    #unless ($syval=~/\_\d+$/) {
 9682: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9683: 		    #&appenv({'request.ambiguous' => $thisfn});
 9684: 		    #return $env{$cache_str}='';
 9685: 		#}    
 9686: 		#$syval.=$1;
 9687: 	    #}
 9688:         } else {
 9689: # ------------------------------------------------------- Was not in symb table
 9690:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9691:                             &GDBM_READER(),0640)) {
 9692: # ---------------------------------------------- Get ID(s) for current resource
 9693:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9694:               unless ($ids) { 
 9695:                  $ids=$bighash{'ids_/'.$thisfn};
 9696:               }
 9697:               unless ($ids) {
 9698: # alias?
 9699: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9700:               }
 9701:               if ($ids) {
 9702: # ------------------------------------------------------------------- Has ID(s)
 9703:                  my @possibilities=split(/\,/,$ids);
 9704:                  if ($#possibilities==0) {
 9705: # ----------------------------------------------- There is only one possibility
 9706: 		     my ($mapid,$resid)=split(/\./,$ids);
 9707: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9708: 						    $resid,$thisfn);
 9709:                  } elsif (!$donotrecurse) {
 9710: # ------------------------------------------ There is more than one possibility
 9711:                      my $realpossible=0;
 9712:                      foreach my $id (@possibilities) {
 9713: 			 my $file=$bighash{'src_'.$id};
 9714:                          if (&allowed('bre',$file)) {
 9715:          		    my ($mapid,$resid)=split(/\./,$id);
 9716:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 9717: 				$realpossible++;
 9718:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9719: 						    $resid,$thisfn);
 9720:                             }
 9721: 			 }
 9722:                      }
 9723: 		     if ($realpossible!=1) { $syval=''; }
 9724:                  } else {
 9725:                      $syval='';
 9726:                  }
 9727: 	      }
 9728:               untie(%bighash)
 9729:            }
 9730:         }
 9731:         if ($syval) {
 9732: 	    return $env{$cache_str}=$syval;
 9733:         }
 9734:     }
 9735:     &appenv({'request.ambiguous' => $thisfn});
 9736:     return $env{$cache_str}='';
 9737: }
 9738: 
 9739: # ---------------------------------------------------------- Return random seed
 9740: 
 9741: sub numval {
 9742:     my $txt=shift;
 9743:     $txt=~tr/A-J/0-9/;
 9744:     $txt=~tr/a-j/0-9/;
 9745:     $txt=~tr/K-T/0-9/;
 9746:     $txt=~tr/k-t/0-9/;
 9747:     $txt=~tr/U-Z/0-5/;
 9748:     $txt=~tr/u-z/0-5/;
 9749:     $txt=~s/\D//g;
 9750:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 9751:     return int($txt);
 9752: }
 9753: 
 9754: sub numval2 {
 9755:     my $txt=shift;
 9756:     $txt=~tr/A-J/0-9/;
 9757:     $txt=~tr/a-j/0-9/;
 9758:     $txt=~tr/K-T/0-9/;
 9759:     $txt=~tr/k-t/0-9/;
 9760:     $txt=~tr/U-Z/0-5/;
 9761:     $txt=~tr/u-z/0-5/;
 9762:     $txt=~s/\D//g;
 9763:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9764:     my $total;
 9765:     foreach my $val (@txts) { $total+=$val; }
 9766:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 9767:     return int($total);
 9768: }
 9769: 
 9770: sub numval3 {
 9771:     use integer;
 9772:     my $txt=shift;
 9773:     $txt=~tr/A-J/0-9/;
 9774:     $txt=~tr/a-j/0-9/;
 9775:     $txt=~tr/K-T/0-9/;
 9776:     $txt=~tr/k-t/0-9/;
 9777:     $txt=~tr/U-Z/0-5/;
 9778:     $txt=~tr/u-z/0-5/;
 9779:     $txt=~s/\D//g;
 9780:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9781:     my $total;
 9782:     foreach my $val (@txts) { $total+=$val; }
 9783:     if ($_64bit) { $total=(($total<<32)>>32); }
 9784:     return $total;
 9785: }
 9786: 
 9787: sub digest {
 9788:     my ($data)=@_;
 9789:     my $digest=&Digest::MD5::md5($data);
 9790:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 9791:     my ($e,$f);
 9792:     {
 9793:         use integer;
 9794:         $e=($a+$b);
 9795:         $f=($c+$d);
 9796:         if ($_64bit) {
 9797:             $e=(($e<<32)>>32);
 9798:             $f=(($f<<32)>>32);
 9799:         }
 9800:     }
 9801:     if (wantarray) {
 9802: 	return ($e,$f);
 9803:     } else {
 9804: 	my $g;
 9805: 	{
 9806: 	    use integer;
 9807: 	    $g=($e+$f);
 9808: 	    if ($_64bit) {
 9809: 		$g=(($g<<32)>>32);
 9810: 	    }
 9811: 	}
 9812: 	return $g;
 9813:     }
 9814: }
 9815: 
 9816: sub latest_rnd_algorithm_id {
 9817:     return '64bit5';
 9818: }
 9819: 
 9820: sub get_rand_alg {
 9821:     my ($courseid)=@_;
 9822:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9823:     if ($courseid) {
 9824: 	return $env{"course.$courseid.rndseed"};
 9825:     }
 9826:     return &latest_rnd_algorithm_id();
 9827: }
 9828: 
 9829: sub validCODE {
 9830:     my ($CODE)=@_;
 9831:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9832:     return 0;
 9833: }
 9834: 
 9835: sub getCODE {
 9836:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9837:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9838: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9839: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9840: 	return $Apache::lonhomework::history{'resource.CODE'};
 9841:     }
 9842:     return undef;
 9843: }
 9844: #
 9845: #  Determines the random seed for a specific context:
 9846: #
 9847: # parameters:
 9848: #   symb      - in course context the symb for the seed.
 9849: #   course_id - The course id of the form domain_coursenum.
 9850: #   domain    - Domain for the user.
 9851: #   course    - Course for the user.
 9852: #   cenv      - environment of the course.
 9853: #
 9854: # NOTE:
 9855: #   All parameters are picked out of the environment if missing
 9856: #   or not defined.
 9857: #   If a symb cannot be determined the current time is used instead.
 9858: #
 9859: #  For a given well defined symb, courside, domain, username,
 9860: #  and course environment, the seed is reproducible.
 9861: #
 9862: sub rndseed {
 9863:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
 9864:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9865:     if (!defined($symb)) {
 9866: 	unless ($symb=$wsymb) { return time; }
 9867:     }
 9868:     if (!defined $courseid) { 
 9869: 	$courseid=$wcourseid; 
 9870:     }
 9871:     if (!defined $domain) { $domain=$wdomain; }
 9872:     if (!defined $username) { $username=$wusername }
 9873: 
 9874:     my $which;
 9875:     if (defined($cenv->{'rndseed'})) {
 9876: 	$which = $cenv->{'rndseed'};
 9877:     } else {
 9878: 	$which =&get_rand_alg($courseid);
 9879:     }
 9880:     if (defined(&getCODE())) {
 9881: 
 9882: 	if ($which eq '64bit5') {
 9883: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9884: 	} elsif ($which eq '64bit4') {
 9885: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9886: 	} else {
 9887: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9888: 	}
 9889:     } elsif ($which eq '64bit5') {
 9890: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9891:     } elsif ($which eq '64bit4') {
 9892: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9893:     } elsif ($which eq '64bit3') {
 9894: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9895:     } elsif ($which eq '64bit2') {
 9896: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9897:     } elsif ($which eq '64bit') {
 9898: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9899:     }
 9900:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9901: }
 9902: 
 9903: sub rndseed_32bit {
 9904:     my ($symb,$courseid,$domain,$username)=@_;
 9905:     {
 9906: 	use integer;
 9907: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9908: 	my $symbseed=numval($symb) << 22;
 9909: 	my $namechck=unpack("%32C*",$username) << 17;
 9910: 	my $nameseed=numval($username) << 12;
 9911: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9912: 	my $courseseed=unpack("%32C*",$courseid);
 9913: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9914: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9915: 	#&logthis("rndseed :$num:$symb");
 9916: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9917: 	return $num;
 9918:     }
 9919: }
 9920: 
 9921: sub rndseed_64bit {
 9922:     my ($symb,$courseid,$domain,$username)=@_;
 9923:     {
 9924: 	use integer;
 9925: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9926: 	my $symbseed=numval($symb) << 10;
 9927: 	my $namechck=unpack("%32S*",$username);
 9928: 	
 9929: 	my $nameseed=numval($username) << 21;
 9930: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9931: 	my $courseseed=unpack("%32S*",$courseid);
 9932: 	
 9933: 	my $num1=$symbchck+$symbseed+$namechck;
 9934: 	my $num2=$nameseed+$domainseed+$courseseed;
 9935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9936: 	#&logthis("rndseed :$num:$symb");
 9937: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9938: 	return "$num1,$num2";
 9939:     }
 9940: }
 9941: 
 9942: sub rndseed_64bit2 {
 9943:     my ($symb,$courseid,$domain,$username)=@_;
 9944:     {
 9945: 	use integer;
 9946: 	# strings need to be an even # of cahracters long, it it is odd the
 9947:         # last characters gets thrown away
 9948: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9949: 	my $symbseed=numval($symb) << 10;
 9950: 	my $namechck=unpack("%32S*",$username.' ');
 9951: 	
 9952: 	my $nameseed=numval($username) << 21;
 9953: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9954: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9955: 	
 9956: 	my $num1=$symbchck+$symbseed+$namechck;
 9957: 	my $num2=$nameseed+$domainseed+$courseseed;
 9958: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9959: 	#&logthis("rndseed :$num:$symb");
 9960: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9961: 	return "$num1,$num2";
 9962:     }
 9963: }
 9964: 
 9965: sub rndseed_64bit3 {
 9966:     my ($symb,$courseid,$domain,$username)=@_;
 9967:     {
 9968: 	use integer;
 9969: 	# strings need to be an even # of cahracters long, it it is odd the
 9970:         # last characters gets thrown away
 9971: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9972: 	my $symbseed=numval2($symb) << 10;
 9973: 	my $namechck=unpack("%32S*",$username.' ');
 9974: 	
 9975: 	my $nameseed=numval2($username) << 21;
 9976: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9977: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9978: 	
 9979: 	my $num1=$symbchck+$symbseed+$namechck;
 9980: 	my $num2=$nameseed+$domainseed+$courseseed;
 9981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9982: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9983: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9984: 	
 9985: 	return "$num1:$num2";
 9986:     }
 9987: }
 9988: 
 9989: sub rndseed_64bit4 {
 9990:     my ($symb,$courseid,$domain,$username)=@_;
 9991:     {
 9992: 	use integer;
 9993: 	# strings need to be an even # of cahracters long, it it is odd the
 9994:         # last characters gets thrown away
 9995: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9996: 	my $symbseed=numval3($symb) << 10;
 9997: 	my $namechck=unpack("%32S*",$username.' ');
 9998: 	
 9999: 	my $nameseed=numval3($username) << 21;
10000: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10001: 	my $courseseed=unpack("%32S*",$courseid.' ');
10002: 	
10003: 	my $num1=$symbchck+$symbseed+$namechck;
10004: 	my $num2=$nameseed+$domainseed+$courseseed;
10005: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10006: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10007: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10008: 	
10009: 	return "$num1:$num2";
10010:     }
10011: }
10012: 
10013: sub rndseed_64bit5 {
10014:     my ($symb,$courseid,$domain,$username)=@_;
10015:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10016:     return "$num1:$num2";
10017: }
10018: 
10019: sub rndseed_CODE_64bit {
10020:     my ($symb,$courseid,$domain,$username)=@_;
10021:     {
10022: 	use integer;
10023: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10024: 	my $symbseed=numval2($symb);
10025: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10026: 	my $CODEseed=numval(&getCODE());
10027: 	my $courseseed=unpack("%32S*",$courseid.' ');
10028: 	my $num1=$symbseed+$CODEchck;
10029: 	my $num2=$CODEseed+$courseseed+$symbchck;
10030: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10031: 	#&logthis("rndseed :$num1:$num2:$symb");
10032: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10033: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10034: 	return "$num1:$num2";
10035:     }
10036: }
10037: 
10038: sub rndseed_CODE_64bit4 {
10039:     my ($symb,$courseid,$domain,$username)=@_;
10040:     {
10041: 	use integer;
10042: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10043: 	my $symbseed=numval3($symb);
10044: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10045: 	my $CODEseed=numval3(&getCODE());
10046: 	my $courseseed=unpack("%32S*",$courseid.' ');
10047: 	my $num1=$symbseed+$CODEchck;
10048: 	my $num2=$CODEseed+$courseseed+$symbchck;
10049: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10050: 	#&logthis("rndseed :$num1:$num2:$symb");
10051: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10052: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10053: 	return "$num1:$num2";
10054:     }
10055: }
10056: 
10057: sub rndseed_CODE_64bit5 {
10058:     my ($symb,$courseid,$domain,$username)=@_;
10059:     my $code = &getCODE();
10060:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10061:     return "$num1:$num2";
10062: }
10063: 
10064: sub setup_random_from_rndseed {
10065:     my ($rndseed)=@_;
10066:     if ($rndseed =~/([,:])/) {
10067: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10068: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10069:     } else {
10070: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10071:     }
10072: }
10073: 
10074: sub latest_receipt_algorithm_id {
10075:     return 'receipt3';
10076: }
10077: 
10078: sub recunique {
10079:     my $fucourseid=shift;
10080:     my $unique;
10081:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10082: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10083: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10084:     } else {
10085: 	$unique=$perlvar{'lonReceipt'};
10086:     }
10087:     return unpack("%32C*",$unique);
10088: }
10089: 
10090: sub recprefix {
10091:     my $fucourseid=shift;
10092:     my $prefix;
10093:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10094: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10095: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10096:     } else {
10097: 	$prefix=$perlvar{'lonHostID'};
10098:     }
10099:     return unpack("%32C*",$prefix);
10100: }
10101: 
10102: sub ireceipt {
10103:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10104: 
10105:     my $return =&recprefix($fucourseid).'-';
10106: 
10107:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10108: 	$env{'request.state'} eq 'construct') {
10109: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10110: 	return $return;
10111:     }
10112: 
10113:     my $cuname=unpack("%32C*",$funame);
10114:     my $cudom=unpack("%32C*",$fudom);
10115:     my $cucourseid=unpack("%32C*",$fucourseid);
10116:     my $cusymb=unpack("%32C*",$fusymb);
10117:     my $cunique=&recunique($fucourseid);
10118:     my $cpart=unpack("%32S*",$part);
10119:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10120: 
10121: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10122: 			       
10123: 	$return.= ($cunique%$cuname+
10124: 		   $cunique%$cudom+
10125: 		   $cusymb%$cuname+
10126: 		   $cusymb%$cudom+
10127: 		   $cucourseid%$cuname+
10128: 		   $cucourseid%$cudom+
10129: 		   $cpart%$cuname+
10130: 		   $cpart%$cudom);
10131:     } else {
10132: 	$return.= ($cunique%$cuname+
10133: 		   $cunique%$cudom+
10134: 		   $cusymb%$cuname+
10135: 		   $cusymb%$cudom+
10136: 		   $cucourseid%$cuname+
10137: 		   $cucourseid%$cudom);
10138:     }
10139:     return $return;
10140: }
10141: 
10142: sub receipt {
10143:     my ($part)=@_;
10144:     my ($symb,$courseid,$domain,$name) = &whichuser();
10145:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10146: }
10147: 
10148: sub whichuser {
10149:     my ($passedsymb)=@_;
10150:     my ($symb,$courseid,$domain,$name,$publicuser);
10151:     if (defined($env{'form.grade_symb'})) {
10152: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10153: 	my $allowed=&allowed('vgr',$tmp_courseid);
10154: 	if (!$allowed &&
10155: 	    exists($env{'request.course.sec'}) &&
10156: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10157: 	    $allowed=&allowed('vgr',$tmp_courseid.
10158: 			      '/'.$env{'request.course.sec'});
10159: 	}
10160: 	if ($allowed) {
10161: 	    ($symb)=&get_env_multiple('form.grade_symb');
10162: 	    $courseid=$tmp_courseid;
10163: 	    ($domain)=&get_env_multiple('form.grade_domain');
10164: 	    ($name)=&get_env_multiple('form.grade_username');
10165: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10166: 	}
10167:     }
10168:     if (!$passedsymb) {
10169: 	$symb=&symbread();
10170:     } else {
10171: 	$symb=$passedsymb;
10172:     }
10173:     $courseid=$env{'request.course.id'};
10174:     $domain=$env{'user.domain'};
10175:     $name=$env{'user.name'};
10176:     if ($name eq 'public' && $domain eq 'public') {
10177: 	if (!defined($env{'form.username'})) {
10178: 	    $env{'form.username'}.=time.rand(10000000);
10179: 	}
10180: 	$name.=$env{'form.username'};
10181:     }
10182:     return ($symb,$courseid,$domain,$name,$publicuser);
10183: 
10184: }
10185: 
10186: # ------------------------------------------------------------ Serves up a file
10187: # returns either the contents of the file or 
10188: # -1 if the file doesn't exist
10189: #
10190: # if the target is a file that was uploaded via DOCS, 
10191: # a check will be made to see if a current copy exists on the local server,
10192: # if it does this will be served, otherwise a copy will be retrieved from
10193: # the home server for the course and stored in /home/httpd/html/userfiles on
10194: # the local server.   
10195: 
10196: sub getfile {
10197:     my ($file) = @_;
10198:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10199:     &repcopy($file);
10200:     return &readfile($file);
10201: }
10202: 
10203: sub repcopy_userfile {
10204:     my ($file)=@_;
10205:     my $londocroot = $perlvar{'lonDocRoot'};
10206:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10207:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10208:     my ($cdom,$cnum,$filename) = 
10209: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10210:     my $uri="/uploaded/$cdom/$cnum/$filename";
10211:     if (-e "$file") {
10212: # we already have a local copy, check it out
10213: 	my @fileinfo = stat($file);
10214: 	my $rtncode;
10215: 	my $info;
10216: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10217: 	if ($lwpresp ne 'ok') {
10218: # there is no such file anymore, even though we had a local copy
10219: 	    if ($rtncode eq '404') {
10220: 		unlink($file);
10221: 	    }
10222: 	    return -1;
10223: 	}
10224: 	if ($info < $fileinfo[9]) {
10225: # nice, the file we have is up-to-date, just say okay
10226: 	    return 'ok';
10227: 	} else {
10228: # the file is outdated, get rid of it
10229: 	    unlink($file);
10230: 	}
10231:     }
10232: # one way or the other, at this point, we don't have the file
10233: # construct the correct path for the file
10234:     my @parts = ($cdom,$cnum); 
10235:     if ($filename =~ m|^(.+)/[^/]+$|) {
10236: 	push @parts, split(/\//,$1);
10237:     }
10238:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10239:     foreach my $part (@parts) {
10240: 	$path .= '/'.$part;
10241: 	if (!-e $path) {
10242: 	    mkdir($path,0770);
10243: 	}
10244:     }
10245: # now the path exists for sure
10246: # get a user agent
10247:     my $ua=new LWP::UserAgent;
10248:     my $transferfile=$file.'.in.transfer';
10249: # FIXME: this should flock
10250:     if (-e $transferfile) { return 'ok'; }
10251:     my $request;
10252:     $uri=~s/^\///;
10253:     my $homeserver = &homeserver($cnum,$cdom);
10254:     my $protocol = $protocol{$homeserver};
10255:     $protocol = 'http' if ($protocol ne 'https');
10256:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10257:     my $response=$ua->request($request,$transferfile);
10258: # did it work?
10259:     if ($response->is_error()) {
10260: 	unlink($transferfile);
10261: 	&logthis("Userfile repcopy failed for $uri");
10262: 	return -1;
10263:     }
10264: # worked, rename the transfer file
10265:     rename($transferfile,$file);
10266:     return 'ok';
10267: }
10268: 
10269: sub tokenwrapper {
10270:     my $uri=shift;
10271:     $uri=~s|^https?\://([^/]+)||;
10272:     $uri=~s|^/||;
10273:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10274:     my $token=$1;
10275:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10276:     if ($udom && $uname && $file) {
10277: 	$file=~s|(\?\.*)*$||;
10278:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10279:         my $homeserver = &homeserver($uname,$udom);
10280:         my $protocol = $protocol{$homeserver};
10281:         $protocol = 'http' if ($protocol ne 'https');
10282:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10283:                (($uri=~/\?/)?'&':'?').'token='.$token.
10284:                                '&tokenissued='.$perlvar{'lonHostID'};
10285:     } else {
10286:         return '/adm/notfound.html';
10287:     }
10288: }
10289: 
10290: # call with reqtype HEAD: get last modification time
10291: # call with reqtype GET: get the file contents
10292: # Do not call this with reqtype GET for large files! It loads everything into memory
10293: #
10294: sub getuploaded {
10295:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10296:     $uri=~s/^\///;
10297:     my $homeserver = &homeserver($cnum,$cdom);
10298:     my $protocol = $protocol{$homeserver};
10299:     $protocol = 'http' if ($protocol ne 'https');
10300:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10301:     my $ua=new LWP::UserAgent;
10302:     my $request=new HTTP::Request($reqtype,$uri);
10303:     my $response=$ua->request($request);
10304:     $$rtncode = $response->code;
10305:     if (! $response->is_success()) {
10306: 	return 'failed';
10307:     }      
10308:     if ($reqtype eq 'HEAD') {
10309: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10310:     } elsif ($reqtype eq 'GET') {
10311: 	$$info = $response->content;
10312:     }
10313:     return 'ok';
10314: }
10315: 
10316: sub readfile {
10317:     my $file = shift;
10318:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10319:     my $fh;
10320:     open($fh,"<$file");
10321:     my $a='';
10322:     while (my $line = <$fh>) { $a .= $line; }
10323:     return $a;
10324: }
10325: 
10326: sub filelocation {
10327:     my ($dir,$file) = @_;
10328:     my $location;
10329:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10330: 
10331:     if ($file =~ m-^/adm/-) {
10332: 	$file=~s-^/adm/wrapper/-/-;
10333: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10334:     }
10335: 
10336:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10337:         $location = $file;
10338:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10339:         my ($udom,$uname,$filename)=
10340:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10341:         my $home=&homeserver($uname,$udom);
10342:         my $is_me=0;
10343:         my @ids=&current_machine_ids();
10344:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10345:         if ($is_me) {
10346:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10347:         } else {
10348:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10349:   	      $udom.'/'.$uname.'/'.$filename;
10350:         }
10351:     } elsif ($file =~ m-^/adm/-) {
10352: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10353:     } else {
10354:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10355:         $file=~s:^/(res|priv)/:/:;
10356:         my $space=$1;
10357:         if ( !( $file =~ m:^/:) ) {
10358:             $location = $dir. '/'.$file;
10359:         } else {
10360:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10361:         }
10362:     }
10363:     $location=~s://+:/:g; # remove duplicate /
10364:     while ($location=~m{/\.\./}) {
10365: 	if ($location =~ m{/[^/]+/\.\./}) {
10366: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10367: 	} else {
10368: 	    $location=~ s{/\.\./}{/}g;
10369: 	}
10370:     } #remove dir/..
10371:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10372:     return $location;
10373: }
10374: 
10375: sub hreflocation {
10376:     my ($dir,$file)=@_;
10377:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10378: 	$file=filelocation($dir,$file);
10379:     } elsif ($file=~m-^/adm/-) {
10380: 	$file=~s-^/adm/wrapper/-/-;
10381: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10382:     }
10383:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10384: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10385:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10386: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10387: 	        {/uploaded/$1/$2/}x;
10388:     }
10389:     if ($file=~ m{^/userfiles/}) {
10390: 	$file =~ s{^/userfiles/}{/uploaded/};
10391:     }
10392:     return $file;
10393: }
10394: 
10395: 
10396: 
10397: 
10398: 
10399: sub current_machine_domains {
10400:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10401: }
10402: 
10403: sub machine_domains {
10404:     my ($hostname) = @_;
10405:     my @domains;
10406:     my %hostname = &all_hostnames();
10407:     while( my($id, $name) = each(%hostname)) {
10408: #	&logthis("-$id-$name-$hostname-");
10409: 	if ($hostname eq $name) {
10410: 	    push(@domains,&host_domain($id));
10411: 	}
10412:     }
10413:     return @domains;
10414: }
10415: 
10416: sub current_machine_ids {
10417:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10418: }
10419: 
10420: sub machine_ids {
10421:     my ($hostname) = @_;
10422:     $hostname ||= &hostname($perlvar{'lonHostID'});
10423:     my @ids;
10424:     my %name_to_host = &all_names();
10425:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10426: 	return @{ $name_to_host{$hostname} };
10427:     }
10428:     return;
10429: }
10430: 
10431: sub additional_machine_domains {
10432:     my @domains;
10433:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10434:     while( my $line = <$fh>) {
10435:         $line =~ s/\s//g;
10436:         push(@domains,$line);
10437:     }
10438:     return @domains;
10439: }
10440: 
10441: sub default_login_domain {
10442:     my $domain = $perlvar{'lonDefDomain'};
10443:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10444:     foreach my $posdom (&current_machine_domains(),
10445:                         &additional_machine_domains()) {
10446:         if (lc($posdom) eq lc($testdomain)) {
10447:             $domain=$posdom;
10448:             last;
10449:         }
10450:     }
10451:     return $domain;
10452: }
10453: 
10454: # ------------------------------------------------------------- Declutters URLs
10455: 
10456: sub declutter {
10457:     my $thisfn=shift;
10458:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10459:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10460:     $thisfn=~s/^\///;
10461:     $thisfn=~s|^adm/wrapper/||;
10462:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10463:     $thisfn=~s/^res\///;
10464:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10465:         $thisfn=~s/\?.+$//;
10466:     }
10467:     return $thisfn;
10468: }
10469: 
10470: # ------------------------------------------------------------- Clutter up URLs
10471: 
10472: sub clutter {
10473:     my $thisfn='/'.&declutter(shift);
10474:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10475: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10476:        $thisfn='/res'.$thisfn; 
10477:     }
10478:     if ($thisfn !~m|^/adm|) {
10479: 	if ($thisfn =~ m|^/ext/|) {
10480: 	    $thisfn='/adm/wrapper'.$thisfn;
10481: 	} else {
10482: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10483: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10484: 	    if ($embstyle eq 'ssi'
10485: 		|| ($embstyle eq 'hdn')
10486: 		|| ($embstyle eq 'rat')
10487: 		|| ($embstyle eq 'prv')
10488: 		|| ($embstyle eq 'ign')) {
10489: 		#do nothing with these
10490: 	    } elsif (($embstyle eq 'img') 
10491: 		|| ($embstyle eq 'emb')
10492: 		|| ($embstyle eq 'wrp')) {
10493: 		$thisfn='/adm/wrapper'.$thisfn;
10494: 	    } elsif ($embstyle eq 'unk'
10495: 		     && $thisfn!~/\.(sequence|page)$/) {
10496: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10497: 	    } else {
10498: #		&logthis("Got a blank emb style");
10499: 	    }
10500: 	}
10501:     }
10502:     return $thisfn;
10503: }
10504: 
10505: sub clutter_with_no_wrapper {
10506:     my $uri = &clutter(shift);
10507:     if ($uri =~ m-^/adm/-) {
10508: 	$uri =~ s-^/adm/wrapper/-/-;
10509: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10510:     }
10511:     return $uri;
10512: }
10513: 
10514: sub freeze_escape {
10515:     my ($value)=@_;
10516:     if (ref($value)) {
10517: 	$value=&nfreeze($value);
10518: 	return '__FROZEN__'.&escape($value);
10519:     }
10520:     return &escape($value);
10521: }
10522: 
10523: 
10524: sub thaw_unescape {
10525:     my ($value)=@_;
10526:     if ($value =~ /^__FROZEN__/) {
10527: 	substr($value,0,10,undef);
10528: 	$value=&unescape($value);
10529: 	return &thaw($value);
10530:     }
10531:     return &unescape($value);
10532: }
10533: 
10534: sub correct_line_ends {
10535:     my ($result)=@_;
10536:     $$result =~s/\r\n/\n/mg;
10537:     $$result =~s/\r/\n/mg;
10538: }
10539: # ================================================================ Main Program
10540: 
10541: sub goodbye {
10542:    &logthis("Starting Shut down");
10543: #not converted to using infrastruture and probably shouldn't be
10544:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10545: #converted
10546: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10547:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10548: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10549: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10550: #1.1 only
10551: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10552: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10553: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10554: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10555:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10556:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10557:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10558:    &flushcourselogs();
10559:    &logthis("Shutting down");
10560: }
10561: 
10562: sub get_dns {
10563:     my ($url,$func,$ignore_cache) = @_;
10564:     if (!$ignore_cache) {
10565: 	my ($content,$cached)=
10566: 	    &Apache::lonnet::is_cached_new('dns',$url);
10567: 	if ($cached) {
10568: 	    &$func($content);
10569: 	    return;
10570: 	}
10571:     }
10572: 
10573:     my %alldns;
10574:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10575:     foreach my $dns (<$config>) {
10576: 	next if ($dns !~ /^\^(\S*)/x);
10577:         my $line = $1;
10578:         my ($host,$protocol) = split(/:/,$line);
10579:         if ($protocol ne 'https') {
10580:             $protocol = 'http';
10581:         }
10582: 	$alldns{$host} = $protocol;
10583:     }
10584:     while (%alldns) {
10585: 	my ($dns) = keys(%alldns);
10586: 	my $ua=new LWP::UserAgent;
10587:         $ua->timeout(30);
10588: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10589: 	my $response=$ua->request($request);
10590:         delete($alldns{$dns});
10591: 	next if ($response->is_error());
10592: 	my @content = split("\n",$response->content);
10593: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10594: 	&$func(\@content);
10595: 	return;
10596:     }
10597:     close($config);
10598:     my $which = (split('/',$url))[3];
10599:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10600:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10601:     my @content = <$config>;
10602:     &$func(\@content);
10603:     return;
10604: }
10605: # ------------------------------------------------------------ Read domain file
10606: {
10607:     my $loaded;
10608:     my %domain;
10609: 
10610:     sub parse_domain_tab {
10611: 	my ($lines) = @_;
10612: 	foreach my $line (@$lines) {
10613: 	    next if ($line =~ /^(\#|\s*$ )/x);
10614: 
10615: 	    chomp($line);
10616: 	    my ($name,@elements) = split(/:/,$line,9);
10617: 	    my %this_domain;
10618: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10619: 			       'lang_def', 'city', 'longi', 'lati',
10620: 			       'primary') {
10621: 		$this_domain{$field} = shift(@elements);
10622: 	    }
10623: 	    $domain{$name} = \%this_domain;
10624: 	}
10625:     }
10626: 
10627:     sub reset_domain_info {
10628: 	undef($loaded);
10629: 	undef(%domain);
10630:     }
10631: 
10632:     sub load_domain_tab {
10633: 	my ($ignore_cache) = @_;
10634: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10635: 	my $fh;
10636: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10637: 	    my @lines = <$fh>;
10638: 	    &parse_domain_tab(\@lines);
10639: 	}
10640: 	close($fh);
10641: 	$loaded = 1;
10642:     }
10643: 
10644:     sub domain {
10645: 	&load_domain_tab() if (!$loaded);
10646: 
10647: 	my ($name,$what) = @_;
10648: 	return if ( !exists($domain{$name}) );
10649: 
10650: 	if (!$what) {
10651: 	    return $domain{$name}{'description'};
10652: 	}
10653: 	return $domain{$name}{$what};
10654:     }
10655: 
10656:     sub domain_info {
10657:         &load_domain_tab() if (!$loaded);
10658:         return %domain;
10659:     }
10660: 
10661: }
10662: 
10663: 
10664: # ------------------------------------------------------------- Read hosts file
10665: {
10666:     my %hostname;
10667:     my %hostdom;
10668:     my %libserv;
10669:     my $loaded;
10670:     my %name_to_host;
10671:     my %internetdom;
10672:     my %LC_dns_serv;
10673: 
10674:     sub parse_hosts_tab {
10675: 	my ($file) = @_;
10676: 	foreach my $configline (@$file) {
10677: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10678:             chomp($configline);
10679: 	    if ($configline =~ /^\^/) {
10680:                 if ($configline =~ /^\^([\w.\-]+)/) {
10681:                     $LC_dns_serv{$1} = 1;
10682:                 }
10683:                 next;
10684:             }
10685: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10686: 	    $name=~s/\s//g;
10687: 	    if ($id && $domain && $role && $name) {
10688: 		$hostname{$id}=$name;
10689: 		push(@{$name_to_host{$name}}, $id);
10690: 		$hostdom{$id}=$domain;
10691: 		if ($role eq 'library') { $libserv{$id}=$name; }
10692:                 if (defined($protocol)) {
10693:                     if ($protocol eq 'https') {
10694:                         $protocol{$id} = $protocol;
10695:                     } else {
10696:                         $protocol{$id} = 'http'; 
10697:                     }
10698:                 } else {
10699:                     $protocol{$id} = 'http';
10700:                 }
10701:                 if (defined($intdom)) {
10702:                     $internetdom{$id} = $intdom;
10703:                 }
10704: 	    }
10705: 	}
10706:     }
10707:     
10708:     sub reset_hosts_info {
10709: 	&purge_remembered();
10710: 	&reset_domain_info();
10711: 	&reset_hosts_ip_info();
10712: 	undef(%name_to_host);
10713: 	undef(%hostname);
10714: 	undef(%hostdom);
10715: 	undef(%libserv);
10716: 	undef($loaded);
10717:     }
10718: 
10719:     sub load_hosts_tab {
10720: 	my ($ignore_cache) = @_;
10721: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10722: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10723: 	my @config = <$config>;
10724: 	&parse_hosts_tab(\@config);
10725: 	close($config);
10726: 	$loaded=1;
10727:     }
10728: 
10729:     sub hostname {
10730: 	&load_hosts_tab() if (!$loaded);
10731: 
10732: 	my ($lonid) = @_;
10733: 	return $hostname{$lonid};
10734:     }
10735: 
10736:     sub all_hostnames {
10737: 	&load_hosts_tab() if (!$loaded);
10738: 
10739: 	return %hostname;
10740:     }
10741: 
10742:     sub all_names {
10743: 	&load_hosts_tab() if (!$loaded);
10744: 
10745: 	return %name_to_host;
10746:     }
10747: 
10748:     sub all_host_domain {
10749:         &load_hosts_tab() if (!$loaded);
10750:         return %hostdom;
10751:     }
10752: 
10753:     sub is_library {
10754: 	&load_hosts_tab() if (!$loaded);
10755: 
10756: 	return exists($libserv{$_[0]});
10757:     }
10758: 
10759:     sub all_library {
10760: 	&load_hosts_tab() if (!$loaded);
10761: 
10762: 	return %libserv;
10763:     }
10764: 
10765:     sub unique_library {
10766: 	#2x reverse removes all hostnames that appear more than once
10767:         my %unique = reverse &all_library();
10768:         return reverse %unique;
10769:     }
10770: 
10771:     sub get_servers {
10772: 	&load_hosts_tab() if (!$loaded);
10773: 
10774: 	my ($domain,$type) = @_;
10775: 	my %possible_hosts = ($type eq 'library') ? %libserv
10776: 	                                          : %hostname;
10777: 	my %result;
10778: 	if (ref($domain) eq 'ARRAY') {
10779: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10780: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10781: 		    $result{$host} = $hostname;
10782: 		}
10783: 	    }
10784: 	} else {
10785: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10786: 		if ($hostdom{$host} eq $domain) {
10787: 		    $result{$host} = $hostname;
10788: 		}
10789: 	    }
10790: 	}
10791: 	return %result;
10792:     }
10793: 
10794:     sub get_unique_servers {
10795:         my %unique = reverse &get_servers(@_);
10796: 	return reverse %unique;
10797:     }
10798: 
10799:     sub host_domain {
10800: 	&load_hosts_tab() if (!$loaded);
10801: 
10802: 	my ($lonid) = @_;
10803: 	return $hostdom{$lonid};
10804:     }
10805: 
10806:     sub all_domains {
10807: 	&load_hosts_tab() if (!$loaded);
10808: 
10809: 	my %seen;
10810: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
10811: 	return @uniq;
10812:     }
10813: 
10814:     sub internet_dom {
10815:         &load_hosts_tab() if (!$loaded);
10816: 
10817:         my ($lonid) = @_;
10818:         return $internetdom{$lonid};
10819:     }
10820: 
10821:     sub is_LC_dns {
10822:         &load_hosts_tab() if (!$loaded);
10823: 
10824:         my ($hostname) = @_;
10825:         return exists($LC_dns_serv{$hostname});
10826:     }
10827: 
10828: }
10829: 
10830: { 
10831:     my %iphost;
10832:     my %name_to_ip;
10833:     my %lonid_to_ip;
10834: 
10835:     sub get_hosts_from_ip {
10836: 	my ($ip) = @_;
10837: 	my %iphosts = &get_iphost();
10838: 	if (ref($iphosts{$ip})) {
10839: 	    return @{$iphosts{$ip}};
10840: 	}
10841: 	return;
10842:     }
10843:     
10844:     sub reset_hosts_ip_info {
10845: 	undef(%iphost);
10846: 	undef(%name_to_ip);
10847: 	undef(%lonid_to_ip);
10848:     }
10849: 
10850:     sub get_host_ip {
10851: 	my ($lonid) = @_;
10852: 	if (exists($lonid_to_ip{$lonid})) {
10853: 	    return $lonid_to_ip{$lonid};
10854: 	}
10855: 	my $name=&hostname($lonid);
10856:    	my $ip = gethostbyname($name);
10857: 	return if (!$ip || length($ip) ne 4);
10858: 	$ip=inet_ntoa($ip);
10859: 	$name_to_ip{$name}   = $ip;
10860: 	$lonid_to_ip{$lonid} = $ip;
10861: 	return $ip;
10862:     }
10863:     
10864:     sub get_iphost {
10865: 	my ($ignore_cache) = @_;
10866: 
10867: 	if (!$ignore_cache) {
10868: 	    if (%iphost) {
10869: 		return %iphost;
10870: 	    }
10871: 	    my ($ip_info,$cached)=
10872: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10873: 	    if ($cached) {
10874: 		%iphost      = %{$ip_info->[0]};
10875: 		%name_to_ip  = %{$ip_info->[1]};
10876: 		%lonid_to_ip = %{$ip_info->[2]};
10877: 		return %iphost;
10878: 	    }
10879: 	}
10880: 
10881: 	# get yesterday's info for fallback
10882: 	my %old_name_to_ip;
10883: 	my ($ip_info,$cached)=
10884: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10885: 	if ($cached) {
10886: 	    %old_name_to_ip = %{$ip_info->[1]};
10887: 	}
10888: 
10889: 	my %name_to_host = &all_names();
10890: 	foreach my $name (keys(%name_to_host)) {
10891: 	    my $ip;
10892: 	    if (!exists($name_to_ip{$name})) {
10893: 		$ip = gethostbyname($name);
10894: 		if (!$ip || length($ip) ne 4) {
10895: 		    if (defined($old_name_to_ip{$name})) {
10896: 			$ip = $old_name_to_ip{$name};
10897: 			&logthis("Can't find $name defaulting to old $ip");
10898: 		    } else {
10899: 			&logthis("Name $name no IP found");
10900: 			next;
10901: 		    }
10902: 		} else {
10903: 		    $ip=inet_ntoa($ip);
10904: 		}
10905: 		$name_to_ip{$name} = $ip;
10906: 	    } else {
10907: 		$ip = $name_to_ip{$name};
10908: 	    }
10909: 	    foreach my $id (@{ $name_to_host{$name} }) {
10910: 		$lonid_to_ip{$id} = $ip;
10911: 	    }
10912: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10913: 	}
10914: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10915: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10916: 				      48*60*60);
10917: 
10918: 	return %iphost;
10919:     }
10920: 
10921:     #
10922:     #  Given a DNS returns the loncapa host name for that DNS 
10923:     # 
10924:     sub host_from_dns {
10925:         my ($dns) = @_;
10926:         my @hosts;
10927:         my $ip;
10928: 
10929:         if (exists($name_to_ip{$dns})) {
10930:             $ip = $name_to_ip{$dns};
10931:         }
10932:         if (!$ip) {
10933:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10934:             if (length($ip) == 4) { 
10935: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10936:             }
10937:         }
10938:         if ($ip) {
10939: 	    @hosts = get_hosts_from_ip($ip);
10940: 	    return $hosts[0];
10941:         }
10942:         return undef;
10943:     }
10944: 
10945:     sub get_internet_names {
10946:         my ($lonid) = @_;
10947:         return if ($lonid eq '');
10948:         my ($idnref,$cached)=
10949:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10950:         if ($cached) {
10951:             return $idnref;
10952:         }
10953:         my $ip = &get_host_ip($lonid);
10954:         my @hosts = &get_hosts_from_ip($ip);
10955:         my %iphost = &get_iphost();
10956:         my (@idns,%seen);
10957:         foreach my $id (@hosts) {
10958:             my $dom = &host_domain($id);
10959:             my $prim_id = &domain($dom,'primary');
10960:             my $prim_ip = &get_host_ip($prim_id);
10961:             next if ($seen{$prim_ip});
10962:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10963:                 foreach my $id (@{$iphost{$prim_ip}}) {
10964:                     my $intdom = &internet_dom($id);
10965:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10966:                         push(@idns,$intdom);
10967:                     }
10968:                 }
10969:             }
10970:             $seen{$prim_ip} = 1;
10971:         }
10972:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10973:     }
10974: 
10975: }
10976: 
10977: sub all_loncaparevs {
10978:     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);
10979: }
10980: 
10981: BEGIN {
10982: 
10983: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10984:     unless ($readit) {
10985: {
10986:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10987:     %perlvar = (%perlvar,%{$configvars});
10988: }
10989: 
10990: 
10991: # ------------------------------------------------------ Read spare server file
10992: {
10993:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10994: 
10995:     while (my $configline=<$config>) {
10996:        chomp($configline);
10997:        if ($configline) {
10998: 	   my ($host,$type) = split(':',$configline,2);
10999: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11000: 	   push(@{ $spareid{$type} }, $host);
11001:        }
11002:     }
11003:     close($config);
11004: }
11005: # ------------------------------------------------------------ Read permissions
11006: {
11007:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11008: 
11009:     while (my $configline=<$config>) {
11010: 	chomp($configline);
11011: 	if ($configline) {
11012: 	    my ($role,$perm)=split(/ /,$configline);
11013: 	    if ($perm ne '') { $pr{$role}=$perm; }
11014: 	}
11015:     }
11016:     close($config);
11017: }
11018: 
11019: # -------------------------------------------- Read plain texts for permissions
11020: {
11021:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11022: 
11023:     while (my $configline=<$config>) {
11024: 	chomp($configline);
11025: 	if ($configline) {
11026: 	    my ($short,@plain)=split(/:/,$configline);
11027:             %{$prp{$short}} = ();
11028: 	    if (@plain > 0) {
11029:                 $prp{$short}{'std'} = $plain[0];
11030:                 for (my $i=1; $i<@plain; $i++) {
11031:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11032:                 }
11033:             }
11034: 	}
11035:     }
11036:     close($config);
11037: }
11038: 
11039: # ---------------------------------------------------------- Read package table
11040: {
11041:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11042: 
11043:     while (my $configline=<$config>) {
11044: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11045: 	chomp($configline);
11046: 	my ($short,$plain)=split(/:/,$configline);
11047: 	my ($pack,$name)=split(/\&/,$short);
11048: 	if ($plain ne '') {
11049: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11050: 	    $packagetab{$short}=$plain; 
11051: 	}
11052:     }
11053:     close($config);
11054: }
11055: 
11056: # ---------------------------------------------------------- Read loncaparev table
11057: {
11058:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11059:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11060:             while (my $configline=<$config>) {
11061:                 chomp($configline);
11062:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11063:                 $loncaparevs{$hostid}=$loncaparev;
11064:             }
11065:             close($config);
11066:         }
11067:     }
11068: }
11069: 
11070: # ---------------------------------------------------------- Read serverhostID table
11071: {
11072:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11073:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11074:             while (my $configline=<$config>) {
11075:                 chomp($configline);
11076:                 my ($name,$id)=split(/:/,$configline);
11077:                 $serverhomeIDs{$name}=$id;
11078:             }
11079:             close($config);
11080:         }
11081:     }
11082: }
11083: 
11084: {
11085:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11086:     if (-e $file) {
11087:         my $parser = HTML::LCParser->new($file);
11088:         while (my $token = $parser->get_token()) {
11089:             if ($token->[0] eq 'S') {
11090:                 my $item = $token->[1];
11091:                 my $name = $token->[2]{'name'};
11092:                 my $value = $token->[2]{'value'};
11093:                 if ($item ne '' && $name ne '' && $value ne '') {
11094:                     my $release = $parser->get_text();
11095:                     $release =~ s/(^\s*|\s*$ )//gx;
11096:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11097:                 }
11098:             }
11099:         }
11100:     }
11101: }
11102: 
11103: # ---------------------------------------------------------- Read managers table
11104: {
11105:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11106:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11107:             while (my $configline=<$config>) {
11108:                 chomp($configline);
11109:                 next if ($configline =~ /^\#/);
11110:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11111:                     $managerstab{$configline} = 1;
11112:                 }
11113:             }
11114:             close($config);
11115:         }
11116:     }
11117: }
11118: 
11119: # ------------- set up temporary directory
11120: {
11121:     $tmpdir = LONCAPA::tempdir();
11122: 
11123: }
11124: 
11125: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11126: 				'compress_threshold'=> 20_000,
11127:  			        });
11128: 
11129: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11130: $dumpcount=0;
11131: $locknum=0;
11132: 
11133: &logtouch();
11134: &logthis('<font color="yellow">INFO: Read configuration</font>');
11135: $readit=1;
11136:     {
11137: 	use integer;
11138: 	my $test=(2**32)+1;
11139: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11140: 	&logthis(" Detected 64bit platform ($_64bit)");
11141:     }
11142: }
11143: }
11144: 
11145: 1;
11146: __END__
11147: 
11148: =pod
11149: 
11150: =head1 NAME
11151: 
11152: Apache::lonnet - Subroutines to ask questions about things in the network.
11153: 
11154: =head1 SYNOPSIS
11155: 
11156: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11157: 
11158:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11159: 
11160: Common parameters:
11161: 
11162: =over 4
11163: 
11164: =item *
11165: 
11166: $uname : an internal username (if $cname expecting a course Id specifically)
11167: 
11168: =item *
11169: 
11170: $udom : a domain (if $cdom expecting a course's domain specifically)
11171: 
11172: =item *
11173: 
11174: $symb : a resource instance identifier
11175: 
11176: =item *
11177: 
11178: $namespace : the name of a .db file that contains the data needed or
11179: being set.
11180: 
11181: =back
11182: 
11183: =head1 OVERVIEW
11184: 
11185: lonnet provides subroutines which interact with the
11186: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11187: about classes, users, and resources.
11188: 
11189: For many of these objects you can also use this to store data about
11190: them or modify them in various ways.
11191: 
11192: =head2 Symbs
11193: 
11194: To identify a specific instance of a resource, LON-CAPA uses symbols
11195: or "symbs"X<symb>. These identifiers are built from the URL of the
11196: map, the resource number of the resource in the map, and the URL of
11197: the resource itself. The latter is somewhat redundant, but might help
11198: if maps change.
11199: 
11200: An example is
11201: 
11202:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11203: 
11204: The respective map entry is
11205: 
11206:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11207:   title="Problem 2">
11208:  </resource>
11209: 
11210: Symbs are used by the random number generator, as well as to store and
11211: restore data specific to a certain instance of for example a problem.
11212: 
11213: =head2 Storing And Retrieving Data
11214: 
11215: X<store()>X<cstore()>X<restore()>Three of the most important functions
11216: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11217: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11218: is is the non-critical message twin of cstore. These functions are for
11219: handlers to store a perl hash to a user's permanent data space in an
11220: easy manner, and to retrieve it again on another call. It is expected
11221: that a handler would use this once at the beginning to retrieve data,
11222: and then again once at the end to send only the new data back.
11223: 
11224: The data is stored in the user's data directory on the user's
11225: homeserver under the ID of the course.
11226: 
11227: The hash that is returned by restore will have all of the previous
11228: value for all of the elements of the hash.
11229: 
11230: Example:
11231: 
11232:  #creating a hash
11233:  my %hash;
11234:  $hash{'foo'}='bar';
11235: 
11236:  #storing it
11237:  &Apache::lonnet::cstore(\%hash);
11238: 
11239:  #changing a value
11240:  $hash{'foo'}='notbar';
11241: 
11242:  #adding a new value
11243:  $hash{'bar'}='foo';
11244:  &Apache::lonnet::cstore(\%hash);
11245: 
11246:  #retrieving the hash
11247:  my %history=&Apache::lonnet::restore();
11248: 
11249:  #print the hash
11250:  foreach my $key (sort(keys(%history))) {
11251:    print("\%history{$key} = $history{$key}");
11252:  }
11253: 
11254: Will print out:
11255: 
11256:  %history{1:foo} = bar
11257:  %history{1:keys} = foo:timestamp
11258:  %history{1:timestamp} = 990455579
11259:  %history{2:bar} = foo
11260:  %history{2:foo} = notbar
11261:  %history{2:keys} = foo:bar:timestamp
11262:  %history{2:timestamp} = 990455580
11263:  %history{bar} = foo
11264:  %history{foo} = notbar
11265:  %history{timestamp} = 990455580
11266:  %history{version} = 2
11267: 
11268: Note that the special hash entries C<keys>, C<version> and
11269: C<timestamp> were added to the hash. C<version> will be equal to the
11270: total number of versions of the data that have been stored. The
11271: C<timestamp> attribute will be the UNIX time the hash was
11272: stored. C<keys> is available in every historical section to list which
11273: keys were added or changed at a specific historical revision of a
11274: hash.
11275: 
11276: B<Warning>: do not store the hash that restore returns directly. This
11277: will cause a mess since it will restore the historical keys as if the
11278: were new keys. I.E. 1:foo will become 1:1:foo etc.
11279: 
11280: Calling convention:
11281: 
11282:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11283:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11284: 
11285: For more detailed information, see lonnet specific documentation.
11286: 
11287: =head1 RETURN MESSAGES
11288: 
11289: =over 4
11290: 
11291: =item * B<con_lost>: unable to contact remote host
11292: 
11293: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11294: when the connection is brought back up
11295: 
11296: =item * B<con_failed>: unable to contact remote host and unable to save message
11297: for later delivery
11298: 
11299: =item * B<error:>: an error a occurred, a description of the error follows the :
11300: 
11301: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11302: that was requested
11303: 
11304: =back
11305: 
11306: =head1 PUBLIC SUBROUTINES
11307: 
11308: =head2 Session Environment Functions
11309: 
11310: =over 4
11311: 
11312: =item * 
11313: X<appenv()>
11314: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11315: the user envirnoment file, and will be restored for each access this
11316: user makes during this session, also modifies the %env for the current
11317: process. Optional rolesarrayref - if defined contains a reference to an array
11318: of roles which are exempt from the restriction on modifying user.role entries 
11319: in the user's environment.db and in %env.    
11320: 
11321: =item *
11322: X<delenv()>
11323: B<delenv($delthis,$regexp)>: removes all items from the session
11324: environment file that begin with $delthis. If the 
11325: optional second arg - $regexp - is true, $delthis is treated as a 
11326: regular expression, otherwise \Q$delthis\E is used. 
11327: The values are also deleted from the current processes %env.
11328: 
11329: =item * get_env_multiple($name) 
11330: 
11331: gets $name from the %env hash, it seemlessly handles the cases where multiple
11332: values may be defined and end up as an array ref.
11333: 
11334: returns an array of values
11335: 
11336: =back
11337: 
11338: =head2 User Information
11339: 
11340: =over 4
11341: 
11342: =item *
11343: X<queryauthenticate()>
11344: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11345: authentication scheme
11346: 
11347: =item *
11348: X<authenticate()>
11349: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11350: authenticate user from domain's lib servers (first use the current
11351: one). C<$upass> should be the users password.
11352: $checkdefauth is optional (value is 1 if a check should be made to
11353:    authenticate user using default authentication method, and allow
11354:    account creation if username does not have account in the domain).
11355: $clientcancheckhost is optional (value is 1 if checking whether the
11356:    server can host will occur on the client side in lonauth.pm).   
11357: 
11358: =item *
11359: X<homeserver()>
11360: B<homeserver($uname,$udom)>: find the server which has
11361: the user's directory and files (there must be only one), this caches
11362: the answer, and also caches if there is a borken connection.
11363: 
11364: =item *
11365: X<idget()>
11366: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11367: (IDs are a unique resource in a domain, there must be only 1 ID per
11368: username, and only 1 username per ID in a specific domain) (returns
11369: hash: id=>name,id=>name)
11370: 
11371: =item *
11372: X<idrget()>
11373: B<idrget($udom,@unames)>: find the IDs behind a list of
11374: usernames (returns hash: name=>id,name=>id)
11375: 
11376: =item *
11377: X<idput()>
11378: B<idput($udom,%ids)>: store away a list of names and associated IDs
11379: 
11380: =item *
11381: X<rolesinit()>
11382: B<rolesinit($udom,$username,$authhost)>: get user privileges
11383: 
11384: =item *
11385: X<getsection()>
11386: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11387: course $cname, return section name/number or '' for "not in course"
11388: and '-1' for "no section"
11389: 
11390: =item *
11391: X<userenvironment()>
11392: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11393: passed in @what from the requested user's environment, returns a hash
11394: 
11395: =item * 
11396: X<userlog_query()>
11397: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11398: activity.log file. %filters defines filters applied when parsing the
11399: log file. These can be start or end timestamps, or the type of action
11400: - log to look for Login or Logout events, check for Checkin or
11401: Checkout, role for role selection. The response is in the form
11402: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11403: escaped strings of the action recorded in the activity.log file.
11404: 
11405: =back
11406: 
11407: =head2 User Roles
11408: 
11409: =over 4
11410: 
11411: =item *
11412: 
11413: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11414:  F: full access
11415:  U,I,K: authentication modes (cxx only)
11416:  '': forbidden
11417:  1: user needs to choose course
11418:  2: browse allowed
11419:  A: passphrase authentication needed
11420: 
11421: =item *
11422: 
11423: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11424: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11425: and course level
11426: 
11427: =item *
11428: 
11429: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11430: (rolesplain.tab); plain text explanation of a user role term.
11431: $type is Course (default) or Community.
11432: If $forcedefault evaluates to true, text returned will be default 
11433: text for $type. Otherwise, if this is a course, the text returned 
11434: will be a custom name for the role (if defined in the course's 
11435: environment).  If no custom name is defined the default is returned.
11436:    
11437: =item *
11438: 
11439: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11440: All arguments are optional. Returns a hash of a roles, either for
11441: co-author/assistant author roles for a user's Construction Space
11442: (default), or if $context is 'userroles', roles for the user himself,
11443: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11444: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11445: For each key, value is set to colon-separated start and end times for
11446: the role.  If no username and domain are specified, will default to
11447: current user/domain. Types, roles, and roledoms are references to arrays
11448: of role statuses (active, future or previous), roles 
11449: (e.g., cc,in, st etc.) and domains of the roles which can be used
11450: to restrict the list of roles reported. If no array ref is 
11451: provided for types, will default to return only active roles.
11452: 
11453: =back
11454: 
11455: =head2 User Modification
11456: 
11457: =over 4
11458: 
11459: =item *
11460: 
11461: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11462: user for the level given by URL.  Optional start and end dates (leave empty
11463: string or zero for "no date")
11464: 
11465: =item *
11466: 
11467: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11468: change a users, password, possible return values are: ok,
11469: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11470: refused
11471: 
11472: =item *
11473: 
11474: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11475: 
11476: =item *
11477: 
11478: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11479:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11480: 
11481: will update user information (firstname,middlename,lastname,generation,
11482: permanentemail), and if forceid is true, student/employee ID also.
11483: A user's institutional affiliation(s) can also be updated.
11484: User information fields will not be overwritten with empty entries 
11485: unless the field is included in the $candelete array reference.
11486: This array is included when a single user is modified via "Manage Users",
11487: or when Autoupdate.pl is run by cron in a domain.
11488: 
11489: =item *
11490: 
11491: modifystudent
11492: 
11493: modify a student's enrollment and identification information.
11494: The course id is resolved based on the current users environment.  
11495: This means the envoking user must be a course coordinator or otherwise
11496: associated with a course.
11497: 
11498: This call is essentially a wrapper for lonnet::modifyuser and
11499: lonnet::modify_student_enrollment
11500: 
11501: Inputs: 
11502: 
11503: =over 4
11504: 
11505: =item B<$udom> Student's loncapa domain
11506: 
11507: =item B<$uname> Student's loncapa login name
11508: 
11509: =item B<$uid> Student/Employee ID
11510: 
11511: =item B<$umode> Student's authentication mode
11512: 
11513: =item B<$upass> Student's password
11514: 
11515: =item B<$first> Student's first name
11516: 
11517: =item B<$middle> Student's middle name
11518: 
11519: =item B<$last> Student's last name
11520: 
11521: =item B<$gene> Student's generation
11522: 
11523: =item B<$usec> Student's section in course
11524: 
11525: =item B<$end> Unix time of the roles expiration
11526: 
11527: =item B<$start> Unix time of the roles start date
11528: 
11529: =item B<$forceid> If defined, allow $uid to be changed
11530: 
11531: =item B<$desiredhome> server to use as home server for student
11532: 
11533: =item B<$email> Student's permanent e-mail address
11534: 
11535: =item B<$type> Type of enrollment (auto or manual)
11536: 
11537: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11538: 
11539: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11540: 
11541: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11542: 
11543: =item B<$context> role change context (shown in User Management Logs display in a course)
11544: 
11545: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11546: 
11547: =back
11548: 
11549: =item *
11550: 
11551: modify_student_enrollment
11552: 
11553: Change a students enrollment status in a class.  The environment variable
11554: 'role.request.course' must be defined for this function to proceed.
11555: 
11556: Inputs:
11557: 
11558: =over 4
11559: 
11560: =item $udom, students domain
11561: 
11562: =item $uname, students name
11563: 
11564: =item $uid, students user id
11565: 
11566: =item $first, students first name
11567: 
11568: =item $middle
11569: 
11570: =item $last
11571: 
11572: =item $gene
11573: 
11574: =item $usec
11575: 
11576: =item $end
11577: 
11578: =item $start
11579: 
11580: =item $type
11581: 
11582: =item $locktype
11583: 
11584: =item $cid
11585: 
11586: =item $selfenroll
11587: 
11588: =item $context
11589: 
11590: =back
11591: 
11592: 
11593: =item *
11594: 
11595: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11596: custom role; give a custom role to a user for the level given by URL.  Specify
11597: name and domain of role author, and role name
11598: 
11599: =item *
11600: 
11601: revokerole($udom,$uname,$url,$role) : revoke a role for url
11602: 
11603: =item *
11604: 
11605: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11606: 
11607: =back
11608: 
11609: =head2 Course Infomation
11610: 
11611: =over 4
11612: 
11613: =item *
11614: 
11615: coursedescription($courseid,$options) : returns a hash of information about the
11616: specified course id, including all environment settings for the
11617: course, the description of the course will be in the hash under the
11618: key 'description'
11619: 
11620: $options is an optional parameter that if supplied is a hash reference that controls
11621: what how this function works.  It has the following key/values:
11622: 
11623: =over 4
11624: 
11625: =item freshen_cache
11626: 
11627: If defined, and the environment cache for the course is valid, it is 
11628: returned in the returned hash.
11629: 
11630: =item one_time
11631: 
11632: If defined, the last cache time is set to _now_
11633: 
11634: =item user
11635: 
11636: If defined, the supplied username is used instead of the current user.
11637: 
11638: 
11639: =back
11640: 
11641: =item *
11642: 
11643: resdata($name,$domain,$type,@which) : request for current parameter
11644: setting for a specific $type, where $type is either 'course' or 'user',
11645: @what should be a list of parameters to ask about. This routine caches
11646: answers for 5 minutes.
11647: 
11648: =item *
11649: 
11650: get_courseresdata($courseid, $domain) : dump the entire course resource
11651: data base, returning a hash that is keyed by the resource name and has
11652: values that are the resource value.  I believe that the timestamps and
11653: versions are also returned.
11654: 
11655: 
11656: =back
11657: 
11658: =head2 Course Modification
11659: 
11660: =over 4
11661: 
11662: =item *
11663: 
11664: writecoursepref($courseid,%prefs) : write preferences (environment
11665: database) for a course
11666: 
11667: =item *
11668: 
11669: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11670: 
11671: =item *
11672: 
11673: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11674: 
11675: =back
11676: 
11677: =head2 Resource Subroutines
11678: 
11679: =over 4
11680: 
11681: =item *
11682: 
11683: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11684: 
11685: =item *
11686: 
11687: repcopy($filename) : subscribes to the requested file, and attempts to
11688: replicate from the owning library server, Might return
11689: 'unavailable', 'not_found', 'forbidden', 'ok', or
11690: 'bad_request', also attempts to grab the metadata for the
11691: resource. Expects the local filesystem pathname
11692: (/home/httpd/html/res/....)
11693: 
11694: =back
11695: 
11696: =head2 Resource Information
11697: 
11698: =over 4
11699: 
11700: =item *
11701: 
11702: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11703: a vairety of different possible values, $varname should be a request
11704: string, and the other parameters can be used to specify who and what
11705: one is asking about.
11706: 
11707: Possible values for $varname are environment.lastname (or other item
11708: from the envirnment hash), user.name (or someother aspect about the
11709: user), resource.0.maxtries (or some other part and parameter of a
11710: resource)
11711: 
11712: =item *
11713: 
11714: directcondval($number) : get current value of a condition; reads from a state
11715: string
11716: 
11717: =item *
11718: 
11719: condval($condidx) : value of condition index based on state
11720: 
11721: =item *
11722: 
11723: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11724: resource's metadata, $what should be either a specific key, or either
11725: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11726: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11727: 
11728: this function automatically caches all requests
11729: 
11730: =item *
11731: 
11732: metadata_query($query,$custom,$customshow) : make a metadata query against the
11733: network of library servers; returns file handle of where SQL and regex results
11734: will be stored for query
11735: 
11736: =item *
11737: 
11738: symbread($filename) : return symbolic list entry (filename argument optional);
11739: returns the data handle
11740: 
11741: =item *
11742: 
11743: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11744: a possible symb for the URL in $thisfn, and if is an encryypted
11745: resource that the user accessed using /enc/ returns a 1 on success, 0
11746: on failure, user must be in a course, as it assumes the existance of
11747: the course initial hash, and uses $env('request.course.id'}
11748: 
11749: 
11750: =item *
11751: 
11752: symbclean($symb) : removes versions numbers from a symb, returns the
11753: cleaned symb
11754: 
11755: =item *
11756: 
11757: is_on_map($uri) : checks if the $uri is somewhere on the current
11758: course map, user must be in a course for it to work.
11759: 
11760: =item *
11761: 
11762: numval($salt) : return random seed value (addend for rndseed)
11763: 
11764: =item *
11765: 
11766: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11767: a random seed, all arguments are optional, if they aren't sent it uses the
11768: environment to derive them. Note: if symb isn't sent and it can't get one
11769: from &symbread it will use the current time as its return value
11770: 
11771: =item *
11772: 
11773: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11774: unfakeable, receipt
11775: 
11776: =item *
11777: 
11778: receipt() : API to ireceipt working off of env values; given out to users
11779: 
11780: =item *
11781: 
11782: countacc($url) : count the number of accesses to a given URL
11783: 
11784: =item *
11785: 
11786: 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
11787: 
11788: =item *
11789: 
11790: 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)
11791: 
11792: =item *
11793: 
11794: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11795: 
11796: =item *
11797: 
11798: devalidate($symb) : devalidate temporary spreadsheet calculations,
11799: forcing spreadsheet to reevaluate the resource scores next time.
11800: 
11801: =back
11802: 
11803: =head2 Storing/Retreiving Data
11804: 
11805: =over 4
11806: 
11807: =item *
11808: 
11809: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11810: for this url; hashref needs to be given and should be a \%hashname; the
11811: remaining args aren't required and if they aren't passed or are '' they will
11812: be derived from the env
11813: 
11814: =item *
11815: 
11816: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11817: uses critical subroutine
11818: 
11819: =item *
11820: 
11821: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11822: all args are optional
11823: 
11824: =item *
11825: 
11826: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
11827: dumps the complete (or key matching regexp) namespace into a hash
11828: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11829: normally &store()ed into
11830: 
11831: $range should be either an integer '100' (give me the first 100
11832:                                            matching records)
11833:               or be  two integers sperated by a - with no spaces
11834:                  '30-50' (give me the 30th through the 50th matching
11835:                           records)
11836: 
11837: 
11838: =item *
11839: 
11840: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11841: replaces a &store() version of data with a replacement set of data
11842: for a particular resource in a namespace passed in the $storehash hash 
11843: reference
11844: 
11845: =item *
11846: 
11847: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11848: works very similar to store/cstore, but all data is stored in a
11849: temporary location and can be reset using tmpreset, $storehash should
11850: be a hash reference, returns nothing on success
11851: 
11852: =item *
11853: 
11854: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11855: similar to restore, but all data is stored in a temporary location and
11856: can be reset using tmpreset. Returns a hash of values on success,
11857: error string otherwise.
11858: 
11859: =item *
11860: 
11861: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11862: deltes all keys for $symb form the temporary storage hash.
11863: 
11864: =item *
11865: 
11866: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11867: reference filled in from namesp ($udom and $uname are optional)
11868: 
11869: =item *
11870: 
11871: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11872: namesp ($udom and $uname are optional)
11873: 
11874: =item *
11875: 
11876: dump($namespace,$udom,$uname,$regexp,$range) : 
11877: dumps the complete (or key matching regexp) namespace into a hash
11878: ($udom, $uname, $regexp, $range are optional)
11879: 
11880: $range should be either an integer '100' (give me the first 100
11881:                                            matching records)
11882:               or be  two integers sperated by a - with no spaces
11883:                  '30-50' (give me the 30th through the 50th matching
11884:                           records)
11885: =item *
11886: 
11887: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11888: $store can be a scalar, an array reference, or if the amount to be 
11889: incremented is > 1, a hash reference.
11890: 
11891: ($udom and $uname are optional)
11892: 
11893: =item *
11894: 
11895: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11896: ($udom and $uname are optional)
11897: 
11898: =item *
11899: 
11900: cput($namespace,$storehash,$udom,$uname) : critical put
11901: ($udom and $uname are optional)
11902: 
11903: =item *
11904: 
11905: newput($namespace,$storehash,$udom,$uname) :
11906: 
11907: Attempts to store the items in the $storehash, but only if they don't
11908: currently exist, if this succeeds you can be certain that you have 
11909: successfully created a new key value pair in the $namespace db.
11910: 
11911: 
11912: Args:
11913:  $namespace: name of database to store values to
11914:  $storehash: hashref to store to the db
11915:  $udom: (optional) domain of user containing the db
11916:  $uname: (optional) name of user caontaining the db
11917: 
11918: Returns:
11919:  'ok' -> succeeded in storing all keys of $storehash
11920:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11921:                         least <key> already existed in the db (other
11922:                         requested keys may also already exist)
11923:  'error: <msg>' -> unable to tie the DB or other error occurred
11924:  'con_lost' -> unable to contact request server
11925:  'refused' -> action was not allowed by remote machine
11926: 
11927: 
11928: =item *
11929: 
11930: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11931: reference filled in from namesp (encrypts the return communication)
11932: ($udom and $uname are optional)
11933: 
11934: =item *
11935: 
11936: log($udom,$name,$home,$message) : write to permanent log for user; use
11937: critical subroutine
11938: 
11939: =item *
11940: 
11941: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11942: array reference filled in from namespace found in domain level on either
11943: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11944: 
11945: =item *
11946: 
11947: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11948: domain level either on specified domain server ($uhome) or primary domain 
11949: server ($udom and $uhome are optional)
11950: 
11951: =item * 
11952: 
11953: get_domain_defaults($target_domain) : returns hash with defaults for
11954: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11955: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11956: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11957: Values are retrieved from cache (if current), or from domain's configuration.db
11958: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11959: or lonTabs/domain.tab. 
11960: 
11961: %domdefaults = &get_auth_defaults($target_domain);
11962: 
11963: =back
11964: 
11965: =head2 Network Status Functions
11966: 
11967: =over 4
11968: 
11969: =item *
11970: 
11971: dirlist() : return directory list based on URI (first arg).
11972: 
11973: Inputs: 1 required, 5 optional.
11974: 
11975: =over
11976: 
11977: =item 
11978: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11979: 
11980: =item
11981: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
11982: 
11983: =item
11984: $username -  username of user/course to be listed. Extracted from $uri if absent. 
11985: 
11986: =item
11987: $getpropath - boolean: 1 if prepend path using &propath(). 
11988: 
11989: =item
11990: $getuserdir - boolean: 1 if prepend path for "userfiles".
11991: 
11992: =item 
11993: $alternateRoot - path to prepend in place of path from $uri.
11994: 
11995: =back
11996: 
11997: Returns: Array of up to two items.
11998: 
11999: =over
12000: 
12001: a reference to an array of files/subdirectories
12002: 
12003: =over
12004: 
12005: Each element in the array of files/subdirectories is a & separated list of
12006: item name and the result of running stat on the item.  If dirlist was requested
12007: for a file instead of a directory, the item name will be ''. For a directory 
12008: listing, if the item is a metadata file, the element will end &N&M 
12009: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12010: default copyright set (1).  
12011: 
12012: =back
12013: 
12014: a scalar containing error condition (if encountered).
12015: 
12016: =over
12017: 
12018: =item 
12019: no_host (no homeserver identified for $username:$domain).
12020: 
12021: =item 
12022: no_such_host (server contacted for listing not identified as valid host).
12023: 
12024: =item 
12025: con_lost (connection to remote server failed).
12026: 
12027: =item 
12028: refused (invalid $username:$domain received on lond side).
12029: 
12030: =item 
12031: no_such_dir (directory at specified path on lond side does not exist). 
12032: 
12033: =item 
12034: empty (directory at specified path on lond side is empty).
12035: 
12036: =over
12037: 
12038: This is currently not encountered because the &ls3, &ls2, 
12039: &ls (_handler) routines on the lond side do not filter out
12040: . and .. from a directory listing. 
12041: 
12042: =back
12043: 
12044: =back
12045: 
12046: =back
12047: 
12048: =item *
12049: 
12050: spareserver() : find server with least workload from spare.tab
12051: 
12052: 
12053: =item *
12054: 
12055: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12056: if there is no corresponding loncapa host.
12057: 
12058: =back
12059: 
12060: 
12061: =head2 Apache Request
12062: 
12063: =over 4
12064: 
12065: =item *
12066: 
12067: ssi($url,%hash) : server side include, does a complete request cycle on url to
12068: localhost, posts hash
12069: 
12070: =back
12071: 
12072: =head2 Data to String to Data
12073: 
12074: =over 4
12075: 
12076: =item *
12077: 
12078: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12079: and '&' separators, supports elements that are arrayrefs and hashrefs
12080: 
12081: =item *
12082: 
12083: hashref2str($hashref) : convert a hashref into a string complete with
12084: escaping and '=' and '&' separators, supports elements that are
12085: arrayrefs and hashrefs
12086: 
12087: =item *
12088: 
12089: arrayref2str($arrayref) : convert an arrayref into a string complete
12090: with escaping and '&' separators, supports elements that are arrayrefs
12091: and hashrefs
12092: 
12093: =item *
12094: 
12095: str2hash($string) : convert string to hash using unescaping and
12096: splitting on '=' and '&', supports elements that are arrayrefs and
12097: hashrefs
12098: 
12099: =item *
12100: 
12101: str2array($string) : convert string to hash using unescaping and
12102: splitting on '&', supports elements that are arrayrefs and hashrefs
12103: 
12104: =back
12105: 
12106: =head2 Logging Routines
12107: 
12108: 
12109: These routines allow one to make log messages in the lonnet.log and
12110: lonnet.perm logfiles.
12111: 
12112: =over 4
12113: 
12114: =item *
12115: 
12116: logtouch() : make sure the logfile, lonnet.log, exists
12117: 
12118: =item *
12119: 
12120: logthis() : append message to the normal lonnet.log file, it gets
12121: preiodically rolled over and deleted.
12122: 
12123: =item *
12124: 
12125: logperm() : append a permanent message to lonnet.perm.log, this log
12126: file never gets deleted by any automated portion of the system, only
12127: messages of critical importance should go in here.
12128: 
12129: 
12130: =back
12131: 
12132: =head2 General File Helper Routines
12133: 
12134: =over 4
12135: 
12136: =item *
12137: 
12138: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12139: (a) files in /uploaded
12140:   (i) If a local copy of the file exists - 
12141:       compares modification date of local copy with last-modified date for 
12142:       definitive version stored on home server for course. If local copy is 
12143:       stale, requests a new version from the home server and stores it. 
12144:       If the original has been removed from the home server, then local copy 
12145:       is unlinked.
12146:   (ii) If local copy does not exist -
12147:       requests the file from the home server and stores it. 
12148:   
12149:   If $caller is 'uploadrep':  
12150:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12151:     for request for files originally uploaded via DOCS. 
12152:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12153:   
12154:   Otherwise:
12155:      This indicates a call from the content generation phase of the request.
12156:      -  returns the entire contents of the file or -1.
12157:      
12158: (b) files in /res
12159:    - returns the entire contents of a file or -1; 
12160:    it properly subscribes to and replicates the file if neccessary.
12161: 
12162: 
12163: =item *
12164: 
12165: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12166:                   reference
12167: 
12168: returns either a stat() list of data about the file or an empty list
12169: if the file doesn't exist or couldn't find out about it (connection
12170: problems or user unknown)
12171: 
12172: =item *
12173: 
12174: filelocation($dir,$file) : returns file system location of a file
12175: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12176: directory that relative $file lookups are to looked in ($dir of /a/dir
12177: and a file of ../bob will become /a/bob)
12178: 
12179: =item *
12180: 
12181: hreflocation($dir,$file) : returns file system location or a URL; same as
12182: filelocation except for hrefs
12183: 
12184: =item *
12185: 
12186: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12187: 
12188: =back
12189: 
12190: =head2 Usererfile file routines (/uploaded*)
12191: 
12192: =over 4
12193: 
12194: =item *
12195: 
12196: userfileupload(): main rotine for putting a file in a user or course's
12197:                   filespace, arguments are,
12198: 
12199:  formname - required - this is the name of the element in $env where the
12200:            filename, and the contents of the file to create/modifed exist
12201:            the filename is in $env{'form.'.$formname.'.filename'} and the
12202:            contents of the file is located in $env{'form.'.$formname}
12203:  context - if coursedoc, store the file in the course of the active role
12204:              of the current user; 
12205:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12206:            if 'canceloverwrite': delete file in tmp/overwrites directory
12207:  subdir - required - subdirectory to put the file in under ../userfiles/
12208:          if undefined, it will be placed in "unknown"
12209: 
12210:  (This routine calls clean_filename() to remove any dangerous
12211:  characters from the filename, and then calls finuserfileupload() to
12212:  complete the transaction)
12213: 
12214:  returns either the url of the uploaded file (/uploaded/....) if successful
12215:  and /adm/notfound.html if unsuccessful
12216: 
12217: =item *
12218: 
12219: clean_filename(): routine for cleaing a filename up for storage in
12220:                  userfile space, argument is:
12221: 
12222:  filename - proposed filename
12223: 
12224: returns: the new clean filename
12225: 
12226: =item *
12227: 
12228: finishuserfileupload(): routine that creates and sends the file to
12229: userspace, probably shouldn't be called directly
12230: 
12231:   docuname: username or courseid of destination for the file
12232:   docudom: domain of user/course of destination for the file
12233:   formname: same as for userfileupload()
12234:   fname: filename (including subdirectories) for the file
12235:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12236:   allfiles: reference to hash used to store objects found by parser
12237:   codebase: reference to hash used for codebases of java objects found by parser
12238:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12239:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12240:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12241:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12242:   context: if 'overwrite', will move the uploaded file from its temporary location to
12243:             userfiles to facilitate overwriting a previously uploaded file with same name.
12244:   mimetype: reference to scalar to accommodate mime type determined
12245:             from File::MMagic if $parser = parse.
12246: 
12247:  returns either the url of the uploaded file (/uploaded/....) if successful
12248:  and /adm/notfound.html if unsuccessful (or an error message if context 
12249:  was 'overwrite').
12250:  
12251: 
12252: =item *
12253: 
12254: renameuserfile(): renames an existing userfile to a new name
12255: 
12256:   Args:
12257:    docuname: username or courseid of destination for the file
12258:    docudom: domain of user/course of destination for the file
12259:    old: current file name (including any subdirs under userfiles)
12260:    new: desired file name (including any subdirs under userfiles)
12261: 
12262: =item *
12263: 
12264: mkdiruserfile(): creates a directory is a userfiles dir
12265: 
12266:   Args:
12267:    docuname: username or courseid of destination for the file
12268:    docudom: domain of user/course of destination for the file
12269:    dir: dir to create (including any subdirs under userfiles)
12270: 
12271: =item *
12272: 
12273: removeuserfile(): removes a file that exists in userfiles
12274: 
12275:   Args:
12276:    docuname: username or courseid of destination for the file
12277:    docudom: domain of user/course of destination for the file
12278:    fname: filname to delete (including any subdirs under userfiles)
12279: 
12280: =item *
12281: 
12282: removeuploadedurl(): convience function for removeuserfile()
12283: 
12284:   Args:
12285:    url:  a full /uploaded/... url to delete
12286: 
12287: =item * 
12288: 
12289: get_portfile_permissions():
12290:   Args:
12291:     domain: domain of user or course contain the portfolio files
12292:     user: name of user or num of course contain the portfolio files
12293:   Returns:
12294:     hashref of a dump of the proper file_permissions.db
12295:    
12296: 
12297: =item * 
12298: 
12299: get_access_controls():
12300: 
12301: Args:
12302:   current_permissions: the hash ref returned from get_portfile_permissions()
12303:   group: (optional) the group you want the files associated with
12304:   file: (optional) the file you want access info on
12305: 
12306: Returns:
12307:     a hash (keys are file names) of hashes containing
12308:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12309:         values are XML containing access control settings (see below) 
12310: 
12311: Internal notes:
12312: 
12313:  access controls are stored in file_permissions.db as key=value pairs.
12314:     key -> path to file/file_name\0uniqueID:scope_end_start
12315:         where scope -> public,guest,course,group,domains or users.
12316:               end -> UNIX time for end of access (0 -> no end date)
12317:               start -> UNIX time for start of access
12318: 
12319:     value -> XML description of access control
12320:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12321:             <start></start>
12322:             <end></end>
12323: 
12324:             <password></password>  for scope type = guest
12325: 
12326:             <domain></domain>     for scope type = course or group
12327:             <number></number>
12328:             <roles id="">
12329:              <role></role>
12330:              <access></access>
12331:              <section></section>
12332:              <group></group>
12333:             </roles>
12334: 
12335:             <dom></dom>         for scope type = domains
12336: 
12337:             <users>             for scope type = users
12338:              <user>
12339:               <uname></uname>
12340:               <udom></udom>
12341:              </user>
12342:             </users>
12343:            </scope> 
12344:               
12345:  Access data is also aggregated for each file in an additional key=value pair:
12346:  key -> path to file/file_name\0accesscontrol 
12347:  value -> reference to hash
12348:           hash contains key = value pairs
12349:           where key = uniqueID:scope_end_start
12350:                 value = UNIX time record was last updated
12351: 
12352:           Used to improve speed of look-ups of access controls for each file.  
12353:  
12354:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12355: 
12356: modify_access_controls():
12357: 
12358: Modifies access controls for a portfolio file
12359: Args
12360: 1. file name
12361: 2. reference to hash of required changes,
12362: 3. domain
12363: 4. username
12364:   where domain,username are the domain of the portfolio owner 
12365:   (either a user or a course) 
12366: 
12367: Returns:
12368: 1. result of additions or updates ('ok' or 'error', with error message). 
12369: 2. result of deletions ('ok' or 'error', with error message).
12370: 3. reference to hash of any new or updated access controls.
12371: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12372:    key = integer (inbound ID)
12373:    value = uniqueID  
12374: 
12375: =back
12376: 
12377: =head2 HTTP Helper Routines
12378: 
12379: =over 4
12380: 
12381: =item *
12382: 
12383: escape() : unpack non-word characters into CGI-compatible hex codes
12384: 
12385: =item *
12386: 
12387: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12388: 
12389: =back
12390: 
12391: =head1 PRIVATE SUBROUTINES
12392: 
12393: =head2 Underlying communication routines (Shouldn't call)
12394: 
12395: =over 4
12396: 
12397: =item *
12398: 
12399: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12400: 
12401: =item *
12402: 
12403: reply() : uses subreply to send a message to remote machine, logs all failures
12404: 
12405: =item *
12406: 
12407: critical() : passes a critical message to another server; if cannot
12408: get through then place message in connection buffer directory and
12409: returns con_delayed, if incapable of saving message, returns
12410: con_failed
12411: 
12412: =item *
12413: 
12414: reconlonc() : tries to reconnect lonc client processes.
12415: 
12416: =back
12417: 
12418: =head2 Resource Access Logging
12419: 
12420: =over 4
12421: 
12422: =item *
12423: 
12424: flushcourselogs() : flush (save) buffer logs and access logs
12425: 
12426: =item *
12427: 
12428: courselog($what) : save message for course in hash
12429: 
12430: =item *
12431: 
12432: courseacclog($what) : save message for course using &courselog().  Perform
12433: special processing for specific resource types (problems, exams, quizzes, etc).
12434: 
12435: =item *
12436: 
12437: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12438: as a PerlChildExitHandler
12439: 
12440: =back
12441: 
12442: =head2 Other
12443: 
12444: =over 4
12445: 
12446: =item *
12447: 
12448: symblist($mapname,%newhash) : update symbolic storage links
12449: 
12450: =back
12451: 
12452: =cut
12453: 

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