File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1168: download - view: text, annotated - select for diffs
Fri May 18 15:31:40 2012 UTC (12 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Some documentation

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1168 2012/05/18 15:31:40 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: use LONCAPA::Lond;
  101: 
  102: use File::Copy;
  103: 
  104: my $readit;
  105: my $max_connection_retries = 10;     # Or some such value.
  106: 
  107: require Exporter;
  108: 
  109: our @ISA = qw (Exporter);
  110: our @EXPORT = qw(%env);
  111: 
  112: 
  113: # --------------------------------------------------------------------- Logging
  114: {
  115:     my $logid;
  116:     sub instructor_log {
  117: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  118:         if (($cnum eq '') || ($cdom eq '')) {
  119:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  120:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  121:         }
  122: 	$logid++;
  123:         my $now = time();
  124: 	my $id=$now.'00000'.$$.'00000'.$logid;
  125: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  126: 				    { $id => {
  127: 					'exe_uname' => $env{'user.name'},
  128: 					'exe_udom'  => $env{'user.domain'},
  129: 					'exe_time'  => $now,
  130: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  131: 					'delflag'   => $delflag,
  132: 					'logentry'  => $storehash,
  133: 					'uname'     => $uname,
  134: 					'udom'      => $udom,
  135: 				    }
  136: 				  },$cdom,$cnum);
  137:     }
  138: }
  139: 
  140: sub logtouch {
  141:     my $execdir=$perlvar{'lonDaemons'};
  142:     unless (-e "$execdir/logs/lonnet.log") {	
  143: 	open(my $fh,">>$execdir/logs/lonnet.log");
  144: 	close $fh;
  145:     }
  146:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  147:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  148: }
  149: 
  150: sub logthis {
  151:     my $message=shift;
  152:     my $execdir=$perlvar{'lonDaemons'};
  153:     my $now=time;
  154:     my $local=localtime($now);
  155:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  156: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  157: 	print $fh $logstring;
  158: 	close($fh);
  159:     }
  160:     return 1;
  161: }
  162: 
  163: sub logperm {
  164:     my $message=shift;
  165:     my $execdir=$perlvar{'lonDaemons'};
  166:     my $now=time;
  167:     my $local=localtime($now);
  168:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  169: 	print $fh "$now:$message:$local\n";
  170: 	close($fh);
  171:     }
  172:     return 1;
  173: }
  174: 
  175: sub create_connection {
  176:     my ($hostname,$lonid) = @_;
  177:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  178: 				     Type    => SOCK_STREAM,
  179: 				     Timeout => 10);
  180:     return 0 if (!$client);
  181:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  182:     my $result = <$client>;
  183:     chomp($result);
  184:     return 1 if ($result eq 'done');
  185:     return 0;
  186: }
  187: 
  188: sub get_server_timezone {
  189:     my ($cnum,$cdom) = @_;
  190:     my $home=&homeserver($cnum,$cdom);
  191:     if ($home ne 'no_host') {
  192:         my $cachetime = 24*3600;
  193:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  194:         if (defined($cached)) {
  195:             return $timezone;
  196:         } else {
  197:             my $timezone = &reply('servertimezone',$home);
  198:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  199:         }
  200:     }
  201: }
  202: 
  203: sub get_server_distarch {
  204:     my ($lonhost,$ignore_cache) = @_;
  205:     if (defined($lonhost)) {
  206:         if (!defined(&hostname($lonhost))) {
  207:             return;
  208:         }
  209:         my $cachetime = 12*3600;
  210:         if (!$ignore_cache) {
  211:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  212:             if (defined($cached)) {
  213:                 return $distarch;
  214:             }
  215:         }
  216:         my $rep = &reply('serverdistarch',$lonhost);
  217:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  218:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  219:                 $rep eq '') {
  220:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  221:         }
  222:     }
  223:     return;
  224: }
  225: 
  226: sub get_server_loncaparev {
  227:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  228:     if (defined($lonhost)) {
  229:         if (!defined(&hostname($lonhost))) {
  230:             undef($lonhost);
  231:         }
  232:     }
  233:     if (!defined($lonhost)) {
  234:         if (defined(&domain($dom,'primary'))) {
  235:             $lonhost=&domain($dom,'primary');
  236:             if ($lonhost eq 'no_host') {
  237:                 undef($lonhost);
  238:             }
  239:         }
  240:     }
  241:     if (defined($lonhost)) {
  242:         my $cachetime = 12*3600;
  243:         if (!$ignore_cache) {
  244:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  245:             if (defined($cached)) {
  246:                 return $loncaparev;
  247:             }
  248:         }
  249:         my ($answer,$loncaparev);
  250:         my @ids=&current_machine_ids();
  251:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  252:             $answer = $perlvar{'lonVersion'};
  253:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  254:                 $loncaparev = $1;
  255:             }
  256:         } else {
  257:             $answer = &reply('serverloncaparev',$lonhost);
  258:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  259:                 if ($caller eq 'loncron') {
  260:                     my $ua=new LWP::UserAgent;
  261:                     $ua->timeout(4);
  262:                     my $protocol = $protocol{$lonhost};
  263:                     $protocol = 'http' if ($protocol ne 'https');
  264:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  265:                     my $request=new HTTP::Request('GET',$url);
  266:                     my $response=$ua->request($request);
  267:                     unless ($response->is_error()) {
  268:                         my $content = $response->content;
  269:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  270:                             $loncaparev = $1;
  271:                         }
  272:                     }
  273:                 } else {
  274:                     $loncaparev = $loncaparevs{$lonhost};
  275:                 }
  276:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  277:                 $loncaparev = $1;
  278:             }
  279:         }
  280:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  281:     }
  282: }
  283: 
  284: sub get_server_homeID {
  285:     my ($hostname,$ignore_cache,$caller) = @_;
  286:     unless ($ignore_cache) {
  287:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  288:         if (defined($cached)) {
  289:             return $serverhomeID;
  290:         }
  291:     }
  292:     my $cachetime = 12*3600;
  293:     my $serverhomeID;
  294:     if ($caller eq 'loncron') { 
  295:         my @machine_ids = &machine_ids($hostname);
  296:         foreach my $id (@machine_ids) {
  297:             my $response = &reply('serverhomeID',$id);
  298:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  299:                 $serverhomeID = $response;
  300:                 last;
  301:             }
  302:         }
  303:         if ($serverhomeID eq '') {
  304:             $serverhomeID = $machine_ids[-1];
  305:         }
  306:     } else {
  307:         $serverhomeID = $serverhomeIDs{$hostname};
  308:     }
  309:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  310: }
  311: 
  312: sub get_remote_globals {
  313:     my ($lonhost,$whathash,$ignore_cache) = @_;
  314:     my ($result,%returnhash,%whatneeded);
  315:     if (ref($whathash) eq 'HASH') {
  316:         foreach my $what (sort(keys(%{$whathash}))) {
  317:             my $hashid = $lonhost.'-'.$what;
  318:             my ($response,$cached);
  319:             unless ($ignore_cache) {
  320:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  321:             }
  322:             if (defined($cached)) {
  323:                 $returnhash{$what} = $response;
  324:             } else {
  325:                 $whatneeded{$what} = 1;
  326:             }
  327:         }
  328:         if (keys(%whatneeded) == 0) {
  329:             $result = 'ok';
  330:         } else {
  331:             my $requested = &freeze_escape(\%whatneeded);
  332:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  333:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  334:                 ($rep eq 'unknown_cmd')) {
  335:                 $result = $rep;
  336:             } else {
  337:                 $result = 'ok';
  338:                 my @pairs=split(/\&/,$rep);
  339:                 foreach my $item (@pairs) {
  340:                     my ($key,$value)=split(/=/,$item,2);
  341:                     my $what = &unescape($key);
  342:                     my $hashid = $lonhost.'-'.$what;
  343:                     $returnhash{$what}=&thaw_unescape($value);
  344:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  345:                 }
  346:             }
  347:         }
  348:     }
  349:     return ($result,\%returnhash);
  350: }
  351: 
  352: sub remote_devalidate_cache {
  353:     my ($lonhost,$name,$id) = @_;
  354:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  355:     return $response;
  356: }
  357: 
  358: # -------------------------------------------------- Non-critical communication
  359: sub subreply {
  360:     my ($cmd,$server)=@_;
  361:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  362:     #
  363:     #  With loncnew process trimming, there's a timing hole between lonc server
  364:     #  process exit and the master server picking up the listen on the AF_UNIX
  365:     #  socket.  In that time interval, a lock file will exist:
  366: 
  367:     my $lockfile=$peerfile.".lock";
  368:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  369: 	sleep(1);
  370:     }
  371:     # At this point, either a loncnew parent is listening or an old lonc
  372:     # or loncnew child is listening so we can connect or everything's dead.
  373:     #
  374:     #   We'll give the connection a few tries before abandoning it.  If
  375:     #   connection is not possible, we'll con_lost back to the client.
  376:     #   
  377:     my $client;
  378:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  379: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  380: 				      Type    => SOCK_STREAM,
  381: 				      Timeout => 10);
  382: 	if ($client) {
  383: 	    last;		# Connected!
  384: 	} else {
  385: 	    &create_connection(&hostname($server),$server);
  386: 	}
  387:         sleep(1);		# Try again later if failed connection.
  388:     }
  389:     my $answer;
  390:     if ($client) {
  391: 	print $client "sethost:$server:$cmd\n";
  392: 	$answer=<$client>;
  393: 	if (!$answer) { $answer="con_lost"; }
  394: 	chomp($answer);
  395:     } else {
  396: 	$answer = 'con_lost';	# Failed connection.
  397:     }
  398:     return $answer;
  399: }
  400: 
  401: sub reply {
  402:     my ($cmd,$server)=@_;
  403:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  404:     my $answer=subreply($cmd,$server);
  405:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  406:        &logthis("<font color=\"blue\">WARNING:".
  407:                 " $cmd to $server returned $answer</font>");
  408:     }
  409:     return $answer;
  410: }
  411: 
  412: # ----------------------------------------------------------- Send USR1 to lonc
  413: 
  414: sub reconlonc {
  415:     my ($lonid) = @_;
  416:     my $hostname = &hostname($lonid);
  417:     if ($lonid) {
  418: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  419: 	if ($hostname && -e $peerfile) {
  420: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  421: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  422: 					     Type    => SOCK_STREAM,
  423: 					     Timeout => 10);
  424: 	    if ($client) {
  425: 		print $client ("reset_retries\n");
  426: 		my $answer=<$client>;
  427: 		#reset just this one.
  428: 	    }
  429: 	}
  430: 	return;
  431:     }
  432: 
  433:     &logthis("Trying to reconnect lonc");
  434:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  435:     if (open(my $fh,"<$loncfile")) {
  436: 	my $loncpid=<$fh>;
  437:         chomp($loncpid);
  438:         if (kill 0 => $loncpid) {
  439: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  440:             kill USR1 => $loncpid;
  441:             sleep 1;
  442:          } else {
  443: 	    &logthis(
  444:                "<font color=\"blue\">WARNING:".
  445:                " lonc at pid $loncpid not responding, giving up</font>");
  446:         }
  447:     } else {
  448: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  449:     }
  450: }
  451: 
  452: # ------------------------------------------------------ Critical communication
  453: 
  454: sub critical {
  455:     my ($cmd,$server)=@_;
  456:     unless (&hostname($server)) {
  457:         &logthis("<font color=\"blue\">WARNING:".
  458:                " Critical message to unknown server ($server)</font>");
  459:         return 'no_such_host';
  460:     }
  461:     my $answer=reply($cmd,$server);
  462:     if ($answer eq 'con_lost') {
  463: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  464: 	my $answer=reply($cmd,$server);
  465:         if ($answer eq 'con_lost') {
  466:             my $now=time;
  467:             my $middlename=$cmd;
  468:             $middlename=substr($middlename,0,16);
  469:             $middlename=~s/\W//g;
  470:             my $dfilename=
  471:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  472:             $dumpcount++;
  473:             {
  474: 		my $dfh;
  475: 		if (open($dfh,">$dfilename")) {
  476: 		    print $dfh "$cmd\n"; 
  477: 		    close($dfh);
  478: 		}
  479:             }
  480:             sleep 2;
  481:             my $wcmd='';
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,"<$dfilename")) {
  485: 		    $wcmd=<$dfh>; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             chomp($wcmd);
  490:             if ($wcmd eq $cmd) {
  491: 		&logthis("<font color=\"blue\">WARNING: ".
  492:                          "Connection buffer $dfilename: $cmd</font>");
  493:                 &logperm("D:$server:$cmd");
  494: 	        return 'con_delayed';
  495:             } else {
  496:                 &logthis("<font color=\"red\">CRITICAL:"
  497:                         ." Critical connection failed: $server $cmd</font>");
  498:                 &logperm("F:$server:$cmd");
  499:                 return 'con_failed';
  500:             }
  501:         }
  502:     }
  503:     return $answer;
  504: }
  505: 
  506: # ------------------------------------------- check if return value is an error
  507: 
  508: sub error {
  509:     my ($result) = @_;
  510:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  511: 	if ($2 == 2) { return undef; }
  512: 	return $1;
  513:     }
  514:     return undef;
  515: }
  516: 
  517: sub convert_and_load_session_env {
  518:     my ($lonidsdir,$handle)=@_;
  519:     my @profile;
  520:     {
  521: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  522: 	if (!$opened) {
  523: 	    return 0;
  524: 	}
  525: 	flock($idf,LOCK_SH);
  526: 	@profile=<$idf>;
  527: 	close($idf);
  528:     }
  529:     my %temp_env;
  530:     foreach my $line (@profile) {
  531: 	if ($line !~ m/=/) {
  532: 	    return 0;
  533: 	}
  534: 	chomp($line);
  535: 	my ($envname,$envvalue)=split(/=/,$line,2);
  536: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  537:     }
  538:     unlink("$lonidsdir/$handle.id");
  539:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  540: 	    0640)) {
  541: 	%disk_env = %temp_env;
  542: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  543: 	untie(%disk_env);
  544:     }
  545:     return 1;
  546: }
  547: 
  548: # ------------------------------------------- Transfer profile into environment
  549: my $env_loaded;
  550: sub transfer_profile_to_env {
  551:     my ($lonidsdir,$handle,$force_transfer) = @_;
  552:     if (!$force_transfer && $env_loaded) { return; } 
  553: 
  554:     if (!defined($lonidsdir)) {
  555: 	$lonidsdir = $perlvar{'lonIDsDir'};
  556:     }
  557:     if (!defined($handle)) {
  558:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  559:     }
  560: 
  561:     my $convert;
  562:     {
  563:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  564: 	if (!$opened) {
  565: 	    return;
  566: 	}
  567: 	flock($idf,LOCK_SH);
  568: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  569: 		&GDBM_READER(),0640)) {
  570: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  571: 	    untie(%disk_env);
  572: 	} else {
  573: 	    $convert = 1;
  574: 	}
  575:     }
  576:     if ($convert) {
  577: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  578: 	    &logthis("Failed to load session, or convert session.");
  579: 	}
  580:     }
  581: 
  582:     my %remove;
  583:     while ( my $envname = each(%env) ) {
  584:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  585:             if ($time < time-300) {
  586:                 $remove{$key}++;
  587:             }
  588:         }
  589:     }
  590: 
  591:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  592:     $env_loaded=1;
  593:     foreach my $expired_key (keys(%remove)) {
  594:         &delenv($expired_key);
  595:     }
  596: }
  597: 
  598: # ---------------------------------------------------- Check for valid session 
  599: sub check_for_valid_session {
  600:     my ($r,$name) = @_;
  601:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  602:     if ($name eq '') {
  603:         $name = 'lonID';
  604:     }
  605:     my $lonid=$cookies{$name};
  606:     return undef if (!$lonid);
  607: 
  608:     my $handle=&LONCAPA::clean_handle($lonid->value);
  609:     my $lonidsdir;
  610:     if ($name eq 'lonDAV') {
  611:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  612:     } else {
  613:         $lonidsdir=$r->dir_config('lonIDsDir');
  614:     }
  615:     return undef if (!-e "$lonidsdir/$handle.id");
  616: 
  617:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  618:     return undef if (!$opened);
  619: 
  620:     flock($idf,LOCK_SH);
  621:     my %disk_env;
  622:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  623: 	    &GDBM_READER(),0640)) {
  624: 	return undef;	
  625:     }
  626: 
  627:     if (!defined($disk_env{'user.name'})
  628: 	|| !defined($disk_env{'user.domain'})) {
  629: 	return undef;
  630:     }
  631:     return $handle;
  632: }
  633: 
  634: sub timed_flock {
  635:     my ($file,$lock_type) = @_;
  636:     my $failed=0;
  637:     eval {
  638: 	local $SIG{__DIE__}='DEFAULT';
  639: 	local $SIG{ALRM}=sub {
  640: 	    $failed=1;
  641: 	    die("failed lock");
  642: 	};
  643: 	alarm(13);
  644: 	flock($file,$lock_type);
  645: 	alarm(0);
  646:     };
  647:     if ($failed) {
  648: 	return undef;
  649:     } else {
  650: 	return 1;
  651:     }
  652: }
  653: 
  654: # ---------------------------------------------------------- Append Environment
  655: 
  656: sub appenv {
  657:     my ($newenv,$roles) = @_;
  658:     if (ref($newenv) eq 'HASH') {
  659:         foreach my $key (keys(%{$newenv})) {
  660:             my $refused = 0;
  661: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  662:                 $refused = 1;
  663:                 if (ref($roles) eq 'ARRAY') {
  664:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  665:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  666:                         $refused = 0;
  667:                     }
  668:                 }
  669:             }
  670:             if ($refused) {
  671:                 &logthis("<font color=\"blue\">WARNING: ".
  672:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  673:                          .'</font>');
  674: 	        delete($newenv->{$key});
  675:             } else {
  676:                 $env{$key}=$newenv->{$key};
  677:             }
  678:         }
  679:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  680:         if ($opened
  681: 	    && &timed_flock($env_file,LOCK_EX)
  682: 	    &&
  683: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  684: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  685: 	    while (my ($key,$value) = each(%{$newenv})) {
  686: 	        $disk_env{$key} = $value;
  687: 	    }
  688: 	    untie(%disk_env);
  689:         }
  690:     }
  691:     return 'ok';
  692: }
  693: # ----------------------------------------------------- Delete from Environment
  694: 
  695: sub delenv {
  696:     my ($delthis,$regexp,$roles) = @_;
  697:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  698:         my $refused = 1;
  699:         if (ref($roles) eq 'ARRAY') {
  700:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  701:             if (grep(/^\Q$role\E$/,@{$roles})) {
  702:                 $refused = 0;
  703:             }
  704:         }
  705:         if ($refused) {
  706:             &logthis("<font color=\"blue\">WARNING: ".
  707:                      "Attempt to delete from environment ".$delthis);
  708:             return 'error';
  709:         }
  710:     }
  711:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  712:     if ($opened
  713: 	&& &timed_flock($env_file,LOCK_EX)
  714: 	&&
  715: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  716: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  717: 	foreach my $key (keys(%disk_env)) {
  718: 	    if ($regexp) {
  719:                 if ($key=~/^$delthis/) {
  720:                     delete($env{$key});
  721:                     delete($disk_env{$key});
  722:                 } 
  723:             } else {
  724:                 if ($key=~/^\Q$delthis\E/) {
  725: 		    delete($env{$key});
  726: 		    delete($disk_env{$key});
  727: 	        }
  728:             }
  729: 	}
  730: 	untie(%disk_env);
  731:     }
  732:     return 'ok';
  733: }
  734: 
  735: sub get_env_multiple {
  736:     my ($name) = @_;
  737:     my @values;
  738:     if (defined($env{$name})) {
  739:         # exists is it an array
  740:         if (ref($env{$name})) {
  741:             @values=@{ $env{$name} };
  742:         } else {
  743:             $values[0]=$env{$name};
  744:         }
  745:     }
  746:     return(@values);
  747: }
  748: 
  749: # ------------------------------------------------------------------- Locking
  750: 
  751: sub set_lock {
  752:     my ($text)=@_;
  753:     $locknum++;
  754:     my $id=$$.'-'.$locknum;
  755:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  756:              'session.lock.'.$id => $text});
  757:     return $id;
  758: }
  759: 
  760: sub get_locks {
  761:     my $num=0;
  762:     my %texts=();
  763:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  764:        if ($lock=~/\w/) {
  765:           $num++;
  766:           $texts{$lock}=$env{'session.lock.'.$lock};
  767:        }
  768:    }
  769:    return ($num,%texts);
  770: }
  771: 
  772: sub remove_lock {
  773:     my ($id)=@_;
  774:     my $newlocks='';
  775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  776:        if (($lock=~/\w/) && ($lock ne $id)) {
  777:           $newlocks.=','.$lock;
  778:        }
  779:     }
  780:     &appenv({'session.locks' => $newlocks});
  781:     &delenv('session.lock.'.$id);
  782: }
  783: 
  784: sub remove_all_locks {
  785:     my $activelocks=$env{'session.locks'};
  786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  787:        if ($lock=~/\w/) {
  788:           &remove_lock($lock);
  789:        }
  790:     }
  791: }
  792: 
  793: 
  794: # ------------------------------------------ Find out current server userload
  795: sub userload {
  796:     my $numusers=0;
  797:     {
  798: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  799: 	my $filename;
  800: 	my $curtime=time;
  801: 	while ($filename=readdir(LONIDS)) {
  802: 	    next if ($filename eq '.' || $filename eq '..');
  803: 	    next if ($filename =~ /publicuser_\d+\.id/);
  804: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  805: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  806: 	}
  807: 	closedir(LONIDS);
  808:     }
  809:     my $userloadpercent=0;
  810:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  811:     if ($maxuserload) {
  812: 	$userloadpercent=100*$numusers/$maxuserload;
  813:     }
  814:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  815:     return $userloadpercent;
  816: }
  817: 
  818: # ------------------------------ Find server with least workload from spare.tab
  819: 
  820: sub spareserver {
  821:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  822:     my $spare_server;
  823:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  824:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  825:                                                      :  $userloadpercent;
  826:     my ($uint_dom,$remotesessions);
  827:     if (($udom ne '') && (&domain($udom) ne '')) {
  828:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  829:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  830:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  831:         $remotesessions = $udomdefaults{'remotesessions'};
  832:     }
  833:     my $spareshash = &this_host_spares($udom);
  834:     if (ref($spareshash) eq 'HASH') {
  835:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  836:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  837:                 if ($uint_dom) {
  838:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  839:                                                  $try_server));
  840:                 }
  841: 	        ($spare_server, $lowest_load) =
  842: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  843:             }
  844:         }
  845: 
  846:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  847: 
  848:         if (!$found_server) {
  849:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  850: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  851:                     if ($uint_dom) {
  852:                         next unless (&spare_can_host($udom,$uint_dom,
  853:                                                      $remotesessions,$try_server));
  854:                     }
  855: 	            ($spare_server, $lowest_load) =
  856: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  857:                 }
  858: 	    }
  859:         }
  860:     }
  861: 
  862:     if (!$want_server_name) {
  863:         my $protocol = 'http';
  864:         if ($protocol{$spare_server} eq 'https') {
  865:             $protocol = $protocol{$spare_server};
  866:         }
  867:         if (defined($spare_server)) {
  868:             my $hostname = &hostname($spare_server);
  869:             if (defined($hostname)) {
  870: 	        $spare_server = $protocol.'://'.$hostname;
  871:             }
  872:         }
  873:     }
  874:     return $spare_server;
  875: }
  876: 
  877: sub compare_server_load {
  878:     my ($try_server, $spare_server, $lowest_load) = @_;
  879: 
  880:     my $loadans     = &reply('load',    $try_server);
  881:     my $userloadans = &reply('userload',$try_server);
  882: 
  883:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  884: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  885:     }
  886: 
  887:     my $load;
  888:     if ($loadans =~ /\d/) {
  889: 	if ($userloadans =~ /\d/) {
  890: 	    #both are numbers, pick the bigger one
  891: 	    $load = ($loadans > $userloadans) ? $loadans 
  892: 		                              : $userloadans;
  893: 	} else {
  894: 	    $load = $loadans;
  895: 	}
  896:     } else {
  897: 	$load = $userloadans;
  898:     }
  899: 
  900:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  901: 	$spare_server = $try_server;
  902: 	$lowest_load  = $load;
  903:     }
  904:     return ($spare_server,$lowest_load);
  905: }
  906: 
  907: # --------------------------- ask offload servers if user already has a session
  908: sub find_existing_session {
  909:     my ($udom,$uname) = @_;
  910:     my $spareshash = &this_host_spares($udom);
  911:     if (ref($spareshash) eq 'HASH') {
  912:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  913:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  914:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  915:             }
  916:         }
  917:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  918:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  919:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  920:             }
  921:         }
  922:     }
  923:     return;
  924: }
  925: 
  926: # -------------------------------- ask if server already has a session for user
  927: sub has_user_session {
  928:     my ($lonid,$udom,$uname) = @_;
  929:     my $result = &reply(join(':','userhassession',
  930: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  931:     return 1 if ($result eq 'ok');
  932: 
  933:     return 0;
  934: }
  935: 
  936: # --------- determine least loaded server in a user's domain which allows login
  937: 
  938: sub choose_server {
  939:     my ($udom,$checkloginvia) = @_;
  940:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  941:     my %servers = &get_servers($udom);
  942:     my $lowest_load = 30000;
  943:     my ($login_host,$hostname,$portal_path,$isredirect);
  944:     foreach my $lonhost (keys(%servers)) {
  945:         my $loginvia;
  946:         if ($checkloginvia) {
  947:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  948:             if ($loginvia) {
  949:                 my ($server,$path) = split(/:/,$loginvia);
  950:                 ($login_host, $lowest_load) =
  951:                     &compare_server_load($server, $login_host, $lowest_load);
  952:                 if ($login_host eq $server) {
  953:                     $portal_path = $path;
  954:                     $isredirect = 1;
  955:                 }
  956:             } else {
  957:                 ($login_host, $lowest_load) =
  958:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  959:                 if ($login_host eq $lonhost) {
  960:                     $portal_path = '';
  961:                     $isredirect = ''; 
  962:                 }
  963:             }
  964:         } else {
  965:             ($login_host, $lowest_load) =
  966:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  967:         }
  968:     }
  969:     if ($login_host ne '') {
  970:         $hostname = &hostname($login_host);
  971:     }
  972:     return ($login_host,$hostname,$portal_path,$isredirect);
  973: }
  974: 
  975: # --------------------------------------------- Try to change a user's password
  976: 
  977: sub changepass {
  978:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  979:     $currentpass = &escape($currentpass);
  980:     $newpass     = &escape($newpass);
  981:     my $lonhost = $perlvar{'lonHostID'};
  982:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  983: 		       $server);
  984:     if (! $answer) {
  985: 	&logthis("No reply on password change request to $server ".
  986: 		 "by $uname in domain $udom.");
  987:     } elsif ($answer =~ "^ok") {
  988:         &logthis("$uname in $udom successfully changed their password ".
  989: 		 "on $server.");
  990:     } elsif ($answer =~ "^pwchange_failure") {
  991: 	&logthis("$uname in $udom was unable to change their password ".
  992: 		 "on $server.  The action was blocked by either lcpasswd ".
  993: 		 "or pwchange");
  994:     } elsif ($answer =~ "^non_authorized") {
  995:         &logthis("$uname in $udom did not get their password correct when ".
  996: 		 "attempting to change it on $server.");
  997:     } elsif ($answer =~ "^auth_mode_error") {
  998:         &logthis("$uname in $udom attempted to change their password despite ".
  999: 		 "not being locally or internally authenticated on $server.");
 1000:     } elsif ($answer =~ "^unknown_user") {
 1001:         &logthis("$uname in $udom attempted to change their password ".
 1002: 		 "on $server but were unable to because $server is not ".
 1003: 		 "their home server.");
 1004:     } elsif ($answer =~ "^refused") {
 1005: 	&logthis("$server refused to change $uname in $udom password because ".
 1006: 		 "it was sent an unencrypted request to change the password.");
 1007:     } elsif ($answer =~ "invalid_client") {
 1008:         &logthis("$server refused to change $uname in $udom password because ".
 1009:                  "it was a reset by e-mail originating from an invalid server.");
 1010:     }
 1011:     return $answer;
 1012: }
 1013: 
 1014: # ----------------------- Try to determine user's current authentication scheme
 1015: 
 1016: sub queryauthenticate {
 1017:     my ($uname,$udom)=@_;
 1018:     my $uhome=&homeserver($uname,$udom);
 1019:     if (!$uhome) {
 1020: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1021: 	return 'no_host';
 1022:     }
 1023:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1024:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1025: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1026:     }
 1027:     return $answer;
 1028: }
 1029: 
 1030: # --------- Try to authenticate user from domain's lib servers (first this one)
 1031: 
 1032: sub authenticate {
 1033:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1034:     $upass=&escape($upass);
 1035:     $uname= &LONCAPA::clean_username($uname);
 1036:     my $uhome=&homeserver($uname,$udom,1);
 1037:     my $newhome;
 1038:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1039: # Maybe the machine was offline and only re-appeared again recently?
 1040:         &reconlonc();
 1041: # One more
 1042: 	$uhome=&homeserver($uname,$udom,1);
 1043:         if (($uhome eq 'no_host') && $checkdefauth) {
 1044:             if (defined(&domain($udom,'primary'))) {
 1045:                 $newhome=&domain($udom,'primary');
 1046:             }
 1047:             if ($newhome ne '') {
 1048:                 $uhome = $newhome;
 1049:             }
 1050:         }
 1051: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1053: 	    return 'no_host';
 1054:         }
 1055:     }
 1056:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1057:     if ($answer eq 'authorized') {
 1058:         if ($newhome) {
 1059:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1060:             return 'no_account_on_host'; 
 1061:         } else {
 1062:             &logthis("User $uname at $udom authorized by $uhome");
 1063:             return $uhome;
 1064:         }
 1065:     }
 1066:     if ($answer eq 'non_authorized') {
 1067: 	&logthis("User $uname at $udom rejected by $uhome");
 1068: 	return 'no_host'; 
 1069:     }
 1070:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1071:     return 'no_host';
 1072: }
 1073: 
 1074: sub can_host_session {
 1075:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1076:     my $canhost = 1;
 1077:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1078:     if (ref($remotesessions) eq 'HASH') {
 1079:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1080:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1081:                 $canhost = 0;
 1082:             } else {
 1083:                 $canhost = 1;
 1084:             }
 1085:         }
 1086:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1087:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1088:                 $canhost = 1;
 1089:             } else {
 1090:                 $canhost = 0;
 1091:             }
 1092:         }
 1093:         if ($canhost) {
 1094:             if ($remotesessions->{'version'} ne '') {
 1095:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1096:                 if ($reqmajor ne '' && $reqminor ne '') {
 1097:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1098:                         my $major = $1;
 1099:                         my $minor = $2;
 1100:                         if (($major < $reqmajor ) ||
 1101:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1102:                             $canhost = 0;
 1103:                         }
 1104:                     } else {
 1105:                         $canhost = 0;
 1106:                     }
 1107:                 }
 1108:             }
 1109:         }
 1110:     }
 1111:     if ($canhost) {
 1112:         if (ref($hostedsessions) eq 'HASH') {
 1113:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1114:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1115:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1116:                 if (($uint_dom ne '') && 
 1117:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1118:                     $canhost = 0;
 1119:                 } else {
 1120:                     $canhost = 1;
 1121:                 }
 1122:             }
 1123:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1124:                 if (($uint_dom ne '') && 
 1125:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1126:                     $canhost = 1;
 1127:                 } else {
 1128:                     $canhost = 0;
 1129:                 }
 1130:             }
 1131:         }
 1132:     }
 1133:     return $canhost;
 1134: }
 1135: 
 1136: sub spare_can_host {
 1137:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1138:     my $canhost=1;
 1139:     my @intdoms;
 1140:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1141:     if (ref($internet_names) eq 'ARRAY') {
 1142:         @intdoms = @{$internet_names};
 1143:     }
 1144:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1145:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1146:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1147:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1148:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1149:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1150:                                      $remotesessions,
 1151:                                      $defdomdefaults{'hostedsessions'});
 1152:     }
 1153:     return $canhost;
 1154: }
 1155: 
 1156: sub this_host_spares {
 1157:     my ($dom) = @_;
 1158:     my ($dom_in_use,$lonhost_in_use,$result);
 1159:     my @hosts = &current_machine_ids();
 1160:     foreach my $lonhost (@hosts) {
 1161:         if (&host_domain($lonhost) eq $dom) {
 1162:             $dom_in_use = $dom;
 1163:             $lonhost_in_use = $lonhost;
 1164:             last;
 1165:         }
 1166:     }
 1167:     if ($dom_in_use ne '') {
 1168:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1169:     }
 1170:     if (ref($result) ne 'HASH') {
 1171:         $lonhost_in_use = $perlvar{'lonHostID'};
 1172:         $dom_in_use = &host_domain($lonhost_in_use);
 1173:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1174:         if (ref($result) ne 'HASH') {
 1175:             $result = \%spareid;
 1176:         }
 1177:     }
 1178:     return $result;
 1179: }
 1180: 
 1181: sub spares_for_offload  {
 1182:     my ($dom_in_use,$lonhost_in_use) = @_;
 1183:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1184:     if (defined($cached)) {
 1185:         return $result;
 1186:     } else {
 1187:         my $cachetime = 60*60*24;
 1188:         my %domconfig =
 1189:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1190:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1191:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1192:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1193:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1194:                 }
 1195:             }
 1196:         }
 1197:     }
 1198:     return;
 1199: }
 1200: 
 1201: sub get_lonbalancer_config {
 1202:     my ($servers) = @_;
 1203:     my ($currbalancer,$currtargets);
 1204:     if (ref($servers) eq 'HASH') {
 1205:         foreach my $server (keys(%{$servers})) {
 1206:             my %what = (
 1207:                          spareid => 1,
 1208:                          perlvar => 1,
 1209:                        );
 1210:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1211:             if ($result eq 'ok') {
 1212:                 if (ref($returnhash) eq 'HASH') {
 1213:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1214:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1215:                             $currbalancer = $server;
 1216:                             $currtargets = {};
 1217:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1218:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1219:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1220:                                 }
 1221:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1222:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1223:                                 }
 1224:                             }
 1225:                             last;
 1226:                         }
 1227:                     }
 1228:                 }
 1229:             }
 1230:         }
 1231:     }
 1232:     return ($currbalancer,$currtargets);
 1233: }
 1234: 
 1235: sub check_loadbalancing {
 1236:     my ($uname,$udom) = @_;
 1237:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1238:         $offloadto,$otherserver);
 1239:     my $lonhost = $perlvar{'lonHostID'};
 1240:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1241:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1242:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1243:     my $serverhomedom = &host_domain($lonhost);
 1244: 
 1245:     my $cachetime = 60*60*24;
 1246: 
 1247:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1248:         $dom_in_use = $udom;
 1249:         $homeintdom = 1;
 1250:     } else {
 1251:         $dom_in_use = $serverhomedom;
 1252:     }
 1253:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1254:     unless (defined($cached)) {
 1255:         my %domconfig =
 1256:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1257:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1258:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1259:         }
 1260:     }
 1261:     if (ref($result) eq 'HASH') {
 1262:         my $currbalancer = $result->{'lonhost'};
 1263:         my $currtargets = $result->{'targets'};
 1264:         my $currrules = $result->{'rules'};
 1265:         if ($currbalancer ne '') {
 1266:             my @hosts = &current_machine_ids();
 1267:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1268:                 $is_balancer = 1;
 1269:             }
 1270:         }
 1271:         if ($is_balancer) {
 1272:             if (ref($currrules) eq 'HASH') {
 1273:                 if ($homeintdom) {
 1274:                     if ($uname ne '') {
 1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1281:                             }
 1282:                         }
 1283:                         if ($rule_in_effect eq '') {
 1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1285:                             if ($userenv{'inststatus'} ne '') {
 1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1287:                                 my ($othertitle,$usertypes,$types) =
 1288:                                     &Apache::loncommon::sorted_inst_types($udom);
 1289:                                 if (ref($types) eq 'ARRAY') {
 1290:                                     foreach my $type (@{$types}) {
 1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1292:                                             if (exists($currrules->{$type})) {
 1293:                                                 $rule_in_effect = $currrules->{$type};
 1294:                                             }
 1295:                                         }
 1296:                                     }
 1297:                                 }
 1298:                             } else {
 1299:                                 if (exists($currrules->{'default'})) {
 1300:                                     $rule_in_effect = $currrules->{'default'};
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     } else {
 1305:                         if (exists($currrules->{'default'})) {
 1306:                             $rule_in_effect = $currrules->{'default'};
 1307:                         }
 1308:                     }
 1309:                 } else {
 1310:                     if ($currrules->{'_LC_external'} ne '') {
 1311:                         $rule_in_effect = $currrules->{'_LC_external'};
 1312:                     }
 1313:                 }
 1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1315:                                                        $uname,$udom);
 1316:             }
 1317:         }
 1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1320:         unless (defined($cached)) {
 1321:             my %domconfig =
 1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1325:             }
 1326:         }
 1327:         if (ref($result) eq 'HASH') {
 1328:             my $currbalancer = $result->{'lonhost'};
 1329:             my $currtargets = $result->{'targets'};
 1330:             my $currrules = $result->{'rules'};
 1331: 
 1332:             if ($currbalancer eq $lonhost) {
 1333:                 $is_balancer = 1;
 1334:                 if (ref($currrules) eq 'HASH') {
 1335:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1336:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1337:                     }
 1338:                 }
 1339:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1340:                                                        $uname,$udom);
 1341:             }
 1342:         } else {
 1343:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1344:                 $is_balancer = 1;
 1345:                 $offloadto = &this_host_spares($dom_in_use);
 1346:             }
 1347:         }
 1348:     } else {
 1349:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1350:             $is_balancer = 1;
 1351:             $offloadto = &this_host_spares($dom_in_use);
 1352:         }
 1353:     }
 1354:     my $lowest_load = 30000;
 1355:     if (ref($offloadto) eq 'HASH') {
 1356:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1357:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1358:                 ($otherserver,$lowest_load) =
 1359:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1360:             }
 1361:         }
 1362:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1363: 
 1364:         if (!$found_server) {
 1365:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1366:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1367:                     ($otherserver,$lowest_load) =
 1368:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1369:                 }
 1370:             }
 1371:         }
 1372:     } elsif (ref($offloadto) eq 'ARRAY') {
 1373:         if (@{$offloadto} == 1) {
 1374:             $otherserver = $offloadto->[0];
 1375:         } elsif (@{$offloadto} > 1) {
 1376:             foreach my $try_server (@{$offloadto}) {
 1377:                 ($otherserver,$lowest_load) =
 1378:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1379:             }
 1380:         }
 1381:     }
 1382:     return ($is_balancer,$otherserver);
 1383: }
 1384: 
 1385: sub get_loadbalancer_targets {
 1386:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1387:     my $offloadto;
 1388:     if ($rule_in_effect eq '') {
 1389:         $offloadto = $currtargets;
 1390:     } else {
 1391:         if ($rule_in_effect eq 'homeserver') {
 1392:             my $homeserver = &homeserver($uname,$udom);
 1393:             if ($homeserver ne 'no_host') {
 1394:                 $offloadto = [$homeserver];
 1395:             }
 1396:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1397:             my %domconfig =
 1398:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1399:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1400:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1401:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1402:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1403:                     }
 1404:                 }
 1405:             } else {
 1406:                 my %servers = &dom_servers($udom);
 1407:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1408:                 if (&hostname($remotebalancer) ne '') {
 1409:                     $offloadto = [$remotebalancer];
 1410:                 }
 1411:             }
 1412:         } elsif (&hostname($rule_in_effect) ne '') {
 1413:             $offloadto = [$rule_in_effect];
 1414:         }
 1415:     }
 1416:     return $offloadto;
 1417: }
 1418: 
 1419: sub internet_dom_servers {
 1420:     my ($dom) = @_;
 1421:     my (%uniqservers,%servers);
 1422:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1423:     my @machinedoms = &machine_domains($primaryserver);
 1424:     foreach my $mdom (@machinedoms) {
 1425:         my %currservers = %servers;
 1426:         my %server = &get_servers($mdom);
 1427:         %servers = (%currservers,%server);
 1428:     }
 1429:     my %by_hostname;
 1430:     foreach my $id (keys(%servers)) {
 1431:         push(@{$by_hostname{$servers{$id}}},$id);
 1432:     }
 1433:     foreach my $hostname (sort(keys(%by_hostname))) {
 1434:         if (@{$by_hostname{$hostname}} > 1) {
 1435:             my $match = 0;
 1436:             foreach my $id (@{$by_hostname{$hostname}}) {
 1437:                 if (&host_domain($id) eq $dom) {
 1438:                     $uniqservers{$id} = $hostname;
 1439:                     $match = 1;
 1440:                 }
 1441:             }
 1442:             unless ($match) {
 1443:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1444:             }
 1445:         } else {
 1446:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1447:         }
 1448:     }
 1449:     return %uniqservers;
 1450: }
 1451: 
 1452: # ---------------------- Find the homebase for a user from domain's lib servers
 1453: 
 1454: my %homecache;
 1455: sub homeserver {
 1456:     my ($uname,$udom,$ignoreBadCache)=@_;
 1457:     my $index="$uname:$udom";
 1458: 
 1459:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1460: 
 1461:     my %servers = &get_servers($udom,'library');
 1462:     foreach my $tryserver (keys(%servers)) {
 1463:         next if ($ignoreBadCache ne 'true' && 
 1464: 		 exists($badServerCache{$tryserver}));
 1465: 
 1466: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1467: 	if ($answer eq 'found') {
 1468: 	    delete($badServerCache{$tryserver}); 
 1469: 	    return $homecache{$index}=$tryserver;
 1470: 	} elsif ($answer eq 'no_host') {
 1471: 	    $badServerCache{$tryserver}=1;
 1472: 	}
 1473:     }    
 1474:     return 'no_host';
 1475: }
 1476: 
 1477: # ------------------------------------- Find the usernames behind a list of IDs
 1478: 
 1479: sub idget {
 1480:     my ($udom,@ids)=@_;
 1481:     my %returnhash=();
 1482:     
 1483:     my %servers = &get_servers($udom,'library');
 1484:     foreach my $tryserver (keys(%servers)) {
 1485: 	my $idlist=join('&',@ids);
 1486: 	$idlist=~tr/A-Z/a-z/; 
 1487: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1488: 	my @answer=();
 1489: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1490: 	    @answer=split(/\&/,$reply);
 1491: 	}                    ;
 1492: 	my $i;
 1493: 	for ($i=0;$i<=$#ids;$i++) {
 1494: 	    if ($answer[$i]) {
 1495: 		$returnhash{$ids[$i]}=$answer[$i];
 1496: 	    } 
 1497: 	}
 1498:     } 
 1499:     return %returnhash;
 1500: }
 1501: 
 1502: # ------------------------------------- Find the IDs behind a list of usernames
 1503: 
 1504: sub idrget {
 1505:     my ($udom,@unames)=@_;
 1506:     my %returnhash=();
 1507:     foreach my $uname (@unames) {
 1508:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1509:     }
 1510:     return %returnhash;
 1511: }
 1512: 
 1513: # ------------------------------- Store away a list of names and associated IDs
 1514: 
 1515: sub idput {
 1516:     my ($udom,%ids)=@_;
 1517:     my %servers=();
 1518:     foreach my $uname (keys(%ids)) {
 1519: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1520:         my $uhom=&homeserver($uname,$udom);
 1521:         if ($uhom ne 'no_host') {
 1522:             my $id=&escape($ids{$uname});
 1523:             $id=~tr/A-Z/a-z/;
 1524:             my $esc_unam=&escape($uname);
 1525: 	    if ($servers{$uhom}) {
 1526: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1527:             } else {
 1528:                 $servers{$uhom}=$id.'='.$esc_unam;
 1529:             }
 1530:         }
 1531:     }
 1532:     foreach my $server (keys(%servers)) {
 1533:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1534:     }
 1535: }
 1536: 
 1537: # ------------------------------dump from db file owned by domainconfig user
 1538: sub dump_dom {
 1539:     my ($namespace, $udom, $regexp) = @_;
 1540: 
 1541:     $udom ||= $env{'user.domain'};
 1542: 
 1543:     return () unless $udom;
 1544: 
 1545:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1546: }
 1547: 
 1548: # ------------------------------------------ get items from domain db files   
 1549: 
 1550: sub get_dom {
 1551:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1552:     my $items='';
 1553:     foreach my $item (@$storearr) {
 1554:         $items.=&escape($item).'&';
 1555:     }
 1556:     $items=~s/\&$//;
 1557:     if (!$udom) {
 1558:         $udom=$env{'user.domain'};
 1559:         if (defined(&domain($udom,'primary'))) {
 1560:             $uhome=&domain($udom,'primary');
 1561:         } else {
 1562:             undef($uhome);
 1563:         }
 1564:     } else {
 1565:         if (!$uhome) {
 1566:             if (defined(&domain($udom,'primary'))) {
 1567:                 $uhome=&domain($udom,'primary');
 1568:             }
 1569:         }
 1570:     }
 1571:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1572:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1573:         my %returnhash;
 1574:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1575:             return %returnhash;
 1576:         }
 1577:         my @pairs=split(/\&/,$rep);
 1578:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1579:             return @pairs;
 1580:         }
 1581:         my $i=0;
 1582:         foreach my $item (@$storearr) {
 1583:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1584:             $i++;
 1585:         }
 1586:         return %returnhash;
 1587:     } else {
 1588:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1589:     }
 1590: }
 1591: 
 1592: # -------------------------------------------- put items in domain db files 
 1593: 
 1594: sub put_dom {
 1595:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1596:     if (!$udom) {
 1597:         $udom=$env{'user.domain'};
 1598:         if (defined(&domain($udom,'primary'))) {
 1599:             $uhome=&domain($udom,'primary');
 1600:         } else {
 1601:             undef($uhome);
 1602:         }
 1603:     } else {
 1604:         if (!$uhome) {
 1605:             if (defined(&domain($udom,'primary'))) {
 1606:                 $uhome=&domain($udom,'primary');
 1607:             }
 1608:         }
 1609:     } 
 1610:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1611:         my $items='';
 1612:         foreach my $item (keys(%$storehash)) {
 1613:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1614:         }
 1615:         $items=~s/\&$//;
 1616:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1617:     } else {
 1618:         &logthis("put_dom failed - no homeserver and/or domain");
 1619:     }
 1620: }
 1621: 
 1622: # --------------------- newput for items in db file owned by domainconfig user
 1623: sub newput_dom {
 1624:     my ($namespace,$storehash,$udom) = @_;
 1625:     my $result;
 1626:     if (!$udom) {
 1627:         $udom=$env{'user.domain'};
 1628:     }
 1629:     if ($udom) {
 1630:         my $uname = &get_domainconfiguser($udom);
 1631:         $result = &newput($namespace,$storehash,$udom,$uname);
 1632:     }
 1633:     return $result;
 1634: }
 1635: 
 1636: # --------------------- delete for items in db file owned by domainconfig user
 1637: sub del_dom {
 1638:     my ($namespace,$storearr,$udom)=@_;
 1639:     if (ref($storearr) eq 'ARRAY') {
 1640:         if (!$udom) {
 1641:             $udom=$env{'user.domain'};
 1642:         }
 1643:         if ($udom) {
 1644:             my $uname = &get_domainconfiguser($udom); 
 1645:             return &del($namespace,$storearr,$udom,$uname);
 1646:         }
 1647:     }
 1648: }
 1649: 
 1650: # ----------------------------------construct domainconfig user for a domain 
 1651: sub get_domainconfiguser {
 1652:     my ($udom) = @_;
 1653:     return $udom.'-domainconfig';
 1654: }
 1655: 
 1656: sub retrieve_inst_usertypes {
 1657:     my ($udom) = @_;
 1658:     my (%returnhash,@order);
 1659:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1660:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1661:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1662:         %returnhash = %{$domdefs{'inststatustypes'}};
 1663:         @order = @{$domdefs{'inststatusorder'}};
 1664:     } else {
 1665:         if (defined(&domain($udom,'primary'))) {
 1666:             my $uhome=&domain($udom,'primary');
 1667:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1668:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1669:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1670:                 return (\%returnhash,\@order);
 1671:             }
 1672:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1673:             my @pairs=split(/\&/,$hashitems);
 1674:             foreach my $item (@pairs) {
 1675:                 my ($key,$value)=split(/=/,$item,2);
 1676:                 $key = &unescape($key);
 1677:                 next if ($key =~ /^error: 2 /);
 1678:                 $returnhash{$key}=&thaw_unescape($value);
 1679:             }
 1680:             my @esc_order = split(/\&/,$orderitems);
 1681:             foreach my $item (@esc_order) {
 1682:                 push(@order,&unescape($item));
 1683:             }
 1684:         } else {
 1685:             &logthis("get_dom failed - no primary domain server for $udom");
 1686:         }
 1687:     }
 1688:     return (\%returnhash,\@order);
 1689: }
 1690: 
 1691: sub is_domainimage {
 1692:     my ($url) = @_;
 1693:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1694:         if (&domain($1) ne '') {
 1695:             return '1';
 1696:         }
 1697:     }
 1698:     return;
 1699: }
 1700: 
 1701: sub inst_directory_query {
 1702:     my ($srch) = @_;
 1703:     my $udom = $srch->{'srchdomain'};
 1704:     my %results;
 1705:     my $homeserver = &domain($udom,'primary');
 1706:     my $outcome;
 1707:     if ($homeserver ne '') {
 1708: 	my $queryid=&reply("querysend:instdirsearch:".
 1709: 			   &escape($srch->{'srchby'}).':'.
 1710: 			   &escape($srch->{'srchterm'}).':'.
 1711: 			   &escape($srch->{'srchtype'}),$homeserver);
 1712: 	my $host=&hostname($homeserver);
 1713: 	if ($queryid !~/^\Q$host\E\_/) {
 1714: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1715: 	    return;
 1716: 	}
 1717: 	my $response = &get_query_reply($queryid);
 1718: 	my $maxtries = 5;
 1719: 	my $tries = 1;
 1720: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1721: 	    $response = &get_query_reply($queryid);
 1722: 	    $tries ++;
 1723: 	}
 1724: 
 1725:         if (!&error($response) && $response ne 'refused') {
 1726:             if ($response eq 'unavailable') {
 1727:                 $outcome = $response;
 1728:             } else {
 1729:                 $outcome = 'ok';
 1730:                 my @matches = split(/\n/,$response);
 1731:                 foreach my $match (@matches) {
 1732:                     my ($key,$value) = split(/=/,$match);
 1733:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1734:                 }
 1735:             }
 1736:         }
 1737:     }
 1738:     return ($outcome,%results);
 1739: }
 1740: 
 1741: sub usersearch {
 1742:     my ($srch) = @_;
 1743:     my $dom = $srch->{'srchdomain'};
 1744:     my %results;
 1745:     my %libserv = &all_library();
 1746:     my $query = 'usersearch';
 1747:     foreach my $tryserver (keys(%libserv)) {
 1748:         if (&host_domain($tryserver) eq $dom) {
 1749:             my $host=&hostname($tryserver);
 1750:             my $queryid=
 1751:                 &reply("querysend:".&escape($query).':'.
 1752:                        &escape($srch->{'srchby'}).':'.
 1753:                        &escape($srch->{'srchtype'}).':'.
 1754:                        &escape($srch->{'srchterm'}),$tryserver);
 1755:             if ($queryid !~/^\Q$host\E\_/) {
 1756:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1757:                 next;
 1758:             }
 1759:             my $reply = &get_query_reply($queryid);
 1760:             my $maxtries = 1;
 1761:             my $tries = 1;
 1762:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1763:                 $reply = &get_query_reply($queryid);
 1764:                 $tries ++;
 1765:             }
 1766:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1767:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1768:             } else {
 1769:                 my @matches;
 1770:                 if ($reply =~ /\n/) {
 1771:                     @matches = split(/\n/,$reply);
 1772:                 } else {
 1773:                     @matches = split(/\&/,$reply);
 1774:                 }
 1775:                 foreach my $match (@matches) {
 1776:                     my ($uname,$udom,%userhash);
 1777:                     foreach my $entry (split(/:/,$match)) {
 1778:                         my ($key,$value) =
 1779:                             map {&unescape($_);} split(/=/,$entry);
 1780:                         $userhash{$key} = $value;
 1781:                         if ($key eq 'username') {
 1782:                             $uname = $value;
 1783:                         } elsif ($key eq 'domain') {
 1784:                             $udom = $value;
 1785:                         }
 1786:                     }
 1787:                     $results{$uname.':'.$udom} = \%userhash;
 1788:                 }
 1789:             }
 1790:         }
 1791:     }
 1792:     return %results;
 1793: }
 1794: 
 1795: sub get_instuser {
 1796:     my ($udom,$uname,$id) = @_;
 1797:     my $homeserver = &domain($udom,'primary');
 1798:     my ($outcome,%results);
 1799:     if ($homeserver ne '') {
 1800:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1801:                            &escape($id).':'.&escape($udom),$homeserver);
 1802:         my $host=&hostname($homeserver);
 1803:         if ($queryid !~/^\Q$host\E\_/) {
 1804:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1805:             return;
 1806:         }
 1807:         my $response = &get_query_reply($queryid);
 1808:         my $maxtries = 5;
 1809:         my $tries = 1;
 1810:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1811:             $response = &get_query_reply($queryid);
 1812:             $tries ++;
 1813:         }
 1814:         if (!&error($response) && $response ne 'refused') {
 1815:             if ($response eq 'unavailable') {
 1816:                 $outcome = $response;
 1817:             } else {
 1818:                 $outcome = 'ok';
 1819:                 my @matches = split(/\n/,$response);
 1820:                 foreach my $match (@matches) {
 1821:                     my ($key,$value) = split(/=/,$match);
 1822:                     $results{&unescape($key)} = &thaw_unescape($value);
 1823:                 }
 1824:             }
 1825:         }
 1826:     }
 1827:     my %userinfo;
 1828:     if (ref($results{$uname}) eq 'HASH') {
 1829:         %userinfo = %{$results{$uname}};
 1830:     } 
 1831:     return ($outcome,%userinfo);
 1832: }
 1833: 
 1834: sub inst_rulecheck {
 1835:     my ($udom,$uname,$id,$item,$rules) = @_;
 1836:     my %returnhash;
 1837:     if ($udom ne '') {
 1838:         if (ref($rules) eq 'ARRAY') {
 1839:             @{$rules} = map {&escape($_);} (@{$rules});
 1840:             my $rulestr = join(':',@{$rules});
 1841:             my $homeserver=&domain($udom,'primary');
 1842:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1843:                 my $response;
 1844:                 if ($item eq 'username') {                
 1845:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1846:                                               ':'.&escape($uname).':'.$rulestr,
 1847:                                               $homeserver));
 1848:                 } elsif ($item eq 'id') {
 1849:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1850:                                               ':'.&escape($id).':'.$rulestr,
 1851:                                               $homeserver));
 1852:                 } elsif ($item eq 'selfcreate') {
 1853:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1854:                                                &escape($udom).':'.&escape($uname).
 1855:                                               ':'.$rulestr,$homeserver));
 1856:                 }
 1857:                 if ($response ne 'refused') {
 1858:                     my @pairs=split(/\&/,$response);
 1859:                     foreach my $item (@pairs) {
 1860:                         my ($key,$value)=split(/=/,$item,2);
 1861:                         $key = &unescape($key);
 1862:                         next if ($key =~ /^error: 2 /);
 1863:                         $returnhash{$key}=&thaw_unescape($value);
 1864:                     }
 1865:                 }
 1866:             }
 1867:         }
 1868:     }
 1869:     return %returnhash;
 1870: }
 1871: 
 1872: sub inst_userrules {
 1873:     my ($udom,$check) = @_;
 1874:     my (%ruleshash,@ruleorder);
 1875:     if ($udom ne '') {
 1876:         my $homeserver=&domain($udom,'primary');
 1877:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1878:             my $response;
 1879:             if ($check eq 'id') {
 1880:                 $response=&reply('instidrules:'.&escape($udom),
 1881:                                  $homeserver);
 1882:             } elsif ($check eq 'email') {
 1883:                 $response=&reply('instemailrules:'.&escape($udom),
 1884:                                  $homeserver);
 1885:             } else {
 1886:                 $response=&reply('instuserrules:'.&escape($udom),
 1887:                                  $homeserver);
 1888:             }
 1889:             if (($response ne 'refused') && ($response ne 'error') && 
 1890:                 ($response ne 'unknown_cmd') && 
 1891:                 ($response ne 'no_such_host')) {
 1892:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1893:                 my @pairs=split(/\&/,$hashitems);
 1894:                 foreach my $item (@pairs) {
 1895:                     my ($key,$value)=split(/=/,$item,2);
 1896:                     $key = &unescape($key);
 1897:                     next if ($key =~ /^error: 2 /);
 1898:                     $ruleshash{$key}=&thaw_unescape($value);
 1899:                 }
 1900:                 my @esc_order = split(/\&/,$orderitems);
 1901:                 foreach my $item (@esc_order) {
 1902:                     push(@ruleorder,&unescape($item));
 1903:                 }
 1904:             }
 1905:         }
 1906:     }
 1907:     return (\%ruleshash,\@ruleorder);
 1908: }
 1909: 
 1910: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1911: 
 1912: sub get_domain_defaults {
 1913:     my ($domain) = @_;
 1914:     my $cachetime = 60*60*24;
 1915:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1916:     if (defined($cached)) {
 1917:         if (ref($result) eq 'HASH') {
 1918:             return %{$result};
 1919:         }
 1920:     }
 1921:     my %domdefaults;
 1922:     my %domconfig =
 1923:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1924:                                   'requestcourses','inststatus',
 1925:                                   'coursedefaults','usersessions'],$domain);
 1926:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1927:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1928:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1929:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1930:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1931:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1932:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1933:     } else {
 1934:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1935:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1936:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1937:     }
 1938:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1939:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1940:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1941:         } else {
 1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1943:         } 
 1944:         my @usertools = ('aboutme','blog','portfolio');
 1945:         foreach my $item (@usertools) {
 1946:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1947:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1948:             }
 1949:         }
 1950:     }
 1951:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1952:         foreach my $item ('official','unofficial','community') {
 1953:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1954:         }
 1955:     }
 1956:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1957:         foreach my $item ('inststatustypes','inststatusorder') {
 1958:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1959:         }
 1960:     }
 1961:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1962:         foreach my $item ('canuse_pdfforms') {
 1963:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1964:         }
 1965:     }
 1966:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1967:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1968:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1969:         }
 1970:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1971:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1972:         }
 1973:     }
 1974:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1975:                                   $cachetime);
 1976:     return %domdefaults;
 1977: }
 1978: 
 1979: # --------------------------------------------------- Assign a key to a student
 1980: 
 1981: sub assign_access_key {
 1982: #
 1983: # a valid key looks like uname:udom#comments
 1984: # comments are being appended
 1985: #
 1986:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1987:     $kdom=
 1988:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1989:     $knum=
 1990:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1991:     $cdom=
 1992:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1993:     $cnum=
 1994:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1995:     $udom=$env{'user.name'} unless (defined($udom));
 1996:     $uname=$env{'user.domain'} unless (defined($uname));
 1997:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1998:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1999:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2000:                                                   # assigned to this person
 2001:                                                   # - this should not happen,
 2002:                                                   # unless something went wrong
 2003:                                                   # the first time around
 2004: # ready to assign
 2005:         $logentry=$1.'; '.$logentry;
 2006:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2007:                                                  $kdom,$knum) eq 'ok') {
 2008: # key now belongs to user
 2009: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2010:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2011:                 &appenv({'environment.'.$envkey => $ckey});
 2012:                 return 'ok';
 2013:             } else {
 2014:                 return 
 2015:   'error: Count not permanently assign key, will need to be re-entered later.';
 2016: 	    }
 2017:         } else {
 2018:             return 'error: Could not assign key, try again later.';
 2019:         }
 2020:     } elsif (!$existing{$ckey}) {
 2021: # the key does not exist
 2022: 	return 'error: The key does not exist';
 2023:     } else {
 2024: # the key is somebody else's
 2025: 	return 'error: The key is already in use';
 2026:     }
 2027: }
 2028: 
 2029: # ------------------------------------------ put an additional comment on a key
 2030: 
 2031: sub comment_access_key {
 2032: #
 2033: # a valid key looks like uname:udom#comments
 2034: # comments are being appended
 2035: #
 2036:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2037:     $cdom=
 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2039:     $cnum=
 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2041:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2042:     if ($existing{$ckey}) {
 2043:         $existing{$ckey}.='; '.$logentry;
 2044: # ready to assign
 2045:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2046:                                                  $cdom,$cnum) eq 'ok') {
 2047: 	    return 'ok';
 2048:         } else {
 2049: 	    return 'error: Count not store comment.';
 2050:         }
 2051:     } else {
 2052: # the key does not exist
 2053: 	return 'error: The key does not exist';
 2054:     }
 2055: }
 2056: 
 2057: # ------------------------------------------------------ Generate a set of keys
 2058: 
 2059: sub generate_access_keys {
 2060:     my ($number,$cdom,$cnum,$logentry)=@_;
 2061:     $cdom=
 2062:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2063:     $cnum=
 2064:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2065:     unless (&allowed('mky',$cdom)) { return 0; }
 2066:     unless (($cdom) && ($cnum)) { return 0; }
 2067:     if ($number>10000) { return 0; }
 2068:     sleep(2); # make sure don't get same seed twice
 2069:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2070:     my $total=0;
 2071:     for (my $i=1;$i<=$number;$i++) {
 2072:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2073:                   sprintf("%lx",int(100000*rand)).'-'.
 2074:                   sprintf("%lx",int(100000*rand));
 2075:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2076:        $newkey=~s/0/h/g; # and also 0 and O
 2077:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2078:        if ($existing{$newkey}) {
 2079:            $i--;
 2080:        } else {
 2081: 	  if (&put('accesskeys',
 2082:               { $newkey => '# generated '.localtime().
 2083:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2084:                            '; '.$logentry },
 2085: 		   $cdom,$cnum) eq 'ok') {
 2086:               $total++;
 2087: 	  }
 2088:        }
 2089:     }
 2090:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2091:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2092:     return $total;
 2093: }
 2094: 
 2095: # ------------------------------------------------------- Validate an accesskey
 2096: 
 2097: sub validate_access_key {
 2098:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2099:     $cdom=
 2100:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2101:     $cnum=
 2102:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2103:     $udom=$env{'user.domain'} unless (defined($udom));
 2104:     $uname=$env{'user.name'} unless (defined($uname));
 2105:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2106:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2107: }
 2108: 
 2109: # ------------------------------------- Find the section of student in a course
 2110: sub devalidate_getsection_cache {
 2111:     my ($udom,$unam,$courseid)=@_;
 2112:     my $hashid="$udom:$unam:$courseid";
 2113:     &devalidate_cache_new('getsection',$hashid);
 2114: }
 2115: 
 2116: sub courseid_to_courseurl {
 2117:     my ($courseid) = @_;
 2118:     #already url style courseid
 2119:     return $courseid if ($courseid =~ m{^/});
 2120: 
 2121:     if (exists($env{'course.'.$courseid.'.num'})) {
 2122: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2123: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2124: 	return "/$cdom/$cnum";
 2125:     }
 2126: 
 2127:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2128:     if (exists($courseinfo{'num'})) {
 2129: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2130:     }
 2131: 
 2132:     return undef;
 2133: }
 2134: 
 2135: sub getsection {
 2136:     my ($udom,$unam,$courseid)=@_;
 2137:     my $cachetime=1800;
 2138: 
 2139:     my $hashid="$udom:$unam:$courseid";
 2140:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2141:     if (defined($cached)) { return $result; }
 2142: 
 2143:     my %Pending; 
 2144:     my %Expired;
 2145:     #
 2146:     # Each role can either have not started yet (pending), be active, 
 2147:     #    or have expired.
 2148:     #
 2149:     # If there is an active role, we are done.
 2150:     #
 2151:     # If there is more than one role which has not started yet, 
 2152:     #     choose the one which will start sooner
 2153:     # If there is one role which has not started yet, return it.
 2154:     #
 2155:     # If there is more than one expired role, choose the one which ended last.
 2156:     # If there is a role which has expired, return it.
 2157:     #
 2158:     $courseid = &courseid_to_courseurl($courseid);
 2159:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2160:     foreach my $key (keys(%roleshash)) {
 2161:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2162:         my $section=$1;
 2163:         if ($key eq $courseid.'_st') { $section=''; }
 2164:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2165:         my $now=time;
 2166:         if (defined($end) && $end && ($now > $end)) {
 2167:             $Expired{$end}=$section;
 2168:             next;
 2169:         }
 2170:         if (defined($start) && $start && ($now < $start)) {
 2171:             $Pending{$start}=$section;
 2172:             next;
 2173:         }
 2174:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2175:     }
 2176:     #
 2177:     # Presumedly there will be few matching roles from the above
 2178:     # loop and the sorting time will be negligible.
 2179:     if (scalar(keys(%Pending))) {
 2180:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2181:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2182:     } 
 2183:     if (scalar(keys(%Expired))) {
 2184:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2185:         my $time = pop(@sorted);
 2186:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2187:     }
 2188:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2189: }
 2190: 
 2191: sub save_cache {
 2192:     &purge_remembered();
 2193:     #&Apache::loncommon::validate_page();
 2194:     undef(%env);
 2195:     undef($env_loaded);
 2196: }
 2197: 
 2198: my $to_remember=-1;
 2199: my %remembered;
 2200: my %accessed;
 2201: my $kicks=0;
 2202: my $hits=0;
 2203: sub make_key {
 2204:     my ($name,$id) = @_;
 2205:     if (length($id) > 65 
 2206: 	&& length(&escape($id)) > 200) {
 2207: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2208:     }
 2209:     return &escape($name.':'.$id);
 2210: }
 2211: 
 2212: sub devalidate_cache_new {
 2213:     my ($name,$id,$debug) = @_;
 2214:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2215:     $id=&make_key($name,$id);
 2216:     $memcache->delete($id);
 2217:     delete($remembered{$id});
 2218:     delete($accessed{$id});
 2219: }
 2220: 
 2221: sub is_cached_new {
 2222:     my ($name,$id,$debug) = @_;
 2223:     $id=&make_key($name,$id);
 2224:     if (exists($remembered{$id})) {
 2225: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2226: 	$accessed{$id}=[&gettimeofday()];
 2227: 	$hits++;
 2228: 	return ($remembered{$id},1);
 2229:     }
 2230:     my $value = $memcache->get($id);
 2231:     if (!(defined($value))) {
 2232: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2233: 	return (undef,undef);
 2234:     }
 2235:     if ($value eq '__undef__') {
 2236: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2237: 	$value=undef;
 2238:     }
 2239:     &make_room($id,$value,$debug);
 2240:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2241:     return ($value,1);
 2242: }
 2243: 
 2244: sub do_cache_new {
 2245:     my ($name,$id,$value,$time,$debug) = @_;
 2246:     $id=&make_key($name,$id);
 2247:     my $setvalue=$value;
 2248:     if (!defined($setvalue)) {
 2249: 	$setvalue='__undef__';
 2250:     }
 2251:     if (!defined($time) ) {
 2252: 	$time=600;
 2253:     }
 2254:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2255:     my $result = $memcache->set($id,$setvalue,$time);
 2256:     if (! $result) {
 2257: 	&logthis("caching of id -> $id  failed");
 2258: 	$memcache->disconnect_all();
 2259:     }
 2260:     # need to make a copy of $value
 2261:     &make_room($id,$value,$debug);
 2262:     return $value;
 2263: }
 2264: 
 2265: sub make_room {
 2266:     my ($id,$value,$debug)=@_;
 2267: 
 2268:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2269:                                     : $value;
 2270:     if ($to_remember<0) { return; }
 2271:     $accessed{$id}=[&gettimeofday()];
 2272:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2273:     my $to_kick;
 2274:     my $max_time=0;
 2275:     foreach my $other (keys(%accessed)) {
 2276: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2277: 	    $to_kick=$other;
 2278: 	    $max_time=&tv_interval($accessed{$other});
 2279: 	}
 2280:     }
 2281:     delete($remembered{$to_kick});
 2282:     delete($accessed{$to_kick});
 2283:     $kicks++;
 2284:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2285:     return;
 2286: }
 2287: 
 2288: sub purge_remembered {
 2289:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2290:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2291:     undef(%remembered);
 2292:     undef(%accessed);
 2293: }
 2294: # ------------------------------------- Read an entry from a user's environment
 2295: 
 2296: sub userenvironment {
 2297:     my ($udom,$unam,@what)=@_;
 2298:     my $items;
 2299:     foreach my $item (@what) {
 2300:         $items.=&escape($item).'&';
 2301:     }
 2302:     $items=~s/\&$//;
 2303:     my %returnhash=();
 2304:     my $uhome = &homeserver($unam,$udom);
 2305:     unless ($uhome eq 'no_host') {
 2306:         my @answer=split(/\&/, 
 2307:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2308:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2309:             return %returnhash;
 2310:         }
 2311:         my $i;
 2312:         for ($i=0;$i<=$#what;$i++) {
 2313: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2314:         }
 2315:     }
 2316:     return %returnhash;
 2317: }
 2318: 
 2319: # ---------------------------------------------------------- Get a studentphoto
 2320: sub studentphoto {
 2321:     my ($udom,$unam,$ext) = @_;
 2322:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2323:     if (defined($env{'request.course.id'})) {
 2324:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2325:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2326:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2327:             } else {
 2328:                 my ($result,$perm_reqd)=
 2329: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2330:                 if ($result eq 'ok') {
 2331:                     if (!($perm_reqd eq 'yes')) {
 2332:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2333:                     }
 2334:                 }
 2335:             }
 2336:         }
 2337:     } else {
 2338:         my ($result,$perm_reqd) = 
 2339: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2340:         if ($result eq 'ok') {
 2341:             if (!($perm_reqd eq 'yes')) {
 2342:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2343:             }
 2344:         }
 2345:     }
 2346:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2347: }
 2348: 
 2349: sub retrievestudentphoto {
 2350:     my ($udom,$unam,$ext,$type) = @_;
 2351:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2352:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2353:     if ($ret eq 'ok') {
 2354:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2355:         if ($type eq 'thumbnail') {
 2356:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2357:         }
 2358:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2359:         return $tokenurl;
 2360:     } else {
 2361:         if ($type eq 'thumbnail') {
 2362:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2363:         } else { 
 2364:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2365:         }
 2366:     }
 2367: }
 2368: 
 2369: # -------------------------------------------------------------------- New chat
 2370: 
 2371: sub chatsend {
 2372:     my ($newentry,$anon,$group)=@_;
 2373:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2375:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2376:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2377: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2378: 		   &escape($newentry)).':'.$group,$chome);
 2379: }
 2380: 
 2381: # ------------------------------------------ Find current version of a resource
 2382: 
 2383: sub getversion {
 2384:     my $fname=&clutter(shift);
 2385:     unless ($fname=~/^\/res\//) { return -1; }
 2386:     return &currentversion(&filelocation('',$fname));
 2387: }
 2388: 
 2389: sub currentversion {
 2390:     my $fname=shift;
 2391:     my $author=$fname;
 2392:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2393:     my ($udom,$uname)=split(/\//,$author);
 2394:     my $home=&homeserver($uname,$udom);
 2395:     if ($home eq 'no_host') { 
 2396:         return -1; 
 2397:     }
 2398:     my $answer=&reply("currentversion:$fname",$home);
 2399:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2400: 	return -1;
 2401:     }
 2402:     return $answer;
 2403: }
 2404: 
 2405: #
 2406: # Return special version number of resource if set by override, empty otherwise
 2407: #
 2408: sub usedversion {
 2409:     my $fname=shift;
 2410:     unless ($fname) { $fname=$env{'request.uri'}; }
 2411:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2412:     if ($urlversion) { return $urlversion; }
 2413:     return '';
 2414: }
 2415: 
 2416: # ----------------------------- Subscribe to a resource, return URL if possible
 2417: 
 2418: sub subscribe {
 2419:     my $fname=shift;
 2420:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2421:     $fname=~s/[\n\r]//g;
 2422:     my $author=$fname;
 2423:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2424:     my ($udom,$uname)=split(/\//,$author);
 2425:     my $home=homeserver($uname,$udom);
 2426:     if ($home eq 'no_host') {
 2427:         return 'not_found';
 2428:     }
 2429:     my $answer=reply("sub:$fname",$home);
 2430:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2431: 	$answer.=' by '.$home;
 2432:     }
 2433:     return $answer;
 2434: }
 2435:     
 2436: # -------------------------------------------------------------- Replicate file
 2437: 
 2438: sub repcopy {
 2439:     my $filename=shift;
 2440:     $filename=~s/\/+/\//g;
 2441:     my $londocroot = $perlvar{'lonDocRoot'};
 2442:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2443:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2444:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2445: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2446: 	return &repcopy_userfile($filename);
 2447:     }
 2448:     $filename=~s/[\n\r]//g;
 2449:     my $transname="$filename.in.transfer";
 2450: # FIXME: this should flock
 2451:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2452:     my $remoteurl=subscribe($filename);
 2453:     if ($remoteurl =~ /^con_lost by/) {
 2454: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2455:            return 'unavailable';
 2456:     } elsif ($remoteurl eq 'not_found') {
 2457: 	   #&logthis("Subscribe returned not_found: $filename");
 2458: 	   return 'not_found';
 2459:     } elsif ($remoteurl =~ /^rejected by/) {
 2460: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2461:            return 'forbidden';
 2462:     } elsif ($remoteurl eq 'directory') {
 2463:            return 'ok';
 2464:     } else {
 2465:         my $author=$filename;
 2466:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2467:         my ($udom,$uname)=split(/\//,$author);
 2468:         my $home=homeserver($uname,$udom);
 2469:         unless ($home eq $perlvar{'lonHostID'}) {
 2470:            my @parts=split(/\//,$filename);
 2471:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2472:            if ($path ne "$londocroot/res") {
 2473:                &logthis("Malconfiguration for replication: $filename");
 2474: 	       return 'bad_request';
 2475:            }
 2476:            my $count;
 2477:            for ($count=5;$count<$#parts;$count++) {
 2478:                $path.="/$parts[$count]";
 2479:                if ((-e $path)!=1) {
 2480: 		   mkdir($path,0777);
 2481:                }
 2482:            }
 2483:            my $ua=new LWP::UserAgent;
 2484:            my $request=new HTTP::Request('GET',"$remoteurl");
 2485:            my $response=$ua->request($request,$transname);
 2486:            if ($response->is_error()) {
 2487: 	       unlink($transname);
 2488:                my $message=$response->status_line;
 2489:                &logthis("<font color=\"blue\">WARNING:"
 2490:                        ." LWP get: $message: $filename</font>");
 2491:                return 'unavailable';
 2492:            } else {
 2493: 	       if ($remoteurl!~/\.meta$/) {
 2494:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2495:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2496:                   if ($mresponse->is_error()) {
 2497: 		      unlink($filename.'.meta');
 2498:                       &logthis(
 2499:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2500:                   }
 2501: 	       }
 2502:                rename($transname,$filename);
 2503:                return 'ok';
 2504:            }
 2505:        }
 2506:     }
 2507: }
 2508: 
 2509: # ------------------------------------------------ Get server side include body
 2510: sub ssi_body {
 2511:     my ($filelink,%form)=@_;
 2512:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2513:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2514:     }
 2515:     my $output='';
 2516:     my $response;
 2517:     if ($filelink=~/^https?\:/) {
 2518:        ($output,$response)=&externalssi($filelink);
 2519:     } else {
 2520:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2521:        $filelink .= 'inhibitmenu=yes';
 2522:        ($output,$response)=&ssi($filelink,%form);
 2523:     }
 2524:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2525:     $output=~s/^.*?\<body[^\>]*\>//si;
 2526:     $output=~s/\<\/body\s*\>.*?$//si;
 2527:     if (wantarray) {
 2528:         return ($output, $response);
 2529:     } else {
 2530:         return $output;
 2531:     }
 2532: }
 2533: 
 2534: # --------------------------------------------------------- Server Side Include
 2535: 
 2536: sub absolute_url {
 2537:     my ($host_name) = @_;
 2538:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2539:     if ($host_name eq '') {
 2540: 	$host_name = $ENV{'SERVER_NAME'};
 2541:     }
 2542:     return $protocol.$host_name;
 2543: }
 2544: 
 2545: #
 2546: #   Server side include.
 2547: # Parameters:
 2548: #  fn     Possibly encrypted resource name/id.
 2549: #  form   Hash that describes how the rendering should be done
 2550: #         and other things.
 2551: # Returns:
 2552: #   Scalar context: The content of the response.
 2553: #   Array context:  2 element list of the content and the full response object.
 2554: #     
 2555: sub ssi {
 2556: 
 2557:     my ($fn,%form)=@_;
 2558:     my $ua=new LWP::UserAgent;
 2559:     my $request;
 2560: 
 2561:     $form{'no_update_last_known'}=1;
 2562:     &Apache::lonenc::check_encrypt(\$fn);
 2563:     if (%form) {
 2564:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2565:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2566:     } else {
 2567:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2568:     }
 2569: 
 2570:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2571:     my $response=$ua->request($request);
 2572: 
 2573:     if (wantarray) {
 2574: 	return ($response->content, $response);
 2575:     } else {
 2576: 	return $response->content;
 2577:     }
 2578: }
 2579: 
 2580: sub externalssi {
 2581:     my ($url)=@_;
 2582:     my $ua=new LWP::UserAgent;
 2583:     my $request=new HTTP::Request('GET',$url);
 2584:     my $response=$ua->request($request);
 2585:     if (wantarray) {
 2586:         return ($response->content, $response);
 2587:     } else {
 2588:         return $response->content;
 2589:     }
 2590: }
 2591: 
 2592: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2593: 
 2594: sub allowuploaded {
 2595:     my ($srcurl,$url)=@_;
 2596:     $url=&clutter(&declutter($url));
 2597:     my $dir=$url;
 2598:     $dir=~s/\/[^\/]+$//;
 2599:     my %httpref=();
 2600:     my $httpurl=&hreflocation('',$url);
 2601:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2602:     &Apache::lonnet::appenv(\%httpref);
 2603: }
 2604: 
 2605: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2606: # input: action, courseID, current domain, intended
 2607: #        path to file, source of file, instruction to parse file for objects,
 2608: #        ref to hash for embedded objects,
 2609: #        ref to hash for codebase of java objects.
 2610: #        reference to scalar to accommodate mime type determined
 2611: #          from File::MMagic if $parser = parse.
 2612: #
 2613: # output: url to file (if action was uploaddoc), 
 2614: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2615: #
 2616: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2617: # course.
 2618: #
 2619: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2620: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2621: #          course's home server.
 2622: #
 2623: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2624: #          be copied from $source (current location) to 
 2625: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2626: #         and will then be copied to
 2627: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2628: #         course's home server.
 2629: #
 2630: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2631: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2632: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2633: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2634: #         in course's home server.
 2635: #
 2636: 
 2637: sub process_coursefile {
 2638:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2639:         $mimetype)=@_;
 2640:     my $fetchresult;
 2641:     my $home=&homeserver($docuname,$docudom);
 2642:     if ($action eq 'propagate') {
 2643:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2644: 			     $home);
 2645:     } else {
 2646:         my $fpath = '';
 2647:         my $fname = $file;
 2648:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2649:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2650:         my $filepath = &build_filepath($fpath);
 2651:         if ($action eq 'copy') {
 2652:             if ($source eq '') {
 2653:                 $fetchresult = 'no source file';
 2654:                 return $fetchresult;
 2655:             } else {
 2656:                 my $destination = $filepath.'/'.$fname;
 2657:                 rename($source,$destination);
 2658:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2659:                                  $home);
 2660:             }
 2661:         } elsif ($action eq 'uploaddoc') {
 2662:             open(my $fh,'>'.$filepath.'/'.$fname);
 2663:             print $fh $env{'form.'.$source};
 2664:             close($fh);
 2665:             if ($parser eq 'parse') {
 2666:                 my $mm = new File::MMagic;
 2667:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2668:                 if ($type eq 'text/html') {
 2669:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2670:                     unless ($parse_result eq 'ok') {
 2671:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2672:                     }
 2673:                 }
 2674:                 if (ref($mimetype)) {
 2675:                     $$mimetype = $type;
 2676:                 } 
 2677:             }
 2678:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2679:                                  $home);
 2680:             if ($fetchresult eq 'ok') {
 2681:                 return '/uploaded/'.$fpath.'/'.$fname;
 2682:             } else {
 2683:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2684:                         ' to host '.$home.': '.$fetchresult);
 2685:                 return '/adm/notfound.html';
 2686:             }
 2687:         }
 2688:     }
 2689:     unless ( $fetchresult eq 'ok') {
 2690:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2691:              ' to host '.$home.': '.$fetchresult);
 2692:     }
 2693:     return $fetchresult;
 2694: }
 2695: 
 2696: sub build_filepath {
 2697:     my ($fpath) = @_;
 2698:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2699:     unless ($fpath eq '') {
 2700:         my @parts=split('/',$fpath);
 2701:         foreach my $part (@parts) {
 2702:             $filepath.= '/'.$part;
 2703:             if ((-e $filepath)!=1) {
 2704:                 mkdir($filepath,0777);
 2705:             }
 2706:         }
 2707:     }
 2708:     return $filepath;
 2709: }
 2710: 
 2711: sub store_edited_file {
 2712:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2713:     my $file = $primary_url;
 2714:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2715:     my $fpath = '';
 2716:     my $fname = $file;
 2717:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2718:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2719:     my $filepath = &build_filepath($fpath);
 2720:     open(my $fh,'>'.$filepath.'/'.$fname);
 2721:     print $fh $content;
 2722:     close($fh);
 2723:     my $home=&homeserver($docuname,$docudom);
 2724:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2725: 			  $home);
 2726:     if ($$fetchresult eq 'ok') {
 2727:         return '/uploaded/'.$fpath.'/'.$fname;
 2728:     } else {
 2729:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2730: 		 ' to host '.$home.': '.$$fetchresult);
 2731:         return '/adm/notfound.html';
 2732:     }
 2733: }
 2734: 
 2735: sub clean_filename {
 2736:     my ($fname,$args)=@_;
 2737: # Replace Windows backslashes by forward slashes
 2738:     $fname=~s/\\/\//g;
 2739:     if (!$args->{'keep_path'}) {
 2740:         # Get rid of everything but the actual filename
 2741: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2742:     }
 2743: # Replace spaces by underscores
 2744:     $fname=~s/\s+/\_/g;
 2745: # Replace all other weird characters by nothing
 2746:     $fname=~s{[^/\w\.\-]}{}g;
 2747: # Replace all .\d. sequences with _\d. so they no longer look like version
 2748: # numbers
 2749:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2750:     return $fname;
 2751: }
 2752: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2753: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2754: # image with the same aspect ratio as the original, but with dimensions which do 
 2755: # not exceed $resizewidth and $resizeheight.
 2756:  
 2757: sub resizeImage {
 2758:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2759:     my $ima = Image::Magick->new;
 2760:     my $resized;
 2761:     if (-e $img_path) {
 2762:         $ima->Read($img_path);
 2763:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2764:             my $width = $ima->Get('width');
 2765:             my $height = $ima->Get('height');
 2766:             if ($width > $resizewidth) {
 2767: 	        my $factor = $width/$resizewidth;
 2768:                 my $newheight = $height/$factor;
 2769:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2770:                 $resized = 1;
 2771:             }
 2772:         }
 2773:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2774:             my $width = $ima->Get('width');
 2775:             my $height = $ima->Get('height');
 2776:             if ($height > $resizeheight) {
 2777:                 my $factor = $height/$resizeheight;
 2778:                 my $newwidth = $width/$factor;
 2779:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2780:                 $resized = 1;
 2781:             }
 2782:         }
 2783:         if ($resized) {
 2784:             $ima->Write($img_path);
 2785:         }
 2786:     }
 2787:     return;
 2788: }
 2789: 
 2790: # --------------- Take an uploaded file and put it into the userfiles directory
 2791: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2792: #                    the desired filename is in $env{"form.$formname.filename"}
 2793: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2794: #                                    canceloverwrite, or ''. 
 2795: #                   if 'coursedoc': upload to the current course
 2796: #                   if 'existingfile': write file to tmp/overwrites directory 
 2797: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2798: #                   $context is passed as argument to &finishuserfileupload
 2799: #        $subdir - directory in userfile to store the file into
 2800: #        $parser - instruction to parse file for objects ($parser = parse)    
 2801: #        $allfiles - reference to hash for embedded objects
 2802: #        $codebase - reference to hash for codebase of java objects
 2803: #        $desuname - username for permanent storage of uploaded file
 2804: #        $dsetudom - domain for permanaent storage of uploaded file
 2805: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2806: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2807: #        $resizewidth - width (pixels) to which to resize uploaded image
 2808: #        $resizeheight - height (pixels) to which to resize uploaded image
 2809: #        $mimetype - reference to scalar to accommodate mime type determined
 2810: #                    from File::MMagic.
 2811: # 
 2812: # output: url of file in userspace, or error: <message> 
 2813: #             or /adm/notfound.html if failure to upload occurse
 2814: 
 2815: sub userfileupload {
 2816:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2817:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2818:     if (!defined($subdir)) { $subdir='unknown'; }
 2819:     my $fname=$env{'form.'.$formname.'.filename'};
 2820:     $fname=&clean_filename($fname);
 2821:     # See if there is anything left
 2822:     unless ($fname) { return 'error: no uploaded file'; }
 2823:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2824:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2825:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2826:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2827:         my $now = time;
 2828:         my $filepath;
 2829:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2830:              $filepath = 'tmp/helprequests/'.$now;
 2831:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2832:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2833:                          '_'.$env{'user.domain'}.'/pending';
 2834:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2835:             my ($docuname,$docudom);
 2836:             if ($destudom) {
 2837:                 $docudom = $destudom;
 2838:             } else {
 2839:                 $docudom = $env{'user.domain'};
 2840:             }
 2841:             if ($destuname) {
 2842:                 $docuname = $destuname;
 2843:             } else {
 2844:                 $docuname = $env{'user.name'};
 2845:             }
 2846:             if (exists($env{'form.group'})) {
 2847:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2848:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2849:             }
 2850:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2851:             if ($context eq 'canceloverwrite') {
 2852:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2853:                 if (-e  $tempfile) {
 2854:                     my @info = stat($tempfile);
 2855:                     if ($info[9] eq $env{'form.timestamp'}) {
 2856:                         unlink($tempfile);
 2857:                     }
 2858:                 }
 2859:                 return;
 2860:             }
 2861:         }
 2862:         # Create the directory if not present
 2863:         my @parts=split(/\//,$filepath);
 2864:         my $fullpath = $perlvar{'lonDaemons'};
 2865:         for (my $i=0;$i<@parts;$i++) {
 2866:             $fullpath .= '/'.$parts[$i];
 2867:             if ((-e $fullpath)!=1) {
 2868:                 mkdir($fullpath,0777);
 2869:             }
 2870:         }
 2871:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2872:         print $fh $env{'form.'.$formname};
 2873:         close($fh);
 2874:         if ($context eq 'existingfile') {
 2875:             my @info = stat($fullpath.'/'.$fname);
 2876:             return ($fullpath.'/'.$fname,$info[9]);
 2877:         } else {
 2878:             return $fullpath.'/'.$fname;
 2879:         }
 2880:     }
 2881:     if ($subdir eq 'scantron') {
 2882:         $fname = 'scantron_orig_'.$fname;
 2883:     } else {
 2884:         $fname="$subdir/$fname";
 2885:     }
 2886:     if ($context eq 'coursedoc') {
 2887: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2888: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2889:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2890:             return &finishuserfileupload($docuname,$docudom,
 2891: 					 $formname,$fname,$parser,$allfiles,
 2892: 					 $codebase,$thumbwidth,$thumbheight,
 2893:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2894:         } else {
 2895:             $fname=$env{'form.folder'}.'/'.$fname;
 2896:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2897: 				       $fname,$formname,$parser,
 2898: 				       $allfiles,$codebase,$mimetype);
 2899:         }
 2900:     } elsif (defined($destuname)) {
 2901:         my $docuname=$destuname;
 2902:         my $docudom=$destudom;
 2903: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2904: 				     $parser,$allfiles,$codebase,
 2905:                                      $thumbwidth,$thumbheight,
 2906:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2907:     } else {
 2908:         my $docuname=$env{'user.name'};
 2909:         my $docudom=$env{'user.domain'};
 2910:         if (exists($env{'form.group'})) {
 2911:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2912:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2913:         }
 2914: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2915: 				     $parser,$allfiles,$codebase,
 2916:                                      $thumbwidth,$thumbheight,
 2917:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2918:     }
 2919: }
 2920: 
 2921: sub finishuserfileupload {
 2922:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2923:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2924:     my $path=$docudom.'/'.$docuname.'/';
 2925:     my $filepath=$perlvar{'lonDocRoot'};
 2926:   
 2927:     my ($fnamepath,$file,$fetchthumb);
 2928:     $file=$fname;
 2929:     if ($fname=~m|/|) {
 2930:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2931: 	$path.=$fnamepath.'/';
 2932:     }
 2933:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2934:     my $count;
 2935:     for ($count=4;$count<=$#parts;$count++) {
 2936:         $filepath.="/$parts[$count]";
 2937:         if ((-e $filepath)!=1) {
 2938: 	    mkdir($filepath,0777);
 2939:         }
 2940:     }
 2941: 
 2942: # Save the file
 2943:     {
 2944: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2945: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2946: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2947: 	    return '/adm/notfound.html';
 2948: 	}
 2949:         if ($context eq 'overwrite') {
 2950:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2951:             my $target = $filepath.'/'.$file;
 2952:             if (-e $source) {
 2953:                 my @info = stat($source);
 2954:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2955:                     unless (&File::Copy::move($source,$target)) {
 2956:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2957:                         return "Moving from $source failed";
 2958:                     }
 2959:                 } else {
 2960:                     return "Temporary file: $source had unexpected date/time for last modification";
 2961:                 }
 2962:             } else {
 2963:                 return "Temporary file: $source missing";
 2964:             }
 2965:         } elsif (!print FH ($env{'form.'.$formname})) {
 2966: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2967: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2968: 	    return '/adm/notfound.html';
 2969: 	}
 2970: 	close(FH);
 2971:         if ($resizewidth && $resizeheight) {
 2972:             my $mm = new File::MMagic;
 2973:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2974:             if ($mime_type =~ m{^image/}) {
 2975: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2976:             }  
 2977: 	}
 2978:     }
 2979:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2980:         if (ref($mimetype)) {
 2981:             if ($$mimetype eq '') {
 2982:                 my $mm = new File::MMagic;
 2983:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2984:                 $$mimetype = $type;
 2985:             }
 2986:         }
 2987:     }
 2988:     if ($parser eq 'parse') {
 2989:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2990:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2991:                                                        $allfiles,$codebase);
 2992:             unless ($parse_result eq 'ok') {
 2993:                 &logthis('Failed to parse '.$filepath.$file.
 2994: 	   	         ' for embedded media: '.$parse_result); 
 2995:             }
 2996:         }
 2997:     }
 2998:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2999:         my $input = $filepath.'/'.$file;
 3000:         my $output = $filepath.'/'.'tn-'.$file;
 3001:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3002:         system("convert -sample $thumbsize $input $output");
 3003:         if (-e $filepath.'/'.'tn-'.$file) {
 3004:             $fetchthumb  = 1; 
 3005:         }
 3006:     }
 3007:  
 3008: # Notify homeserver to grep it
 3009: #
 3010:     my $docuhome=&homeserver($docuname,$docudom);	
 3011:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3012:     if ($fetchresult eq 'ok') {
 3013:         if ($fetchthumb) {
 3014:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3015:             if ($thumbresult ne 'ok') {
 3016:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3017:                          $docuhome.': '.$thumbresult);
 3018:             }
 3019:         }
 3020: #
 3021: # Return the URL to it
 3022:         return '/uploaded/'.$path.$file;
 3023:     } else {
 3024:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3025: 		 ': '.$fetchresult);
 3026:         return '/adm/notfound.html';
 3027:     }
 3028: }
 3029: 
 3030: sub extract_embedded_items {
 3031:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3032:     my @state = ();
 3033:     my (%lastids,%related,%shockwave,%flashvars);
 3034:     my %javafiles = (
 3035:                       codebase => '',
 3036:                       code => '',
 3037:                       archive => ''
 3038:                     );
 3039:     my %mediafiles = (
 3040:                       src => '',
 3041:                       movie => '',
 3042:                      );
 3043:     my $p;
 3044:     if ($content) {
 3045:         $p = HTML::LCParser->new($content);
 3046:     } else {
 3047:         $p = HTML::LCParser->new($fullpath);
 3048:     }
 3049:     while (my $t=$p->get_token()) {
 3050: 	if ($t->[0] eq 'S') {
 3051: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3052: 	    push(@state, $tagname);
 3053:             if (lc($tagname) eq 'allow') {
 3054:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3055:             }
 3056: 	    if (lc($tagname) eq 'img') {
 3057: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3058: 	    }
 3059: 	    if (lc($tagname) eq 'a') {
 3060: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3061: 	    }
 3062:             if (lc($tagname) eq 'script') {
 3063:                 my $src;
 3064:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3065:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3066:                 } else {
 3067:                     if ($attr->{'src'} ne '') {
 3068:                         $src = $attr->{'src'};
 3069:                         &add_filetype($allfiles,$src,'src');
 3070:                     }
 3071:                 }
 3072:                 my $text = $p->get_trimmed_text();
 3073:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3074:                     my @swfargs = split(/,/,$1);
 3075:                     foreach my $item (@swfargs) {
 3076:                         $item =~ s/["']//g;
 3077:                         $item =~ s/^\s+//;
 3078:                         $item =~ s/\s+$//;
 3079:                     }
 3080:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3081:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3082:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3083:                         } else {
 3084:                             $related{$swfargs[0]} = [$swfargs[2]];
 3085:                         }
 3086:                     }
 3087:                 }
 3088:             }
 3089:             if (lc($tagname) eq 'link') {
 3090:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3091:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3092:                 }
 3093:             }
 3094: 	    if (lc($tagname) eq 'object' ||
 3095: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3096: 		foreach my $item (keys(%javafiles)) {
 3097: 		    $javafiles{$item} = '';
 3098: 		}
 3099:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3100:                     $lastids{lc($tagname)} = $attr->{'id'};
 3101:                 }
 3102: 	    }
 3103: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3104: 		my $name = lc($attr->{'name'});
 3105: 		foreach my $item (keys(%javafiles)) {
 3106: 		    if ($name eq $item) {
 3107: 			$javafiles{$item} = $attr->{'value'};
 3108: 			last;
 3109: 		    }
 3110: 		}
 3111:                 my $pathfrom;
 3112: 		foreach my $item (keys(%mediafiles)) {
 3113: 		    if ($name eq $item) {
 3114:                         $pathfrom = $attr->{'value'};
 3115:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3116: 			&add_filetype($allfiles,$pathfrom,$name);
 3117: 			last;
 3118: 		    }
 3119: 		}
 3120:                 if ($name eq 'flashvars') {
 3121:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3122:                 }
 3123:                 if ($pathfrom ne '') {
 3124:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3125:                                          $pathfrom);
 3126:                 }
 3127: 	    }
 3128: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3129: 		foreach my $item (keys(%javafiles)) {
 3130: 		    if ($attr->{$item}) {
 3131: 			$javafiles{$item} = $attr->{$item};
 3132: 			last;
 3133: 		    }
 3134: 		}
 3135: 		foreach my $item (keys(%mediafiles)) {
 3136: 		    if ($attr->{$item}) {
 3137: 			&add_filetype($allfiles,$attr->{$item},$item);
 3138: 			last;
 3139: 		    }
 3140: 		}
 3141:                 if (lc($tagname) eq 'embed') {
 3142:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3143:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3144:                                              $attr->{'src'});
 3145:                     }
 3146:                 }
 3147: 	    }
 3148:             if ($t->[4] =~ m{/>$}) {
 3149:                 pop(@state);  
 3150:             }
 3151: 	} elsif ($t->[0] eq 'E') {
 3152: 	    my ($tagname) = ($t->[1]);
 3153: 	    if ($javafiles{'codebase'} ne '') {
 3154: 		$javafiles{'codebase'} .= '/';
 3155: 	    }  
 3156: 	    if (lc($tagname) eq 'applet' ||
 3157: 		lc($tagname) eq 'object' ||
 3158: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3159: 		) {
 3160: 		foreach my $item (keys(%javafiles)) {
 3161: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3162: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3163: 			&add_filetype($allfiles,$file,$item);
 3164: 		    }
 3165: 		}
 3166: 	    } 
 3167: 	    pop @state;
 3168: 	}
 3169:     }
 3170:     foreach my $id (sort(keys(%flashvars))) {
 3171:         if ($shockwave{$id} ne '') {
 3172:             my @pairs = split(/\&/,$flashvars{$id});
 3173:             foreach my $pair (@pairs) {
 3174:                 my ($key,$value) = split(/\=/,$pair);
 3175:                 if ($key eq 'thumb') {
 3176:                     &add_filetype($allfiles,$value,$key);
 3177:                 } elsif ($key eq 'content') {
 3178:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3179:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3180:                     if ($ext ne '') {
 3181:                         &add_filetype($allfiles,$path.$value,$ext);
 3182:                     }
 3183:                 }
 3184:             }
 3185:         }
 3186:     }
 3187:     return 'ok';
 3188: }
 3189: 
 3190: sub add_filetype {
 3191:     my ($allfiles,$file,$type)=@_;
 3192:     if (exists($allfiles->{$file})) {
 3193: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3194: 	    push(@{$allfiles->{$file}}, &escape($type));
 3195: 	}
 3196:     } else {
 3197: 	@{$allfiles->{$file}} = (&escape($type));
 3198:     }
 3199: }
 3200: 
 3201: sub embedded_dependency {
 3202:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3203:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3204:         if (($identifier ne '') &&
 3205:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3206:             ($pathfrom ne '')) {
 3207:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3208:             foreach my $dep (@{$related->{$identifier}}) {
 3209:                 &add_filetype($allfiles,$path.$dep,'object');
 3210:             }
 3211:         }
 3212:     }
 3213:     return;
 3214: }
 3215: 
 3216: sub removeuploadedurl {
 3217:     my ($url)=@_;	
 3218:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3219:     return &removeuserfile($uname,$udom,$fname);
 3220: }
 3221: 
 3222: sub removeuserfile {
 3223:     my ($docuname,$docudom,$fname)=@_;
 3224:     my $home=&homeserver($docuname,$docudom);    
 3225:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3226:     if ($result eq 'ok') {	
 3227:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3228:             my $metafile = $fname.'.meta';
 3229:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3230: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3231:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3232:             my $sqlresult = 
 3233:                 &update_portfolio_table($docuname,$docudom,$file,
 3234:                                         'portfolio_metadata',$group,
 3235:                                         'delete');
 3236:         }
 3237:     }
 3238:     return $result;
 3239: }
 3240: 
 3241: sub mkdiruserfile {
 3242:     my ($docuname,$docudom,$dir)=@_;
 3243:     my $home=&homeserver($docuname,$docudom);
 3244:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3245: }
 3246: 
 3247: sub renameuserfile {
 3248:     my ($docuname,$docudom,$old,$new)=@_;
 3249:     my $home=&homeserver($docuname,$docudom);
 3250:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3251:                         &escape("$old").':'.&escape("$new"),$home);
 3252:     if ($result eq 'ok') {
 3253:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3254:             my $oldmeta = $old.'.meta';
 3255:             my $newmeta = $new.'.meta';
 3256:             my $metaresult = 
 3257:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3258: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3259:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3260:             my $sqlresult = 
 3261:                 &update_portfolio_table($docuname,$docudom,$file,
 3262:                                         'portfolio_metadata',$group,
 3263:                                         'delete');
 3264:         }
 3265:     }
 3266:     return $result;
 3267: }
 3268: 
 3269: # ------------------------------------------------------------------------- Log
 3270: 
 3271: sub log {
 3272:     my ($dom,$nam,$hom,$what)=@_;
 3273:     return critical("log:$dom:$nam:$what",$hom);
 3274: }
 3275: 
 3276: # ------------------------------------------------------------------ Course Log
 3277: #
 3278: # This routine flushes several buffers of non-mission-critical nature
 3279: #
 3280: 
 3281: sub flushcourselogs {
 3282:     &logthis('Flushing log buffers');
 3283: #
 3284: # course logs
 3285: # This is a log of all transactions in a course, which can be used
 3286: # for data mining purposes
 3287: #
 3288: # It also collects the courseid database, which lists last transaction
 3289: # times and course titles for all courseids
 3290: #
 3291:     my %courseidbuffer=();
 3292:     foreach my $crsid (keys(%courselogs)) {
 3293:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3294: 		          &escape($courselogs{$crsid}),
 3295: 		          $coursehombuf{$crsid}) eq 'ok') {
 3296: 	    delete $courselogs{$crsid};
 3297:         } else {
 3298:             &logthis('Failed to flush log buffer for '.$crsid);
 3299:             if (length($courselogs{$crsid})>40000) {
 3300:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3301:                         " exceeded maximum size, deleting.</font>");
 3302:                delete $courselogs{$crsid};
 3303:             }
 3304:         }
 3305:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3306:             'description' => $coursedescrbuf{$crsid},
 3307:             'inst_code'    => $courseinstcodebuf{$crsid},
 3308:             'type'        => $coursetypebuf{$crsid},
 3309:             'owner'       => $courseownerbuf{$crsid},
 3310:         };
 3311:     }
 3312: #
 3313: # Write course id database (reverse lookup) to homeserver of courses 
 3314: # Is used in pickcourse
 3315: #
 3316:     foreach my $crs_home (keys(%courseidbuffer)) {
 3317:         my $response = &courseidput(&host_domain($crs_home),
 3318:                                     $courseidbuffer{$crs_home},
 3319:                                     $crs_home,'timeonly');
 3320:     }
 3321: #
 3322: # File accesses
 3323: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3324: #
 3325:     foreach my $entry (keys(%accesshash)) {
 3326:         if ($entry =~ /___count$/) {
 3327:             my ($dom,$name);
 3328:             ($dom,$name,undef)=
 3329: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3330:             if (! defined($dom) || $dom eq '' || 
 3331:                 ! defined($name) || $name eq '') {
 3332:                 my $cid = $env{'request.course.id'};
 3333:                 $dom  = $env{'request.'.$cid.'.domain'};
 3334:                 $name = $env{'request.'.$cid.'.num'};
 3335:             }
 3336:             my $value = $accesshash{$entry};
 3337:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3338:             my %temphash=($url => $value);
 3339:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3340:             if ($result eq 'ok') {
 3341:                 delete $accesshash{$entry};
 3342:             }
 3343:         } else {
 3344:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3345:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3346:             my %temphash=($entry => $accesshash{$entry});
 3347:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3348:                 delete $accesshash{$entry};
 3349:             }
 3350:         }
 3351:     }
 3352: #
 3353: # Roles
 3354: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3355: #
 3356:     foreach my $entry (keys(%userrolehash)) {
 3357:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3358: 	    split(/\:/,$entry);
 3359:         if (&Apache::lonnet::put('nohist_userroles',
 3360:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3361:                 $rudom,$runame) eq 'ok') {
 3362: 	    delete $userrolehash{$entry};
 3363:         }
 3364:     }
 3365: #
 3366: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3367: #
 3368:     my %domrolebuffer = ();
 3369:     foreach my $entry (keys(%domainrolehash)) {
 3370:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3371:         if ($domrolebuffer{$rudom}) {
 3372:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3373:                       '='.&escape($domainrolehash{$entry});
 3374:         } else {
 3375:             $domrolebuffer{$rudom}.=&escape($entry).
 3376:                       '='.&escape($domainrolehash{$entry});
 3377:         }
 3378:         delete $domainrolehash{$entry};
 3379:     }
 3380:     foreach my $dom (keys(%domrolebuffer)) {
 3381: 	my %servers = &get_servers($dom,'library');
 3382: 	foreach my $tryserver (keys(%servers)) {
 3383: 	    unless (&reply('domroleput:'.$dom.':'.
 3384: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3385: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3386: 	    }
 3387:         }
 3388:     }
 3389:     $dumpcount++;
 3390: }
 3391: 
 3392: sub courselog {
 3393:     my $what=shift;
 3394:     $what=time.':'.$what;
 3395:     unless ($env{'request.course.id'}) { return ''; }
 3396:     $coursedombuf{$env{'request.course.id'}}=
 3397:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3398:     $coursenumbuf{$env{'request.course.id'}}=
 3399:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3400:     $coursehombuf{$env{'request.course.id'}}=
 3401:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3402:     $coursedescrbuf{$env{'request.course.id'}}=
 3403:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3404:     $courseinstcodebuf{$env{'request.course.id'}}=
 3405:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3406:     $courseownerbuf{$env{'request.course.id'}}=
 3407:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3408:     $coursetypebuf{$env{'request.course.id'}}=
 3409:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3410:     if (defined $courselogs{$env{'request.course.id'}}) {
 3411: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3412:     } else {
 3413: 	$courselogs{$env{'request.course.id'}}.=$what;
 3414:     }
 3415:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3416: 	&flushcourselogs();
 3417:     }
 3418: }
 3419: 
 3420: sub courseacclog {
 3421:     my $fnsymb=shift;
 3422:     unless ($env{'request.course.id'}) { return ''; }
 3423:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3424:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3425:         $what.=':POST';
 3426:         # FIXME: Probably ought to escape things....
 3427: 	foreach my $key (keys(%env)) {
 3428:             if ($key=~/^form\.(.*)/) {
 3429:                 my $formitem = $1;
 3430:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3431:                     $what.=':'.$formitem.'='.$env{$key};
 3432:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3433:                     $what.=':'.$formitem.'='.$env{$key};
 3434:                 }
 3435:             }
 3436:         }
 3437:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3438:         # FIXME: We should not be depending on a form parameter that someone
 3439:         # editing lonsearchcat.pm might change in the future.
 3440:         if ($env{'form.phase'} eq 'course_search') {
 3441:             $what.= ':POST';
 3442:             # FIXME: Probably ought to escape things....
 3443:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3444:                                  'crsdiscuss') {
 3445:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3446:             }
 3447:         }
 3448:     }
 3449:     &courselog($what);
 3450: }
 3451: 
 3452: sub countacc {
 3453:     my $url=&declutter(shift);
 3454:     return if (! defined($url) || $url eq '');
 3455:     unless ($env{'request.course.id'}) { return ''; }
 3456: #
 3457: # Mark that this url was used in this course
 3458: #
 3459:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3460: #
 3461: # Increase the access count for this resource in this child process
 3462: #
 3463:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3464:     $accesshash{$key}++;
 3465: }
 3466: 
 3467: sub linklog {
 3468:     my ($from,$to)=@_;
 3469:     $from=&declutter($from);
 3470:     $to=&declutter($to);
 3471:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3472:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3473: }
 3474: 
 3475: sub statslog {
 3476:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3477:     if ($users<2) { return; }
 3478:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3479:             'course'       => $env{'request.course.id'},
 3480:             'sections'     => '"all"',
 3481:             'num_students' => $users,
 3482:             'part'         => $part,
 3483:             'symb'         => $symb,
 3484:             'mean_tries'   => $av_attempts,
 3485:             'deg_of_diff'  => $degdiff});
 3486:     foreach my $key (keys(%dynstore)) {
 3487:         $accesshash{$key}=$dynstore{$key};
 3488:     }
 3489: }
 3490:   
 3491: sub userrolelog {
 3492:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3493:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3494:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3495:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3496:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3497:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3498:        $userrolehash
 3499:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3500:                     =$tend.':'.$tstart;
 3501:     }
 3502:     if (($env{'request.role'} =~ /dc\./) &&
 3503: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3504: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3505: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3506:          ($trole=~/^co/))) {
 3507:        $userrolehash
 3508:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3509:                     =$tend.':'.$tstart;
 3510:     }
 3511:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3512:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3513:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3514:         ($trole=~/^sc/)) {
 3515:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3516:        $domainrolehash
 3517:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3518:                     = $tend.':'.$tstart;
 3519:     }
 3520: }
 3521: 
 3522: sub courserolelog {
 3523:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3524:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3525:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3526:         ($trole eq 'ta') || ($trole eq 'st') ||
 3527:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3528:         ($trole eq 'co')) {
 3529:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3530:             my $cdom = $1;
 3531:             my $cnum = $2;
 3532:             my $sec = $3;
 3533:             my $namespace = 'rolelog';
 3534:             my %storehash = (
 3535:                                role    => $trole,
 3536:                                start   => $tstart,
 3537:                                end     => $tend,
 3538:                                selfenroll => $selfenroll,
 3539:                                context    => $context,
 3540:                             );
 3541:             if ($trole eq 'gr') {
 3542:                 $namespace = 'groupslog';
 3543:                 $storehash{'group'} = $sec;
 3544:             } else {
 3545:                 $storehash{'section'} = $sec;
 3546:             }
 3547:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3548:             if (($trole ne 'st') || ($sec ne '')) {
 3549:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3550:             }
 3551:         }
 3552:     }
 3553:     return;
 3554: }
 3555: 
 3556: sub get_course_adv_roles {
 3557:     my ($cid,$codes) = @_;
 3558:     $cid=$env{'request.course.id'} unless (defined($cid));
 3559:     my %coursehash=&coursedescription($cid);
 3560:     my $crstype = &Apache::loncommon::course_type($cid);
 3561:     my %nothide=();
 3562:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3563:         if ($user !~ /:/) {
 3564: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3565:         } else {
 3566:             $nothide{$user}=1;
 3567:         }
 3568:     }
 3569:     my %returnhash=();
 3570:     my %dumphash=
 3571:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3572:     my $now=time;
 3573:     my %privileged;
 3574:     foreach my $entry (keys(%dumphash)) {
 3575: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3576:         if (($tstart) && ($tstart<0)) { next; }
 3577:         if (($tend) && ($tend<$now)) { next; }
 3578:         if (($tstart) && ($now<$tstart)) { next; }
 3579:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3580: 	if ($username eq '' || $domain eq '') { next; }
 3581:         unless (ref($privileged{$domain}) eq 'HASH') {
 3582:             my %dompersonnel =
 3583:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3584:             $privileged{$domain} = {};
 3585:             foreach my $server (keys(%dompersonnel)) {
 3586:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3587:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3588:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3589:                         $privileged{$udom}{$uname} = 1;
 3590:                     }
 3591:                 }
 3592:             }
 3593:         }
 3594:         if ((exists($privileged{$domain}{$username})) && 
 3595:             (!$nothide{$username.':'.$domain})) { next; }
 3596: 	if ($role eq 'cr') { next; }
 3597:         if ($codes) {
 3598:             if ($section) { $role .= ':'.$section; }
 3599:             if ($returnhash{$role}) {
 3600:                 $returnhash{$role}.=','.$username.':'.$domain;
 3601:             } else {
 3602:                 $returnhash{$role}=$username.':'.$domain;
 3603:             }
 3604:         } else {
 3605:             my $key=&plaintext($role,$crstype);
 3606:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3607:             if ($returnhash{$key}) {
 3608: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3609:             } else {
 3610:                 $returnhash{$key}=$username.':'.$domain;
 3611:             }
 3612:         }
 3613:     }
 3614:     return %returnhash;
 3615: }
 3616: 
 3617: sub get_my_roles {
 3618:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3619:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3620:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3621:     my (%dumphash,%nothide);
 3622:     if ($context eq 'userroles') {
 3623:         %dumphash = &dump('roles',$udom,$uname);
 3624:     } else {
 3625:         %dumphash=
 3626:             &dump('nohist_userroles',$udom,$uname);
 3627:         if ($hidepriv) {
 3628:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3629:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3630:                 if ($user !~ /:/) {
 3631:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3632:                 } else {
 3633:                     $nothide{$user} = 1;
 3634:                 }
 3635:             }
 3636:         }
 3637:     }
 3638:     my %returnhash=();
 3639:     my $now=time;
 3640:     my %privileged;
 3641:     foreach my $entry (keys(%dumphash)) {
 3642:         my ($role,$tend,$tstart);
 3643:         if ($context eq 'userroles') {
 3644:             next if ($entry =~ /^rolesdef/);
 3645: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3646:         } else {
 3647:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3648:         }
 3649:         if (($tstart) && ($tstart<0)) { next; }
 3650:         my $status = 'active';
 3651:         if (($tend) && ($tend<=$now)) {
 3652:             $status = 'previous';
 3653:         } 
 3654:         if (($tstart) && ($now<$tstart)) {
 3655:             $status = 'future';
 3656:         }
 3657:         if (ref($types) eq 'ARRAY') {
 3658:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3659:                 next;
 3660:             } 
 3661:         } else {
 3662:             if ($status ne 'active') {
 3663:                 next;
 3664:             }
 3665:         }
 3666:         my ($rolecode,$username,$domain,$section,$area);
 3667:         if ($context eq 'userroles') {
 3668:             ($area,$rolecode) = split(/_/,$entry);
 3669:             (undef,$domain,$username,$section) = split(/\//,$area);
 3670:         } else {
 3671:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3672:         }
 3673:         if (ref($roledoms) eq 'ARRAY') {
 3674:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3675:                 next;
 3676:             }
 3677:         }
 3678:         if (ref($roles) eq 'ARRAY') {
 3679:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3680:                 if ($role =~ /^cr\//) {
 3681:                     if (!grep(/^cr$/,@{$roles})) {
 3682:                         next;
 3683:                     }
 3684:                 } elsif ($role =~ /^gr\//) {
 3685:                     if (!grep(/^gr$/,@{$roles})) {
 3686:                         next;
 3687:                     }
 3688:                 } else {
 3689:                     next;
 3690:                 }
 3691:             }
 3692:         }
 3693:         if ($hidepriv) {
 3694:             if ($context eq 'userroles') {
 3695:                 if ((&privileged($username,$domain)) &&
 3696:                     (!$nothide{$username.':'.$domain})) {
 3697:                     next;
 3698:                 }
 3699:             } else {
 3700:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3701:                     my %dompersonnel =
 3702:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3703:                     $privileged{$domain} = {};
 3704:                     if (keys(%dompersonnel)) {
 3705:                         foreach my $server (keys(%dompersonnel)) {
 3706:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3707:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3708:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3709:                                     $privileged{$udom}{$uname} = $trole;
 3710:                                 }
 3711:                             }
 3712:                         }
 3713:                     }
 3714:                 }
 3715:                 if (exists($privileged{$domain}{$username})) {
 3716:                     if (!$nothide{$username.':'.$domain}) {
 3717:                         next;
 3718:                     }
 3719:                 }
 3720:             }
 3721:         }
 3722:         if ($withsec) {
 3723:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3724:                 $tstart.':'.$tend;
 3725:         } else {
 3726:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3727:         }
 3728:     }
 3729:     return %returnhash;
 3730: }
 3731: 
 3732: # ----------------------------------------------------- Frontpage Announcements
 3733: #
 3734: #
 3735: 
 3736: sub postannounce {
 3737:     my ($server,$text)=@_;
 3738:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3739:     unless ($text=~/\w/) { $text=''; }
 3740:     return &reply('setannounce:'.&escape($text),$server);
 3741: }
 3742: 
 3743: sub getannounce {
 3744: 
 3745:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3746: 	my $announcement='';
 3747: 	while (my $line = <$fh>) { $announcement .= $line; }
 3748: 	close($fh);
 3749: 	if ($announcement=~/\w/) { 
 3750: 	    return 
 3751:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3752:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3753: 	} else {
 3754: 	    return '';
 3755: 	}
 3756:     } else {
 3757: 	return '';
 3758:     }
 3759: }
 3760: 
 3761: # ---------------------------------------------------------- Course ID routines
 3762: # Deal with domain's nohist_courseid.db files
 3763: #
 3764: 
 3765: sub courseidput {
 3766:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3767:     return unless (ref($storehash) eq 'HASH');
 3768:     my $outcome;
 3769:     if ($caller eq 'timeonly') {
 3770:         my $cids = '';
 3771:         foreach my $item (keys(%$storehash)) {
 3772:             $cids.=&escape($item).'&';
 3773:         }
 3774:         $cids=~s/\&$//;
 3775:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3776:                           $coursehome);       
 3777:     } else {
 3778:         my $items = '';
 3779:         foreach my $item (keys(%$storehash)) {
 3780:             $items.= &escape($item).'='.
 3781:                      &freeze_escape($$storehash{$item}).'&';
 3782:         }
 3783:         $items=~s/\&$//;
 3784:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3785:                           $coursehome);
 3786:     }
 3787:     if ($outcome eq 'unknown_cmd') {
 3788:         my $what;
 3789:         foreach my $cid (keys(%$storehash)) {
 3790:             $what .= &escape($cid).'=';
 3791:             foreach my $item ('description','inst_code','owner','type') {
 3792:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3793:             }
 3794:             $what =~ s/\:$/&/;
 3795:         }
 3796:         $what =~ s/\&$//;  
 3797:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3798:     } else {
 3799:         return $outcome;
 3800:     }
 3801: }
 3802: 
 3803: sub courseiddump {
 3804:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3805:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3806:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3807:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3808:     my $as_hash = 1;
 3809:     my %returnhash;
 3810:     if (!$domfilter) { $domfilter=''; }
 3811:     my %libserv = &all_library();
 3812:     foreach my $tryserver (keys(%libserv)) {
 3813:         if ( (  $hostidflag == 1 
 3814: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3815: 	     || (!defined($hostidflag)) ) {
 3816: 
 3817: 	    if (($domfilter eq '') ||
 3818: 		(&host_domain($tryserver) eq $domfilter)) {
 3819:                 my $rep = 
 3820:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3821:                          $sincefilter.':'.&escape($descfilter).':'.
 3822:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3823:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3824:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3825:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3826:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3827:                          &escape($cc_clone).':'.$cloneonly.':'.
 3828:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3829:                          &escape($creationcontext).':'.$domcloner,
 3830:                          $tryserver);
 3831:                 my @pairs=split(/\&/,$rep);
 3832:                 foreach my $item (@pairs) {
 3833:                     my ($key,$value)=split(/\=/,$item,2);
 3834:                     $key = &unescape($key);
 3835:                     next if ($key =~ /^error: 2 /);
 3836:                     my $result = &thaw_unescape($value);
 3837:                     if (ref($result) eq 'HASH') {
 3838:                         $returnhash{$key}=$result;
 3839:                     } else {
 3840:                         my @responses = split(/:/,$value);
 3841:                         my @items = ('description','inst_code','owner','type');
 3842:                         for (my $i=0; $i<@responses; $i++) {
 3843:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3844:                         }
 3845:                     }
 3846:                 }
 3847:             }
 3848:         }
 3849:     }
 3850:     return %returnhash;
 3851: }
 3852: 
 3853: sub courselastaccess {
 3854:     my ($cdom,$cnum,$hostidref) = @_;
 3855:     my %returnhash;
 3856:     if ($cdom && $cnum) {
 3857:         my $chome = &homeserver($cnum,$cdom);
 3858:         if ($chome ne 'no_host') {
 3859:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3860:             &extract_lastaccess(\%returnhash,$rep);
 3861:         }
 3862:     } else {
 3863:         if (!$cdom) { $cdom=''; }
 3864:         my %libserv = &all_library();
 3865:         foreach my $tryserver (keys(%libserv)) {
 3866:             if (ref($hostidref) eq 'ARRAY') {
 3867:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3868:             } 
 3869:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3870:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3871:                 &extract_lastaccess(\%returnhash,$rep);
 3872:             }
 3873:         }
 3874:     }
 3875:     return %returnhash;
 3876: }
 3877: 
 3878: sub extract_lastaccess {
 3879:     my ($returnhash,$rep) = @_;
 3880:     if (ref($returnhash) eq 'HASH') {
 3881:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3882:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3883:                  $rep eq '') {
 3884:             my @pairs=split(/\&/,$rep);
 3885:             foreach my $item (@pairs) {
 3886:                 my ($key,$value)=split(/\=/,$item,2);
 3887:                 $key = &unescape($key);
 3888:                 next if ($key =~ /^error: 2 /);
 3889:                 $returnhash->{$key} = &thaw_unescape($value);
 3890:             }
 3891:         }
 3892:     }
 3893:     return;
 3894: }
 3895: 
 3896: # ---------------------------------------------------------- DC e-mail
 3897: 
 3898: sub dcmailput {
 3899:     my ($domain,$msgid,$message,$server)=@_;
 3900:     my $status = &Apache::lonnet::critical(
 3901:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3902:        &escape($message),$server);
 3903:     return $status;
 3904: }
 3905: 
 3906: sub dcmaildump {
 3907:     my ($dom,$startdate,$enddate,$senders) = @_;
 3908:     my %returnhash=();
 3909: 
 3910:     if (defined(&domain($dom,'primary'))) {
 3911:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3912:                                                          &escape($enddate).':';
 3913: 	my @esc_senders=map { &escape($_)} @$senders;
 3914: 	$cmd.=&escape(join('&',@esc_senders));
 3915: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3916:             my ($key,$value) = split(/\=/,$line,2);
 3917:             if (($key) && ($value)) {
 3918:                 $returnhash{&unescape($key)} = &unescape($value);
 3919:             }
 3920:         }
 3921:     }
 3922:     return %returnhash;
 3923: }
 3924: # ---------------------------------------------------------- Domain roles
 3925: 
 3926: sub get_domain_roles {
 3927:     my ($dom,$roles,$startdate,$enddate)=@_;
 3928:     if ((!defined($startdate)) || ($startdate eq '')) {
 3929:         $startdate = '.';
 3930:     }
 3931:     if ((!defined($enddate)) || ($enddate eq '')) {
 3932:         $enddate = '.';
 3933:     }
 3934:     my $rolelist;
 3935:     if (ref($roles) eq 'ARRAY') {
 3936:         $rolelist = join(':',@{$roles});
 3937:     }
 3938:     my %personnel = ();
 3939: 
 3940:     my %servers = &get_servers($dom,'library');
 3941:     foreach my $tryserver (keys(%servers)) {
 3942: 	%{$personnel{$tryserver}}=();
 3943: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3944: 					    &escape($startdate).':'.
 3945: 					    &escape($enddate).':'.
 3946: 					    &escape($rolelist), $tryserver))) {
 3947: 	    my ($key,$value) = split(/\=/,$line,2);
 3948: 	    if (($key) && ($value)) {
 3949: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3950: 	    }
 3951: 	}
 3952:     }
 3953:     return %personnel;
 3954: }
 3955: 
 3956: # ----------------------------------------------------------- Interval timing 
 3957: 
 3958: {
 3959: # Caches needed for speedup of navmaps
 3960: # We don't want to cache this for very long at all (5 seconds at most)
 3961: # 
 3962: # The user for whom we cache
 3963: my $cachedkey='';
 3964: # The cached times for this user
 3965: my %cachedtimes=();
 3966: # When this was last done
 3967: my $cachedtime=();
 3968: 
 3969: sub load_all_first_access {
 3970:     my ($uname,$udom)=@_;
 3971:     if (($cachedkey eq $uname.':'.$udom) &&
 3972:         (abs($cachedtime-time)<5)) {
 3973:         return;
 3974:     }
 3975:     $cachedtime=time;
 3976:     $cachedkey=$uname.':'.$udom;
 3977:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3978: }
 3979: 
 3980: sub get_first_access {
 3981:     my ($type,$argsymb,$argmap)=@_;
 3982:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3983:     if ($argsymb) { $symb=$argsymb; }
 3984:     my ($map,$id,$res)=&decode_symb($symb);
 3985:     if ($argmap) { $map = $argmap; }
 3986:     if ($type eq 'course') {
 3987: 	$res='course';
 3988:     } elsif ($type eq 'map') {
 3989: 	$res=&symbread($map);
 3990:     } else {
 3991: 	$res=$symb;
 3992:     }
 3993:     &load_all_first_access($uname,$udom);
 3994:     return $cachedtimes{"$courseid\0$res"};
 3995: }
 3996: 
 3997: sub set_first_access {
 3998:     my ($type,$interval)=@_;
 3999:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4000:     my ($map,$id,$res)=&decode_symb($symb);
 4001:     if ($type eq 'course') {
 4002: 	$res='course';
 4003:     } elsif ($type eq 'map') {
 4004: 	$res=&symbread($map);
 4005:     } else {
 4006: 	$res=$symb;
 4007:     }
 4008:     $cachedkey='';
 4009:     my $firstaccess=&get_first_access($type,$symb,$map);
 4010:     if (!$firstaccess) {
 4011:         my $start = time;
 4012: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4013:                           $udom,$uname);
 4014:         if ($putres eq 'ok') {
 4015:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4016:                  $udom,$uname); 
 4017:             &appenv(
 4018:                      {
 4019:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4020:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4021:                      }
 4022:                   );
 4023:         }
 4024:         return $putres;
 4025:     }
 4026:     return 'already_set';
 4027: }
 4028: }
 4029: # --------------------------------------------- Set Expire Date for Spreadsheet
 4030: 
 4031: sub expirespread {
 4032:     my ($uname,$udom,$stype,$usymb)=@_;
 4033:     my $cid=$env{'request.course.id'}; 
 4034:     if ($cid) {
 4035:        my $now=time;
 4036:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4037:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4038:                             $env{'course.'.$cid.'.num'}.
 4039: 	        	    ':nohist_expirationdates:'.
 4040:                             &escape($key).'='.$now,
 4041:                             $env{'course.'.$cid.'.home'})
 4042:     }
 4043:     return 'ok';
 4044: }
 4045: 
 4046: # ----------------------------------------------------- Devalidate Spreadsheets
 4047: 
 4048: sub devalidate {
 4049:     my ($symb,$uname,$udom)=@_;
 4050:     my $cid=$env{'request.course.id'}; 
 4051:     if ($cid) {
 4052:         # delete the stored spreadsheets for
 4053:         # - the student level sheet of this user in course's homespace
 4054:         # - the assessment level sheet for this resource 
 4055:         #   for this user in user's homespace
 4056: 	# - current conditional state info
 4057: 	my $key=$uname.':'.$udom.':';
 4058:         my $status=
 4059: 	    &del('nohist_calculatedsheets',
 4060: 		 [$key.'studentcalc:'],
 4061: 		 $env{'course.'.$cid.'.domain'},
 4062: 		 $env{'course.'.$cid.'.num'})
 4063: 		.' '.
 4064: 	    &del('nohist_calculatedsheets_'.$cid,
 4065: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4066:         unless ($status eq 'ok ok') {
 4067:            &logthis('Could not devalidate spreadsheet '.
 4068:                     $uname.' at '.$udom.' for '.
 4069: 		    $symb.': '.$status);
 4070:         }
 4071: 	&delenv('user.state.'.$cid);
 4072:     }
 4073: }
 4074: 
 4075: sub get_scalar {
 4076:     my ($string,$end) = @_;
 4077:     my $value;
 4078:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4079: 	$value = $1;
 4080:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4081: 	$value = $1;
 4082:     }
 4083:     return &unescape($value);
 4084: }
 4085: 
 4086: sub array2str {
 4087:   my (@array) = @_;
 4088:   my $result=&arrayref2str(\@array);
 4089:   $result=~s/^__ARRAY_REF__//;
 4090:   $result=~s/__END_ARRAY_REF__$//;
 4091:   return $result;
 4092: }
 4093: 
 4094: sub arrayref2str {
 4095:   my ($arrayref) = @_;
 4096:   my $result='__ARRAY_REF__';
 4097:   foreach my $elem (@$arrayref) {
 4098:     if(ref($elem) eq 'ARRAY') {
 4099:       $result.=&arrayref2str($elem).'&';
 4100:     } elsif(ref($elem) eq 'HASH') {
 4101:       $result.=&hashref2str($elem).'&';
 4102:     } elsif(ref($elem)) {
 4103:       #print("Got a ref of ".(ref($elem))." skipping.");
 4104:     } else {
 4105:       $result.=&escape($elem).'&';
 4106:     }
 4107:   }
 4108:   $result=~s/\&$//;
 4109:   $result .= '__END_ARRAY_REF__';
 4110:   return $result;
 4111: }
 4112: 
 4113: sub hash2str {
 4114:   my (%hash) = @_;
 4115:   my $result=&hashref2str(\%hash);
 4116:   $result=~s/^__HASH_REF__//;
 4117:   $result=~s/__END_HASH_REF__$//;
 4118:   return $result;
 4119: }
 4120: 
 4121: sub hashref2str {
 4122:   my ($hashref)=@_;
 4123:   my $result='__HASH_REF__';
 4124:   foreach my $key (sort(keys(%$hashref))) {
 4125:     if (ref($key) eq 'ARRAY') {
 4126:       $result.=&arrayref2str($key).'=';
 4127:     } elsif (ref($key) eq 'HASH') {
 4128:       $result.=&hashref2str($key).'=';
 4129:     } elsif (ref($key)) {
 4130:       $result.='=';
 4131:       #print("Got a ref of ".(ref($key))." skipping.");
 4132:     } else {
 4133: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4134:     }
 4135: 
 4136:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4137:       $result.=&arrayref2str($hashref->{$key}).'&';
 4138:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4139:       $result.=&hashref2str($hashref->{$key}).'&';
 4140:     } elsif(ref($hashref->{$key})) {
 4141:        $result.='&';
 4142:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4143:     } else {
 4144:       $result.=&escape($hashref->{$key}).'&';
 4145:     }
 4146:   }
 4147:   $result=~s/\&$//;
 4148:   $result .= '__END_HASH_REF__';
 4149:   return $result;
 4150: }
 4151: 
 4152: sub str2hash {
 4153:     my ($string)=@_;
 4154:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4155:     return %$hash;
 4156: }
 4157: 
 4158: sub str2hashref {
 4159:   my ($string) = @_;
 4160: 
 4161:   my %hash;
 4162: 
 4163:   if($string !~ /^__HASH_REF__/) {
 4164:       if (! ($string eq '' || !defined($string))) {
 4165: 	  $hash{'error'}='Not hash reference';
 4166:       }
 4167:       return (\%hash, $string);
 4168:   }
 4169: 
 4170:   $string =~ s/^__HASH_REF__//;
 4171: 
 4172:   while($string !~ /^__END_HASH_REF__/) {
 4173:       #key
 4174:       my $key='';
 4175:       if($string =~ /^__HASH_REF__/) {
 4176:           ($key, $string)=&str2hashref($string);
 4177:           if(defined($key->{'error'})) {
 4178:               $hash{'error'}='Bad data';
 4179:               return (\%hash, $string);
 4180:           }
 4181:       } elsif($string =~ /^__ARRAY_REF__/) {
 4182:           ($key, $string)=&str2arrayref($string);
 4183:           if($key->[0] eq 'Array reference error') {
 4184:               $hash{'error'}='Bad data';
 4185:               return (\%hash, $string);
 4186:           }
 4187:       } else {
 4188:           $string =~ s/^(.*?)=//;
 4189: 	  $key=&unescape($1);
 4190:       }
 4191:       $string =~ s/^=//;
 4192: 
 4193:       #value
 4194:       my $value='';
 4195:       if($string =~ /^__HASH_REF__/) {
 4196:           ($value, $string)=&str2hashref($string);
 4197:           if(defined($value->{'error'})) {
 4198:               $hash{'error'}='Bad data';
 4199:               return (\%hash, $string);
 4200:           }
 4201:       } elsif($string =~ /^__ARRAY_REF__/) {
 4202:           ($value, $string)=&str2arrayref($string);
 4203:           if($value->[0] eq 'Array reference error') {
 4204:               $hash{'error'}='Bad data';
 4205:               return (\%hash, $string);
 4206:           }
 4207:       } else {
 4208: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4209:       }
 4210:       $string =~ s/^&//;
 4211: 
 4212:       $hash{$key}=$value;
 4213:   }
 4214: 
 4215:   $string =~ s/^__END_HASH_REF__//;
 4216: 
 4217:   return (\%hash, $string);
 4218: }
 4219: 
 4220: sub str2array {
 4221:     my ($string)=@_;
 4222:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4223:     return @$array;
 4224: }
 4225: 
 4226: sub str2arrayref {
 4227:   my ($string) = @_;
 4228:   my @array;
 4229: 
 4230:   if($string !~ /^__ARRAY_REF__/) {
 4231:       if (! ($string eq '' || !defined($string))) {
 4232: 	  $array[0]='Array reference error';
 4233:       }
 4234:       return (\@array, $string);
 4235:   }
 4236: 
 4237:   $string =~ s/^__ARRAY_REF__//;
 4238: 
 4239:   while($string !~ /^__END_ARRAY_REF__/) {
 4240:       my $value='';
 4241:       if($string =~ /^__HASH_REF__/) {
 4242:           ($value, $string)=&str2hashref($string);
 4243:           if(defined($value->{'error'})) {
 4244:               $array[0] ='Array reference error';
 4245:               return (\@array, $string);
 4246:           }
 4247:       } elsif($string =~ /^__ARRAY_REF__/) {
 4248:           ($value, $string)=&str2arrayref($string);
 4249:           if($value->[0] eq 'Array reference error') {
 4250:               $array[0] ='Array reference error';
 4251:               return (\@array, $string);
 4252:           }
 4253:       } else {
 4254: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4255:       }
 4256:       $string =~ s/^&//;
 4257: 
 4258:       push(@array, $value);
 4259:   }
 4260: 
 4261:   $string =~ s/^__END_ARRAY_REF__//;
 4262: 
 4263:   return (\@array, $string);
 4264: }
 4265: 
 4266: # -------------------------------------------------------------------Temp Store
 4267: 
 4268: sub tmpreset {
 4269:   my ($symb,$namespace,$domain,$stuname) = @_;
 4270:   if (!$symb) {
 4271:     $symb=&symbread();
 4272:     if (!$symb) { $symb= $env{'request.url'}; }
 4273:   }
 4274:   $symb=escape($symb);
 4275: 
 4276:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4277:   $namespace=~s/\//\_/g;
 4278:   $namespace=~s/\W//g;
 4279: 
 4280:   if (!$domain) { $domain=$env{'user.domain'}; }
 4281:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4282:   if ($domain eq 'public' && $stuname eq 'public') {
 4283:       $stuname=$ENV{'REMOTE_ADDR'};
 4284:   }
 4285:   my $path=LONCAPA::tempdir();
 4286:   my %hash;
 4287:   if (tie(%hash,'GDBM_File',
 4288: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4289: 	  &GDBM_WRCREAT(),0640)) {
 4290:     foreach my $key (keys(%hash)) {
 4291:       if ($key=~ /:$symb/) {
 4292: 	delete($hash{$key});
 4293:       }
 4294:     }
 4295:   }
 4296: }
 4297: 
 4298: sub tmpstore {
 4299:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4300: 
 4301:   if (!$symb) {
 4302:     $symb=&symbread();
 4303:     if (!$symb) { $symb= $env{'request.url'}; }
 4304:   }
 4305:   $symb=escape($symb);
 4306: 
 4307:   if (!$namespace) {
 4308:     # I don't think we would ever want to store this for a course.
 4309:     # it seems this will only be used if we don't have a course.
 4310:     #$namespace=$env{'request.course.id'};
 4311:     #if (!$namespace) {
 4312:       $namespace=$env{'request.state'};
 4313:     #}
 4314:   }
 4315:   $namespace=~s/\//\_/g;
 4316:   $namespace=~s/\W//g;
 4317:   if (!$domain) { $domain=$env{'user.domain'}; }
 4318:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4319:   if ($domain eq 'public' && $stuname eq 'public') {
 4320:       $stuname=$ENV{'REMOTE_ADDR'};
 4321:   }
 4322:   my $now=time;
 4323:   my %hash;
 4324:   my $path=LONCAPA::tempdir();
 4325:   if (tie(%hash,'GDBM_File',
 4326: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4327: 	  &GDBM_WRCREAT(),0640)) {
 4328:     $hash{"version:$symb"}++;
 4329:     my $version=$hash{"version:$symb"};
 4330:     my $allkeys=''; 
 4331:     foreach my $key (keys(%$storehash)) {
 4332:       $allkeys.=$key.':';
 4333:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4334:     }
 4335:     $hash{"$version:$symb:timestamp"}=$now;
 4336:     $allkeys.='timestamp';
 4337:     $hash{"$version:keys:$symb"}=$allkeys;
 4338:     if (untie(%hash)) {
 4339:       return 'ok';
 4340:     } else {
 4341:       return "error:$!";
 4342:     }
 4343:   } else {
 4344:     return "error:$!";
 4345:   }
 4346: }
 4347: 
 4348: # -----------------------------------------------------------------Temp Restore
 4349: 
 4350: sub tmprestore {
 4351:   my ($symb,$namespace,$domain,$stuname) = @_;
 4352: 
 4353:   if (!$symb) {
 4354:     $symb=&symbread();
 4355:     if (!$symb) { $symb= $env{'request.url'}; }
 4356:   }
 4357:   $symb=escape($symb);
 4358: 
 4359:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4360: 
 4361:   if (!$domain) { $domain=$env{'user.domain'}; }
 4362:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4363:   if ($domain eq 'public' && $stuname eq 'public') {
 4364:       $stuname=$ENV{'REMOTE_ADDR'};
 4365:   }
 4366:   my %returnhash;
 4367:   $namespace=~s/\//\_/g;
 4368:   $namespace=~s/\W//g;
 4369:   my %hash;
 4370:   my $path=LONCAPA::tempdir();
 4371:   if (tie(%hash,'GDBM_File',
 4372: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4373: 	  &GDBM_READER(),0640)) {
 4374:     my $version=$hash{"version:$symb"};
 4375:     $returnhash{'version'}=$version;
 4376:     my $scope;
 4377:     for ($scope=1;$scope<=$version;$scope++) {
 4378:       my $vkeys=$hash{"$scope:keys:$symb"};
 4379:       my @keys=split(/:/,$vkeys);
 4380:       my $key;
 4381:       $returnhash{"$scope:keys"}=$vkeys;
 4382:       foreach $key (@keys) {
 4383: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4384: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4385:       }
 4386:     }
 4387:     if (!(untie(%hash))) {
 4388:       return "error:$!";
 4389:     }
 4390:   } else {
 4391:     return "error:$!";
 4392:   }
 4393:   return %returnhash;
 4394: }
 4395: 
 4396: # ----------------------------------------------------------------------- Store
 4397: 
 4398: sub store {
 4399:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4400:     my $home='';
 4401: 
 4402:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4403: 
 4404:     $symb=&symbclean($symb);
 4405:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4406: 
 4407:     if (!$domain) { $domain=$env{'user.domain'}; }
 4408:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4409: 
 4410:     &devalidate($symb,$stuname,$domain);
 4411: 
 4412:     $symb=escape($symb);
 4413:     if (!$namespace) { 
 4414:        unless ($namespace=$env{'request.course.id'}) { 
 4415:           return ''; 
 4416:        } 
 4417:     }
 4418:     if (!$home) { $home=$env{'user.home'}; }
 4419: 
 4420:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4421:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4422: 
 4423:     my $namevalue='';
 4424:     foreach my $key (keys(%$storehash)) {
 4425:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4426:     }
 4427:     $namevalue=~s/\&$//;
 4428:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4429:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4430: }
 4431: 
 4432: # -------------------------------------------------------------- Critical Store
 4433: 
 4434: sub cstore {
 4435:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4436:     my $home='';
 4437: 
 4438:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4439: 
 4440:     $symb=&symbclean($symb);
 4441:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4442: 
 4443:     if (!$domain) { $domain=$env{'user.domain'}; }
 4444:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4445: 
 4446:     &devalidate($symb,$stuname,$domain);
 4447: 
 4448:     $symb=escape($symb);
 4449:     if (!$namespace) { 
 4450:        unless ($namespace=$env{'request.course.id'}) { 
 4451:           return ''; 
 4452:        } 
 4453:     }
 4454:     if (!$home) { $home=$env{'user.home'}; }
 4455: 
 4456:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4457:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4458: 
 4459:     my $namevalue='';
 4460:     foreach my $key (keys(%$storehash)) {
 4461:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4462:     }
 4463:     $namevalue=~s/\&$//;
 4464:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4465:     return critical
 4466:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4467: }
 4468: 
 4469: # --------------------------------------------------------------------- Restore
 4470: 
 4471: sub restore {
 4472:     my ($symb,$namespace,$domain,$stuname) = @_;
 4473:     my $home='';
 4474: 
 4475:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4476: 
 4477:     if (!$symb) {
 4478:       unless ($symb=escape(&symbread())) { return ''; }
 4479:     } else {
 4480:       $symb=&escape(&symbclean($symb));
 4481:     }
 4482:     if (!$namespace) { 
 4483:        unless ($namespace=$env{'request.course.id'}) { 
 4484:           return ''; 
 4485:        } 
 4486:     }
 4487:     if (!$domain) { $domain=$env{'user.domain'}; }
 4488:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4489:     if (!$home) { $home=$env{'user.home'}; }
 4490:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4491: 
 4492:     my %returnhash=();
 4493:     foreach my $line (split(/\&/,$answer)) {
 4494: 	my ($name,$value)=split(/\=/,$line);
 4495:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4496:     }
 4497:     my $version;
 4498:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4499:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4500:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4501:        }
 4502:     }
 4503:     return %returnhash;
 4504: }
 4505: 
 4506: # ---------------------------------------------------------- Course Description
 4507: #
 4508: #  
 4509: 
 4510: sub coursedescription {
 4511:     my ($courseid,$args)=@_;
 4512:     $courseid=~s/^\///;
 4513:     $courseid=~s/\_/\//g;
 4514:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4515:     my $chome=&homeserver($cnum,$cdomain);
 4516:     my $normalid=$cdomain.'_'.$cnum;
 4517:     # need to always cache even if we get errors otherwise we keep 
 4518:     # trying and trying and trying to get the course description.
 4519:     my %envhash=();
 4520:     my %returnhash=();
 4521:     
 4522:     my $expiretime=600;
 4523:     if ($env{'request.course.id'} eq $normalid) {
 4524: 	$expiretime=120;
 4525:     }
 4526: 
 4527:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4528:     if (!$args->{'freshen_cache'}
 4529: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4530: 	foreach my $key (keys(%env)) {
 4531: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4532: 	    my ($setting) = $1;
 4533: 	    $returnhash{$setting} = $env{$key};
 4534: 	}
 4535: 	return %returnhash;
 4536:     }
 4537: 
 4538:     # get the data again
 4539: 
 4540:     if (!$args->{'one_time'}) {
 4541: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4542:     }
 4543: 
 4544:     if ($chome ne 'no_host') {
 4545:        %returnhash=&dump('environment',$cdomain,$cnum);
 4546:        if (!exists($returnhash{'con_lost'})) {
 4547: 	   my $username = $env{'user.name'}; # Defult username
 4548: 	   if(defined $args->{'user'}) {
 4549: 	       $username = $args->{'user'};
 4550: 	   }
 4551:            $returnhash{'home'}= $chome;
 4552: 	   $returnhash{'domain'} = $cdomain;
 4553: 	   $returnhash{'num'} = $cnum;
 4554:            if (!defined($returnhash{'type'})) {
 4555:                $returnhash{'type'} = 'Course';
 4556:            }
 4557:            while (my ($name,$value) = each %returnhash) {
 4558:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4559:            }
 4560:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4561:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4562: 	       $username.'_'.$cdomain.'_'.$cnum;
 4563:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4564:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4565:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4566:        }
 4567:     }
 4568:     if (!$args->{'one_time'}) {
 4569: 	&appenv(\%envhash);
 4570:     }
 4571:     return %returnhash;
 4572: }
 4573: 
 4574: sub update_released_required {
 4575:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4576:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4577:         $cid = $env{'request.course.id'};
 4578:         $cdom = $env{'course.'.$cid.'.domain'};
 4579:         $cnum = $env{'course.'.$cid.'.num'};
 4580:         $chome = $env{'course.'.$cid.'.home'};
 4581:     }
 4582:     if ($needsrelease) {
 4583:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4584:         my $needsupdate;
 4585:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4586:             $needsupdate = 1;
 4587:         } else {
 4588:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4589:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4590:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4591:                 $needsupdate = 1;
 4592:             }
 4593:         }
 4594:         if ($needsupdate) {
 4595:             my %needshash = (
 4596:                              'internal.releaserequired' => $needsrelease,
 4597:                             );
 4598:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4599:             if ($putresult eq 'ok') {
 4600:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4601:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4602:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4603:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4604:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4605:                 }
 4606:             }
 4607:         }
 4608:     }
 4609:     return;
 4610: }
 4611: 
 4612: # -------------------------------------------------See if a user is privileged
 4613: 
 4614: sub privileged {
 4615:     my ($username,$domain)=@_;
 4616:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4617: 			&homeserver($username,$domain));
 4618:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4619:         ($rolesdump =~ /^error:/)) {
 4620:         return 0;
 4621:     }
 4622:     my $now=time;
 4623:     if ($rolesdump ne '') {
 4624:         foreach my $entry (split(/&/,$rolesdump)) {
 4625: 	    if ($entry!~/^rolesdef_/) {
 4626: 		my ($area,$role)=split(/=/,$entry);
 4627: 		$area=~s/\_\w\w$//;
 4628: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4629: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4630: 		    my $active=1;
 4631: 		    if ($tend) {
 4632: 			if ($tend<$now) { $active=0; }
 4633: 		    }
 4634: 		    if ($tstart) {
 4635: 			if ($tstart>$now) { $active=0; }
 4636: 		    }
 4637: 		    if ($active) { return 1; }
 4638: 		}
 4639: 	    }
 4640: 	}
 4641:     }
 4642:     return 0;
 4643: }
 4644: 
 4645: # -------------------------------------------------------- Get user privileges
 4646: 
 4647: sub rolesinit {
 4648:     my ($domain,$username,$authhost)=@_;
 4649:     my $now=time;
 4650:     my %userroles = ('user.login.time' => $now);
 4651:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 4652:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4653:         ($rolesdump =~ /^error:/)) {
 4654:         return \%userroles;
 4655:     }
 4656:     my %firstaccess = &dump('firstaccesstimes',$domain,$username);
 4657:     my %timerinterval = &dump('timerinterval',$domain,$username);
 4658:     my (%coursetimerstarts,%firstaccchk,%firstaccenv,
 4659:         %coursetimerintervals,%timerintchk,%timerintenv);
 4660:     foreach my $key (keys(%firstaccess)) {
 4661:         my ($cid,$rest) = split(/\0/,$key);
 4662:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4663:     }
 4664:     foreach my $key (keys(%timerinterval)) {
 4665:         my ($cid,$rest) = split(/\0/,$key);
 4666:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4667:     }
 4668:     my %allroles=();
 4669:     my %allgroups=();
 4670: 
 4671:     if ($rolesdump ne '') {
 4672:         foreach my $entry (split(/&/,$rolesdump)) {
 4673: 	  if ($entry!~/^rolesdef_/) {
 4674:             my ($area,$role)=split(/=/,$entry);
 4675: 	    $area=~s/\_\w\w$//;
 4676:             my ($trole,$tend,$tstart,$group_privs);
 4677: 	    if ($role=~/^cr/) {
 4678: # Custom role, defined by a user 
 4679: # e.g., user.role.cr/msu/smith/mynewrole
 4680: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4681: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4682: 		    ($tend,$tstart)=split('_',$trest);
 4683: 		} else {
 4684: 		    $trole=$role;
 4685: 		}
 4686:             } elsif ($role =~ m|^gr/|) {
 4687: # Role of member in a group, defined within a course/community
 4688: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4689:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4690:                 next if ($tstart eq '-1');
 4691:                 ($trole,$group_privs) = split(/\//,$trole);
 4692:                 $group_privs = &unescape($group_privs);
 4693: 	    } else {
 4694: # Just a normal role, defined in roles.tab
 4695: 		($trole,$tend,$tstart)=split(/_/,$role);
 4696: 	    }
 4697: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4698: 					 $username);
 4699: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4700:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4701:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4702:             if (($area ne '') && ($trole ne '')) {
 4703: 		my $spec=$trole.'.'.$area;
 4704: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4705: 		if ($trole =~ /^cr\//) {
 4706: # Custom role, defined by a user
 4707:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4708:                 } elsif ($trole eq 'gr') {
 4709: # Role of a member in a group, defined within a course/community
 4710:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4711: 		} else {
 4712: # Normal role, defined in roles.tab
 4713:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4714: 		}
 4715:                 if ($trole ne 'gr') {
 4716:                     my $cid = $tdomain.'_'.$trest;
 4717:                     unless ($firstaccchk{$cid}) {
 4718:                         if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4719:                             foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4720:                                 $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4721:                                     $coursetimerstarts{$cid}{$item}; 
 4722:                             }
 4723:                         }
 4724:                         $firstaccchk{$cid} = 1;
 4725:                     }
 4726:                     unless ($timerintchk{$cid}) {
 4727:                         if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4728:                             foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4729:                                 $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4730:                                    $coursetimerintervals{$cid}{$item};
 4731:                             }
 4732:                         }
 4733:                         $timerintchk{$cid} = 1;
 4734:                     }
 4735:                 }
 4736:             }
 4737:           }
 4738:         }
 4739:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4740:         $userroles{'user.adv'}    = $adv;
 4741: 	$userroles{'user.author'} = $author;
 4742:         $env{'user.adv'}=$adv;
 4743:     }
 4744:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4745: }
 4746: 
 4747: sub set_arearole {
 4748:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4749: # log the associated role with the area
 4750:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4751:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4752: }
 4753: 
 4754: sub custom_roleprivs {
 4755:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4756:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4757:     my $homsvr=homeserver($rauthor,$rdomain);
 4758:     if (&hostname($homsvr) ne '') {
 4759:         my ($rdummy,$roledef)=
 4760:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4761:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4762:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4763:             if (defined($syspriv)) {
 4764:                 if ($trest =~ /^$match_community$/) {
 4765:                     $syspriv =~ s/bre\&S//; 
 4766:                 }
 4767:                 $$allroles{'cm./'}.=':'.$syspriv;
 4768:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4769:             }
 4770:             if ($tdomain ne '') {
 4771:                 if (defined($dompriv)) {
 4772:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4773:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4774:                 }
 4775:                 if (($trest ne '') && (defined($coursepriv))) {
 4776:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4777:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4778:                 }
 4779:             }
 4780:         }
 4781:     }
 4782: }
 4783: 
 4784: sub group_roleprivs {
 4785:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4786:     my $access = 1;
 4787:     my $now = time;
 4788:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4789:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4790:     if ($access) {
 4791:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4792:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4793:     }
 4794: }
 4795: 
 4796: sub standard_roleprivs {
 4797:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4798:     if (defined($pr{$trole.':s'})) {
 4799:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4800:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4801:     }
 4802:     if ($tdomain ne '') {
 4803:         if (defined($pr{$trole.':d'})) {
 4804:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4805:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4806:         }
 4807:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4808:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4809:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4810:         }
 4811:     }
 4812: }
 4813: 
 4814: sub set_userprivs {
 4815:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4816:     my $author=0;
 4817:     my $adv=0;
 4818:     my %grouproles = ();
 4819:     if (keys(%{$allgroups}) > 0) {
 4820:         my @groupkeys; 
 4821:         foreach my $role (keys(%{$allroles})) {
 4822:             push(@groupkeys,$role);
 4823:         }
 4824:         if (ref($groups_roles) eq 'HASH') {
 4825:             foreach my $key (keys(%{$groups_roles})) {
 4826:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4827:                     push(@groupkeys,$key);
 4828:                 }
 4829:             }
 4830:         }
 4831:         if (@groupkeys > 0) {
 4832:             foreach my $role (@groupkeys) {
 4833:                 my ($trole,$area,$sec,$extendedarea);
 4834:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4835:                     $trole = $1;
 4836:                     $area = $2;
 4837:                     $sec = $3;
 4838:                     $extendedarea = $area.$sec;
 4839:                     if (exists($$allgroups{$area})) {
 4840:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4841:                             my $spec = $trole.'.'.$extendedarea;
 4842:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4843:                                                 $$allgroups{$area}{$group};
 4844:                         }
 4845:                     }
 4846:                 }
 4847:             }
 4848:         }
 4849:     }
 4850:     foreach my $group (keys(%grouproles)) {
 4851:         $$allroles{$group} = $grouproles{$group};
 4852:     }
 4853:     foreach my $role (keys(%{$allroles})) {
 4854:         my %thesepriv;
 4855:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4856:         foreach my $item (split(/:/,$$allroles{$role})) {
 4857:             if ($item ne '') {
 4858:                 my ($privilege,$restrictions)=split(/&/,$item);
 4859:                 if ($restrictions eq '') {
 4860:                     $thesepriv{$privilege}='F';
 4861:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4862:                     $thesepriv{$privilege}.=$restrictions;
 4863:                 }
 4864:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4865:             }
 4866:         }
 4867:         my $thesestr='';
 4868:         foreach my $priv (sort(keys(%thesepriv))) {
 4869: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4870: 	}
 4871:         $userroles->{'user.priv.'.$role} = $thesestr;
 4872:     }
 4873:     return ($author,$adv);
 4874: }
 4875: 
 4876: sub role_status {
 4877:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4878:     my @pwhere = ();
 4879:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4880:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4881:         unless (!defined($$role) || $$role eq '') {
 4882:             $$where=join('.',@pwhere);
 4883:             $$trolecode=$$role.'.'.$$where;
 4884:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4885:             $$tstatus='is';
 4886:             if ($$tstart && $$tstart>$update) {
 4887:                 $$tstatus='future';
 4888:                 if ($$tstart<$now) {
 4889:                     if ($$tstart && $$tstart>$refresh) {
 4890:                         if (($$where ne '') && ($$role ne '')) {
 4891:                             my (%allroles,%allgroups,$group_privs,
 4892:                                 %groups_roles,@rolecodes);
 4893:                             my %userroles = (
 4894:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4895:                             );
 4896:                             @rolecodes = ('cm'); 
 4897:                             my $spec=$$role.'.'.$$where;
 4898:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4899:                             if ($$role =~ /^cr\//) {
 4900:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4901:                                 push(@rolecodes,'cr');
 4902:                             } elsif ($$role eq 'gr') {
 4903:                                 push(@rolecodes,$$role);
 4904:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4905:                                                     $env{'user.name'});
 4906:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4907:                                 (undef,my $group_privs) = split(/\//,$trole);
 4908:                                 $group_privs = &unescape($group_privs);
 4909:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4910:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4911:                                 &get_groups_roles($tdomain,$trest,
 4912:                                                   \%course_roles,\@rolecodes,
 4913:                                                   \%groups_roles);
 4914:                             } else {
 4915:                                 push(@rolecodes,$$role);
 4916:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4917:                             }
 4918:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4919:                             &appenv(\%userroles,\@rolecodes);
 4920:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4921:                         }
 4922:                     }
 4923:                     $$tstatus = 'is';
 4924:                 }
 4925:             }
 4926:             if ($$tend) {
 4927:                 if ($$tend<$update) {
 4928:                     $$tstatus='expired';
 4929:                 } elsif ($$tend<$now) {
 4930:                     $$tstatus='will_not';
 4931:                 }
 4932:             }
 4933:         }
 4934:     }
 4935: }
 4936: 
 4937: sub get_groups_roles {
 4938:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4939:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4940:                   (ref($rolecodes) eq 'ARRAY') && 
 4941:                   (ref($groups_roles) eq 'HASH')); 
 4942:     if (keys(%{$cdom_courseroles}) > 0) {
 4943:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4944:         if ($cdom ne '' && $cnum ne '') {
 4945:             foreach my $key (keys(%{$cdom_courseroles})) {
 4946:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4947:                     my $crsrole = $1;
 4948:                     my $crssec = $2;
 4949:                     if ($crsrole =~ /^cr/) {
 4950:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4951:                             push(@{$rolecodes},'cr');
 4952:                         }
 4953:                     } else {
 4954:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4955:                             push(@{$rolecodes},$crsrole);
 4956:                         }
 4957:                     }
 4958:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4959:                     if ($crssec ne '') {
 4960:                         $rolekey .= "/$crssec";
 4961:                     }
 4962:                     $rolekey .= './';
 4963:                     $groups_roles->{$rolekey} = $rolecodes;
 4964:                 }
 4965:             }
 4966:         }
 4967:     }
 4968:     return;
 4969: }
 4970: 
 4971: sub delete_env_groupprivs {
 4972:     my ($where,$courseroles,$possroles) = @_;
 4973:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4974:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4975:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4976:         %{$courseroles->{$udom}} =
 4977:             &get_my_roles('','','userroles',['active'],
 4978:                           $possroles,[$udom],1);
 4979:     }
 4980:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4981:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4982:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4983:             my $area = '/'.$cdom.'/'.$cnum;
 4984:             my $privkey = "user.priv.$crsrole.$area";
 4985:             if ($crssec ne '') {
 4986:                 $privkey .= '/'.$crssec;
 4987:             }
 4988:             $privkey .= ".$area/$group";
 4989:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4990:         }
 4991:     }
 4992:     return;
 4993: }
 4994: 
 4995: sub check_adhoc_privs {
 4996:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4997:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4998:     if ($env{$cckey}) {
 4999:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5000:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5001:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5002:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5003:         }
 5004:     } else {
 5005:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5006:     }
 5007: }
 5008: 
 5009: sub set_adhoc_privileges {
 5010: # role can be cc or ca
 5011:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5012:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5013:     my $spec = $role.'.'.$area;
 5014:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5015:                                   $env{'user.name'});
 5016:     my %ccrole = ();
 5017:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5018:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5019:     &appenv(\%userroles,[$role,'cm']);
 5020:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5021:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5022:         &appenv( {'request.role'        => $spec,
 5023:                   'request.role.domain' => $dcdom,
 5024:                   'request.course.sec'  => ''
 5025:                  }
 5026:                );
 5027:         my $tadv=0;
 5028:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5029:         &appenv({'request.role.adv'    => $tadv});
 5030:     }
 5031: }
 5032: 
 5033: # --------------------------------------------------------------- get interface
 5034: 
 5035: sub get {
 5036:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5037:    my $items='';
 5038:    foreach my $item (@$storearr) {
 5039:        $items.=&escape($item).'&';
 5040:    }
 5041:    $items=~s/\&$//;
 5042:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5043:    if (!$uname) { $uname=$env{'user.name'}; }
 5044:    my $uhome=&homeserver($uname,$udomain);
 5045: 
 5046:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5047:    my @pairs=split(/\&/,$rep);
 5048:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5049:      return @pairs;
 5050:    }
 5051:    my %returnhash=();
 5052:    my $i=0;
 5053:    foreach my $item (@$storearr) {
 5054:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5055:       $i++;
 5056:    }
 5057:    return %returnhash;
 5058: }
 5059: 
 5060: # --------------------------------------------------------------- del interface
 5061: 
 5062: sub del {
 5063:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5064:    my $items='';
 5065:    foreach my $item (@$storearr) {
 5066:        $items.=&escape($item).'&';
 5067:    }
 5068: 
 5069:    $items=~s/\&$//;
 5070:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5071:    if (!$uname) { $uname=$env{'user.name'}; }
 5072:    my $uhome=&homeserver($uname,$udomain);
 5073:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5074: }
 5075: 
 5076: # -------------------------------------------------------------- dump interface
 5077: 
 5078: sub dump {
 5079:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5080:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5081:     if (!$uname) { $uname=$env{'user.name'}; }
 5082:     my $uhome=&homeserver($uname,$udomain);
 5083: 
 5084:     if ($regexp) {
 5085: 	$regexp=&escape($regexp);
 5086:     } else {
 5087: 	$regexp='.';
 5088:     }
 5089:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5090:     my @pairs=split(/\&/,$rep);
 5091:     my %returnhash=();
 5092:     if (!($rep =~ /^error/ )) {
 5093: 	foreach my $item (@pairs) {
 5094: 	    my ($key,$value)=split(/=/,$item,2);
 5095: 	    $key = &unescape($key);
 5096: 	    next if ($key =~ /^error: 2 /);
 5097: 	    $returnhash{$key}=&thaw_unescape($value);
 5098: 	}
 5099:     }
 5100:     return %returnhash;
 5101: }
 5102: 
 5103: 
 5104: # --------------------------------------------------------- dumpstore interface
 5105: 
 5106: sub dumpstore {
 5107:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5108:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5109:    if (!$uname) { $uname=$env{'user.name'}; }
 5110:    my $uhome=&homeserver($uname,$udomain);
 5111:    if ($regexp) {
 5112:        $regexp=&escape($regexp);
 5113:    } else {
 5114:        $regexp='.';
 5115:    }
 5116:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5117:    my @pairs=split(/\&/,$rep);
 5118:    my %returnhash=();
 5119:    foreach my $item (@pairs) {
 5120:        my ($key,$value)=split(/=/,$item,2);
 5121:        next if ($key =~ /^error: 2 /);
 5122:        $returnhash{$key}=&thaw_unescape($value);
 5123:    }
 5124:    return %returnhash;
 5125: }
 5126: 
 5127: # -------------------------------------------------------------- keys interface
 5128: 
 5129: sub getkeys {
 5130:    my ($namespace,$udomain,$uname)=@_;
 5131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5132:    if (!$uname) { $uname=$env{'user.name'}; }
 5133:    my $uhome=&homeserver($uname,$udomain);
 5134:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5135:    my @keyarray=();
 5136:    foreach my $key (split(/\&/,$rep)) {
 5137:       next if ($key =~ /^error: 2 /);
 5138:       push(@keyarray,&unescape($key));
 5139:    }
 5140:    return @keyarray;
 5141: }
 5142: 
 5143: # --------------------------------------------------------------- currentdump
 5144: sub currentdump {
 5145:    my ($courseid,$sdom,$sname)=@_;
 5146:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5147:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5148:    $sname    = $env{'user.name'}         if (! defined($sname));
 5149:    my $uhome = &homeserver($sname,$sdom);
 5150:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5151:    return if ($rep =~ /^(error:|no_such_host)/);
 5152:    #
 5153:    my %returnhash=();
 5154:    #
 5155:    if ($rep eq "unknown_cmd") { 
 5156:        # an old lond will not know currentdump
 5157:        # Do a dump and make it look like a currentdump
 5158:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5159:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5160:        my %hash = @tmp;
 5161:        @tmp=();
 5162:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5163:    } else {
 5164:        my @pairs=split(/\&/,$rep);
 5165:        foreach my $pair (@pairs) {
 5166:            my ($key,$value)=split(/=/,$pair,2);
 5167:            my ($symb,$param) = split(/:/,$key);
 5168:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5169:                                                         &thaw_unescape($value);
 5170:        }
 5171:    }
 5172:    return %returnhash;
 5173: }
 5174: 
 5175: sub convert_dump_to_currentdump{
 5176:     my %hash = %{shift()};
 5177:     my %returnhash;
 5178:     # Code ripped from lond, essentially.  The only difference
 5179:     # here is the unescaping done by lonnet::dump().  Conceivably
 5180:     # we might run in to problems with parameter names =~ /^v\./
 5181:     while (my ($key,$value) = each(%hash)) {
 5182:         my ($v,$symb,$param) = split(/:/,$key);
 5183: 	$symb  = &unescape($symb);
 5184: 	$param = &unescape($param);
 5185:         next if ($v eq 'version' || $symb eq 'keys');
 5186:         next if (exists($returnhash{$symb}) &&
 5187:                  exists($returnhash{$symb}->{$param}) &&
 5188:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5189:         $returnhash{$symb}->{$param}=$value;
 5190:         $returnhash{$symb}->{'v.'.$param}=$v;
 5191:     }
 5192:     #
 5193:     # Remove all of the keys in the hashes which keep track of
 5194:     # the version of the parameter.
 5195:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5196:         # use a foreach because we are going to delete from the hash.
 5197:         foreach my $key (keys(%$param_hash)) {
 5198:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5199:         }
 5200:     }
 5201:     return \%returnhash;
 5202: }
 5203: 
 5204: # ------------------------------------------------------ critical inc interface
 5205: 
 5206: sub cinc {
 5207:     return &inc(@_,'critical');
 5208: }
 5209: 
 5210: # --------------------------------------------------------------- inc interface
 5211: 
 5212: sub inc {
 5213:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5214:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5215:     if (!$uname) { $uname=$env{'user.name'}; }
 5216:     my $uhome=&homeserver($uname,$udomain);
 5217:     my $items='';
 5218:     if (! ref($store)) {
 5219:         # got a single value, so use that instead
 5220:         $items = &escape($store).'=&';
 5221:     } elsif (ref($store) eq 'SCALAR') {
 5222:         $items = &escape($$store).'=&';        
 5223:     } elsif (ref($store) eq 'ARRAY') {
 5224:         $items = join('=&',map {&escape($_);} @{$store});
 5225:     } elsif (ref($store) eq 'HASH') {
 5226:         while (my($key,$value) = each(%{$store})) {
 5227:             $items.= &escape($key).'='.&escape($value).'&';
 5228:         }
 5229:     }
 5230:     $items=~s/\&$//;
 5231:     if ($critical) {
 5232: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5233:     } else {
 5234: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5235:     }
 5236: }
 5237: 
 5238: # --------------------------------------------------------------- put interface
 5239: 
 5240: sub put {
 5241:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5242:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5243:    if (!$uname) { $uname=$env{'user.name'}; }
 5244:    my $uhome=&homeserver($uname,$udomain);
 5245:    my $items='';
 5246:    foreach my $item (keys(%$storehash)) {
 5247:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5248:    }
 5249:    $items=~s/\&$//;
 5250:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5251: }
 5252: 
 5253: # ------------------------------------------------------------ newput interface
 5254: 
 5255: sub newput {
 5256:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5257:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5258:    if (!$uname) { $uname=$env{'user.name'}; }
 5259:    my $uhome=&homeserver($uname,$udomain);
 5260:    my $items='';
 5261:    foreach my $key (keys(%$storehash)) {
 5262:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5263:    }
 5264:    $items=~s/\&$//;
 5265:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5266: }
 5267: 
 5268: # ---------------------------------------------------------  putstore interface
 5269: 
 5270: sub putstore {
 5271:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5273:    if (!$uname) { $uname=$env{'user.name'}; }
 5274:    my $uhome=&homeserver($uname,$udomain);
 5275:    my $items='';
 5276:    foreach my $key (keys(%$storehash)) {
 5277:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5278:    }
 5279:    $items=~s/\&$//;
 5280:    my $esc_symb=&escape($symb);
 5281:    my $esc_v=&escape($version);
 5282:    my $reply =
 5283:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5284: 	      $uhome);
 5285:    if ($reply eq 'unknown_cmd') {
 5286:        # gfall back to way things use to be done
 5287:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5288: 			    $uname);
 5289:    }
 5290:    return $reply;
 5291: }
 5292: 
 5293: sub old_putstore {
 5294:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5295:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5296:     if (!$uname) { $uname=$env{'user.name'}; }
 5297:     my $uhome=&homeserver($uname,$udomain);
 5298:     my %newstorehash;
 5299:     foreach my $item (keys(%$storehash)) {
 5300: 	my $key = $version.':'.&escape($symb).':'.$item;
 5301: 	$newstorehash{$key} = $storehash->{$item};
 5302:     }
 5303:     my $items='';
 5304:     my %allitems = ();
 5305:     foreach my $item (keys(%newstorehash)) {
 5306: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5307: 	    my $key = $1.':keys:'.$2;
 5308: 	    $allitems{$key} .= $3.':';
 5309: 	}
 5310: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5311:     }
 5312:     foreach my $item (keys(%allitems)) {
 5313: 	$allitems{$item} =~ s/\:$//;
 5314: 	$items.= $item.'='.$allitems{$item}.'&';
 5315:     }
 5316:     $items=~s/\&$//;
 5317:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5318: }
 5319: 
 5320: # ------------------------------------------------------ critical put interface
 5321: 
 5322: sub cput {
 5323:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5324:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5325:    if (!$uname) { $uname=$env{'user.name'}; }
 5326:    my $uhome=&homeserver($uname,$udomain);
 5327:    my $items='';
 5328:    foreach my $item (keys(%$storehash)) {
 5329:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5330:    }
 5331:    $items=~s/\&$//;
 5332:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5333: }
 5334: 
 5335: # -------------------------------------------------------------- eget interface
 5336: 
 5337: sub eget {
 5338:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5339:    my $items='';
 5340:    foreach my $item (@$storearr) {
 5341:        $items.=&escape($item).'&';
 5342:    }
 5343:    $items=~s/\&$//;
 5344:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5345:    if (!$uname) { $uname=$env{'user.name'}; }
 5346:    my $uhome=&homeserver($uname,$udomain);
 5347:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5348:    my @pairs=split(/\&/,$rep);
 5349:    my %returnhash=();
 5350:    my $i=0;
 5351:    foreach my $item (@$storearr) {
 5352:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5353:       $i++;
 5354:    }
 5355:    return %returnhash;
 5356: }
 5357: 
 5358: # ------------------------------------------------------------ tmpput interface
 5359: sub tmpput {
 5360:     my ($storehash,$server,$context)=@_;
 5361:     my $items='';
 5362:     foreach my $item (keys(%$storehash)) {
 5363: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5364:     }
 5365:     $items=~s/\&$//;
 5366:     if (defined($context)) {
 5367:         $items .= ':'.&escape($context);
 5368:     }
 5369:     return &reply("tmpput:$items",$server);
 5370: }
 5371: 
 5372: # ------------------------------------------------------------ tmpget interface
 5373: sub tmpget {
 5374:     my ($token,$server)=@_;
 5375:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5376:     my $rep=&reply("tmpget:$token",$server);
 5377:     my %returnhash;
 5378:     foreach my $item (split(/\&/,$rep)) {
 5379: 	my ($key,$value)=split(/=/,$item);
 5380:         next if ($key =~ /^error: 2 /);
 5381: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5382:     }
 5383:     return %returnhash;
 5384: }
 5385: 
 5386: # ------------------------------------------------------------ tmpdel interface
 5387: sub tmpdel {
 5388:     my ($token,$server)=@_;
 5389:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5390:     return &reply("tmpdel:$token",$server);
 5391: }
 5392: 
 5393: # -------------------------------------------------- portfolio access checking
 5394: 
 5395: sub portfolio_access {
 5396:     my ($requrl) = @_;
 5397:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5398:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5399:     if ($result) {
 5400:         my %setters;
 5401:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5402:             my ($startblock,$endblock) =
 5403:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5404:             if ($startblock && $endblock) {
 5405:                 return 'B';
 5406:             }
 5407:         } else {
 5408:             my ($startblock,$endblock) =
 5409:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5410:             if ($startblock && $endblock) {
 5411:                 return 'B';
 5412:             }
 5413:         }
 5414:     }
 5415:     if ($result eq 'ok') {
 5416:        return 'F';
 5417:     } elsif ($result =~ /^[^:]+:guest_/) {
 5418:        return 'A';
 5419:     }
 5420:     return '';
 5421: }
 5422: 
 5423: sub get_portfolio_access {
 5424:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5425: 
 5426:     if (!ref($access_hash)) {
 5427: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5428: 	my %access_controls = &get_access_controls($current_perms,$group,
 5429: 						   $file_name);
 5430: 	$access_hash = $access_controls{$file_name};
 5431:     }
 5432: 
 5433:     my ($public,$guest,@domains,@users,@courses,@groups);
 5434:     my $now = time;
 5435:     if (ref($access_hash) eq 'HASH') {
 5436:         foreach my $key (keys(%{$access_hash})) {
 5437:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5438:             if ($start > $now) {
 5439:                 next;
 5440:             }
 5441:             if ($end && $end<$now) {
 5442:                 next;
 5443:             }
 5444:             if ($scope eq 'public') {
 5445:                 $public = $key;
 5446:                 last;
 5447:             } elsif ($scope eq 'guest') {
 5448:                 $guest = $key;
 5449:             } elsif ($scope eq 'domains') {
 5450:                 push(@domains,$key);
 5451:             } elsif ($scope eq 'users') {
 5452:                 push(@users,$key);
 5453:             } elsif ($scope eq 'course') {
 5454:                 push(@courses,$key);
 5455:             } elsif ($scope eq 'group') {
 5456:                 push(@groups,$key);
 5457:             }
 5458:         }
 5459:         if ($public) {
 5460:             return 'ok';
 5461:         }
 5462:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5463:             if ($guest) {
 5464:                 return $guest;
 5465:             }
 5466:         } else {
 5467:             if (@domains > 0) {
 5468:                 foreach my $domkey (@domains) {
 5469:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5470:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5471:                             return 'ok';
 5472:                         }
 5473:                     }
 5474:                 }
 5475:             }
 5476:             if (@users > 0) {
 5477:                 foreach my $userkey (@users) {
 5478:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5479:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5480:                             if (ref($item) eq 'HASH') {
 5481:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5482:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5483:                                     return 'ok';
 5484:                                 }
 5485:                             }
 5486:                         }
 5487:                     } 
 5488:                 }
 5489:             }
 5490:             my %roleshash;
 5491:             my @courses_and_groups = @courses;
 5492:             push(@courses_and_groups,@groups); 
 5493:             if (@courses_and_groups > 0) {
 5494:                 my (%allgroups,%allroles); 
 5495:                 my ($start,$end,$role,$sec,$group);
 5496:                 foreach my $envkey (%env) {
 5497:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5498:                         my $cid = $2.'_'.$3; 
 5499:                         if ($1 eq 'gr') {
 5500:                             $group = $4;
 5501:                             $allgroups{$cid}{$group} = $env{$envkey};
 5502:                         } else {
 5503:                             if ($4 eq '') {
 5504:                                 $sec = 'none';
 5505:                             } else {
 5506:                                 $sec = $4;
 5507:                             }
 5508:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5509:                         }
 5510:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5511:                         my $cid = $2.'_'.$3;
 5512:                         if ($4 eq '') {
 5513:                             $sec = 'none';
 5514:                         } else {
 5515:                             $sec = $4;
 5516:                         }
 5517:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5518:                     }
 5519:                 }
 5520:                 if (keys(%allroles) == 0) {
 5521:                     return;
 5522:                 }
 5523:                 foreach my $key (@courses_and_groups) {
 5524:                     my %content = %{$$access_hash{$key}};
 5525:                     my $cnum = $content{'number'};
 5526:                     my $cdom = $content{'domain'};
 5527:                     my $cid = $cdom.'_'.$cnum;
 5528:                     if (!exists($allroles{$cid})) {
 5529:                         next;
 5530:                     }    
 5531:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5532:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5533:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5534:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5535:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5536:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5537:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5538:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5539:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5540:                                         if (grep/^all$/,@sections) {
 5541:                                             return 'ok';
 5542:                                         } else {
 5543:                                             if (grep/^$sec$/,@sections) {
 5544:                                                 return 'ok';
 5545:                                             }
 5546:                                         }
 5547:                                     }
 5548:                                 }
 5549:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5550:                                     if (grep/^none$/,@groups) {
 5551:                                         return 'ok';
 5552:                                     }
 5553:                                 } else {
 5554:                                     if (grep/^all$/,@groups) {
 5555:                                         return 'ok';
 5556:                                     } 
 5557:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5558:                                         if (grep/^$group$/,@groups) {
 5559:                                             return 'ok';
 5560:                                         }
 5561:                                     }
 5562:                                 } 
 5563:                             }
 5564:                         }
 5565:                     }
 5566:                 }
 5567:             }
 5568:             if ($guest) {
 5569:                 return $guest;
 5570:             }
 5571:         }
 5572:     }
 5573:     return;
 5574: }
 5575: 
 5576: sub course_group_datechecker {
 5577:     my ($dates,$now,$status) = @_;
 5578:     my ($start,$end) = split(/\./,$dates);
 5579:     if (!$start && !$end) {
 5580:         return 'ok';
 5581:     }
 5582:     if (grep/^active$/,@{$status}) {
 5583:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5584:             return 'ok';
 5585:         }
 5586:     }
 5587:     if (grep/^previous$/,@{$status}) {
 5588:         if ($end > $now ) {
 5589:             return 'ok';
 5590:         }
 5591:     }
 5592:     if (grep/^future$/,@{$status}) {
 5593:         if ($start > $now) {
 5594:             return 'ok';
 5595:         }
 5596:     }
 5597:     return; 
 5598: }
 5599: 
 5600: sub parse_portfolio_url {
 5601:     my ($url) = @_;
 5602: 
 5603:     my ($type,$udom,$unum,$group,$file_name);
 5604:     
 5605:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5606: 	$type = 1;
 5607:         $udom = $1;
 5608:         $unum = $2;
 5609:         $file_name = $3;
 5610:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5611: 	$type = 2;
 5612:         $udom = $1;
 5613:         $unum = $2;
 5614:         $group = $3;
 5615:         $file_name = $3.'/'.$4;
 5616:     }
 5617:     if (wantarray) {
 5618: 	return ($type,$udom,$unum,$file_name,$group);
 5619:     }
 5620:     return $type;
 5621: }
 5622: 
 5623: sub is_portfolio_url {
 5624:     my ($url) = @_;
 5625:     return scalar(&parse_portfolio_url($url));
 5626: }
 5627: 
 5628: sub is_portfolio_file {
 5629:     my ($file) = @_;
 5630:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5631:         return 1;
 5632:     }
 5633:     return;
 5634: }
 5635: 
 5636: sub usertools_access {
 5637:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5638:     my ($access,%tools);
 5639:     if ($context eq '') {
 5640:         $context = 'tools';
 5641:     }
 5642:     if ($context eq 'requestcourses') {
 5643:         %tools = (
 5644:                       official   => 1,
 5645:                       unofficial => 1,
 5646:                       community  => 1,
 5647:                  );
 5648:     } else {
 5649:         %tools = (
 5650:                       aboutme   => 1,
 5651:                       blog      => 1,
 5652:                       portfolio => 1,
 5653:                  );
 5654:     }
 5655:     return if (!defined($tools{$tool}));
 5656: 
 5657:     if ((!defined($udom)) || (!defined($uname))) {
 5658:         $udom = $env{'user.domain'};
 5659:         $uname = $env{'user.name'};
 5660:     }
 5661: 
 5662:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5663:         if ($action ne 'reload') {
 5664:             if ($context eq 'requestcourses') {
 5665:                 return $env{'environment.canrequest.'.$tool};
 5666:             } else {
 5667:                 return $env{'environment.availabletools.'.$tool};
 5668:             }
 5669:         }
 5670:     }
 5671: 
 5672:     my ($toolstatus,$inststatus);
 5673: 
 5674:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5675:          ($action ne 'reload')) {
 5676:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5677:         $inststatus = $env{'environment.inststatus'};
 5678:     } else {
 5679:         if (ref($userenvref) eq 'HASH') {
 5680:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5681:             $inststatus = $userenvref->{'inststatus'};
 5682:         } else {
 5683:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5684:             $toolstatus = $userenv{$context.'.'.$tool};
 5685:             $inststatus = $userenv{'inststatus'};
 5686:         }
 5687:     }
 5688: 
 5689:     if ($toolstatus ne '') {
 5690:         if ($toolstatus) {
 5691:             $access = 1;
 5692:         } else {
 5693:             $access = 0;
 5694:         }
 5695:         return $access;
 5696:     }
 5697: 
 5698:     my ($is_adv,%domdef);
 5699:     if (ref($is_advref) eq 'HASH') {
 5700:         $is_adv = $is_advref->{'is_adv'};
 5701:     } else {
 5702:         $is_adv = &is_advanced_user($udom,$uname);
 5703:     }
 5704:     if (ref($domdefref) eq 'HASH') {
 5705:         %domdef = %{$domdefref};
 5706:     } else {
 5707:         %domdef = &get_domain_defaults($udom);
 5708:     }
 5709:     if (ref($domdef{$tool}) eq 'HASH') {
 5710:         if ($is_adv) {
 5711:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5712:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5713:                     $access = 1;
 5714:                 } else {
 5715:                     $access = 0;
 5716:                 }
 5717:                 return $access;
 5718:             }
 5719:         }
 5720:         if ($inststatus ne '') {
 5721:             my ($hasaccess,$hasnoaccess);
 5722:             foreach my $affiliation (split(/:/,$inststatus)) {
 5723:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5724:                     if ($domdef{$tool}{$affiliation}) {
 5725:                         $hasaccess = 1;
 5726:                     } else {
 5727:                         $hasnoaccess = 1;
 5728:                     }
 5729:                 }
 5730:             }
 5731:             if ($hasaccess || $hasnoaccess) {
 5732:                 if ($hasaccess) {
 5733:                     $access = 1;
 5734:                 } elsif ($hasnoaccess) {
 5735:                     $access = 0; 
 5736:                 }
 5737:                 return $access;
 5738:             }
 5739:         } else {
 5740:             if ($domdef{$tool}{'default'} ne '') {
 5741:                 if ($domdef{$tool}{'default'}) {
 5742:                     $access = 1;
 5743:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5744:                     $access = 0;
 5745:                 }
 5746:                 return $access;
 5747:             }
 5748:         }
 5749:     } else {
 5750:         if ($context eq 'tools') {
 5751:             $access = 1;
 5752:         } else {
 5753:             $access = 0;
 5754:         }
 5755:         return $access;
 5756:     }
 5757: }
 5758: 
 5759: sub is_course_owner {
 5760:     my ($cdom,$cnum,$udom,$uname) = @_;
 5761:     if (($udom eq '') || ($uname eq '')) {
 5762:         $udom = $env{'user.domain'};
 5763:         $uname = $env{'user.name'};
 5764:     }
 5765:     unless (($udom eq '') || ($uname eq '')) {
 5766:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5767:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5768:                 return 1;
 5769:             } else {
 5770:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5771:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5772:                     return 1;
 5773:                 }
 5774:             }
 5775:         }
 5776:     }
 5777:     return;
 5778: }
 5779: 
 5780: sub is_advanced_user {
 5781:     my ($udom,$uname) = @_;
 5782:     if ($udom ne '' && $uname ne '') {
 5783:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5784:             if (wantarray) {
 5785:                 return ($env{'user.adv'},$env{'user.author'});
 5786:             } else {
 5787:                 return $env{'user.adv'};
 5788:             }
 5789:         }
 5790:     }
 5791:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5792:     my %allroles;
 5793:     my ($is_adv,$is_author);
 5794:     foreach my $role (keys(%roleshash)) {
 5795:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5796:         my $area = '/'.$tdomain.'/'.$trest;
 5797:         if ($sec ne '') {
 5798:             $area .= '/'.$sec;
 5799:         }
 5800:         if (($area ne '') && ($trole ne '')) {
 5801:             my $spec=$trole.'.'.$area;
 5802:             if ($trole =~ /^cr\//) {
 5803:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5804:             } elsif ($trole ne 'gr') {
 5805:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5806:             }
 5807:             if ($trole eq 'au') {
 5808:                 $is_author = 1;
 5809:             }
 5810:         }
 5811:     }
 5812:     foreach my $role (keys(%allroles)) {
 5813:         last if ($is_adv);
 5814:         foreach my $item (split(/:/,$allroles{$role})) {
 5815:             if ($item ne '') {
 5816:                 my ($privilege,$restrictions)=split(/&/,$item);
 5817:                 if ($privilege eq 'adv') {
 5818:                     $is_adv = 1;
 5819:                     last;
 5820:                 }
 5821:             }
 5822:         }
 5823:     }
 5824:     if (wantarray) {
 5825:         return ($is_adv,$is_author);
 5826:     }
 5827:     return $is_adv;
 5828: }
 5829: 
 5830: sub check_can_request {
 5831:     my ($dom,$can_request,$request_domains) = @_;
 5832:     my $canreq = 0;
 5833:     my ($types,$typename) = &Apache::loncommon::course_types();
 5834:     my @options = ('approval','validate','autolimit');
 5835:     my $optregex = join('|',@options);
 5836:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5837:         foreach my $type (@{$types}) {
 5838:             if (&usertools_access($env{'user.name'},
 5839:                                   $env{'user.domain'},
 5840:                                   $type,undef,'requestcourses')) {
 5841:                 $canreq ++;
 5842:                 if (ref($request_domains) eq 'HASH') {
 5843:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5844:                 }
 5845:                 if ($dom eq $env{'user.domain'}) {
 5846:                     $can_request->{$type} = 1;
 5847:                 }
 5848:             }
 5849:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5850:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5851:                 if (@curr > 0) {
 5852:                     foreach my $item (@curr) {
 5853:                         if (ref($request_domains) eq 'HASH') {
 5854:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5855:                             if ($otherdom ne '') {
 5856:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5857:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5858:                                         push(@{$request_domains->{$type}},$otherdom);
 5859:                                     }
 5860:                                 } else {
 5861:                                     push(@{$request_domains->{$type}},$otherdom);
 5862:                                 }
 5863:                             }
 5864:                         }
 5865:                     }
 5866:                     unless($dom eq $env{'user.domain'}) {
 5867:                         $canreq ++;
 5868:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5869:                             $can_request->{$type} = 1;
 5870:                         }
 5871:                     }
 5872:                 }
 5873:             }
 5874:         }
 5875:     }
 5876:     return $canreq;
 5877: }
 5878: 
 5879: # ---------------------------------------------- Custom access rule evaluation
 5880: 
 5881: sub customaccess {
 5882:     my ($priv,$uri)=@_;
 5883:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5884:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5885:     $udom = &LONCAPA::clean_domain($udom);
 5886:     $ucrs = &LONCAPA::clean_username($ucrs);
 5887:     my $access=0;
 5888:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5889: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5890: 	if ($type eq 'user') {
 5891: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5892: 		my ($tdom,$tuname)=split(m{/},$scope);
 5893: 		if ($tdom) {
 5894: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5895: 		}
 5896: 		if ($tuname) {
 5897: 		    if ($tuname ne $env{'user.name'}) { next; }
 5898: 		}
 5899: 		$access=($effect eq 'allow');
 5900: 		last;
 5901: 	    }
 5902: 	} else {
 5903: 	    if ($role) {
 5904: 		if ($role ne $urole) { next; }
 5905: 	    }
 5906: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5907: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5908: 		if ($tdom) {
 5909: 		    if ($tdom ne $udom) { next; }
 5910: 		}
 5911: 		if ($tcrs) {
 5912: 		    if ($tcrs ne $ucrs) { next; }
 5913: 		}
 5914: 		if ($tsec) {
 5915: 		    if ($tsec ne $usec) { next; }
 5916: 		}
 5917: 		$access=($effect eq 'allow');
 5918: 		last;
 5919: 	    }
 5920: 	    if ($realm eq '' && $role eq '') {
 5921: 		$access=($effect eq 'allow');
 5922: 	    }
 5923: 	}
 5924:     }
 5925:     return $access;
 5926: }
 5927: 
 5928: # ------------------------------------------------- Check for a user privilege
 5929: 
 5930: sub allowed {
 5931:     my ($priv,$uri,$symb,$role)=@_;
 5932:     my $ver_orguri=$uri;
 5933:     $uri=&deversion($uri);
 5934:     my $orguri=$uri;
 5935:     $uri=&declutter($uri);
 5936: 
 5937:     if ($priv eq 'evb') {
 5938: # Evade communication block restrictions for specified role in a course
 5939:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5940:             return $1;
 5941:         } else {
 5942:             return;
 5943:         }
 5944:     }
 5945: 
 5946:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5947: # Free bre access to adm and meta resources
 5948:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5949: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5950: 	&& ($priv eq 'bre')) {
 5951: 	return 'F';
 5952:     }
 5953: 
 5954: # Free bre access to user's own portfolio contents
 5955:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5956:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5957: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5958:         my %setters;
 5959:         my ($startblock,$endblock) = 
 5960:             &Apache::loncommon::blockcheck(\%setters,'port');
 5961:         if ($startblock && $endblock) {
 5962:             return 'B';
 5963:         } else {
 5964:             return 'F';
 5965:         }
 5966:     }
 5967: 
 5968: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5969:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5970:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5971:         if (exists($env{'request.course.id'})) {
 5972:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5973:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5974:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5975:                 my $courseprivid=$env{'request.course.id'};
 5976:                 $courseprivid=~s/\_/\//;
 5977:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5978:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5979:                     return $1; 
 5980:                 } else {
 5981:                     if ($env{'request.course.sec'}) {
 5982:                         $courseprivid.='/'.$env{'request.course.sec'};
 5983:                     }
 5984:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5985:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5986:                         return $2;
 5987:                     }
 5988:                 }
 5989:             }
 5990:         }
 5991:     }
 5992: 
 5993: # Free bre to public access
 5994: 
 5995:     if ($priv eq 'bre') {
 5996:         my $copyright=&metadata($uri,'copyright');
 5997: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5998:            return 'F'; 
 5999:         }
 6000:         if ($copyright eq 'priv') {
 6001:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6002: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6003: 		return '';
 6004:             }
 6005:         }
 6006:         if ($copyright eq 'domain') {
 6007:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6008: 	    unless (($env{'user.domain'} eq $1) ||
 6009:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6010: 		return '';
 6011:             }
 6012:         }
 6013:         if ($env{'request.role'}=~ /li\.\//) {
 6014:             # Library role, so allow browsing of resources in this domain.
 6015:             return 'F';
 6016:         }
 6017:         if ($copyright eq 'custom') {
 6018: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6019:         }
 6020:     }
 6021:     # Domain coordinator is trying to create a course
 6022:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6023:         # uri is the requested domain in this case.
 6024:         # comparison to 'request.role.domain' shows if the user has selected
 6025:         # a role of dc for the domain in question.
 6026:         return 'F' if ($uri eq $env{'request.role.domain'});
 6027:     }
 6028: 
 6029:     my $thisallowed='';
 6030:     my $statecond=0;
 6031:     my $courseprivid='';
 6032: 
 6033:     my $ownaccess;
 6034:     # Community Coordinator or Assistant Co-author browsing resource space.
 6035:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6036:         if ($uri eq '') {
 6037:             $ownaccess = 1;
 6038:         } else {
 6039:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6040:                 my $udom = $env{'user.domain'};
 6041:                 my $uname = $env{'user.name'};
 6042:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6043:                     $ownaccess = 1;
 6044:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6045:                     unless ($uri =~ m{\.\./}) {
 6046:                         $ownaccess = 1;
 6047:                     }
 6048:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6049:                     my $now = time;
 6050:                     if ($uri =~ m{^([^/]+)/?$}) {
 6051:                         my $adom = $1;
 6052:                         foreach my $key (keys(%env)) {
 6053:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6054:                                 my ($start,$end) = split('.',$env{$key});
 6055:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6056:                                     $ownaccess = 1;
 6057:                                     last;
 6058:                                 }
 6059:                             }
 6060:                         }
 6061:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6062:                         my $adom = $1;
 6063:                         my $aname = $2;
 6064:                         foreach my $role ('ca','aa') { 
 6065:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6066:                                 my ($start,$end) =
 6067:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6068:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6069:                                     $ownaccess = 1;
 6070:                                     last;
 6071:                                 }
 6072:                             }
 6073:                         }
 6074:                     }
 6075:                 }
 6076:             }
 6077:         }
 6078:     }
 6079: 
 6080: # Course
 6081: 
 6082:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6083:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6084:             $thisallowed.=$1;
 6085:         }
 6086:     }
 6087: 
 6088: # Domain
 6089: 
 6090:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6091:        =~/\Q$priv\E\&([^\:]*)/) {
 6092:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6093:             $thisallowed.=$1;
 6094:         }
 6095:     }
 6096: 
 6097: # User who is not author or co-author might still be able to edit
 6098: # resource of an author in the domain (e.g., if Domain Coordinator).
 6099:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6100:         (&allowed('mdc',$env{'request.course.id'}))) {
 6101:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6102:             $thisallowed.=$1;
 6103:         }
 6104:     }
 6105: 
 6106: # Course: uri itself is a course
 6107:     my $courseuri=$uri;
 6108:     $courseuri=~s/\_(\d)/\/$1/;
 6109:     $courseuri=~s/^([^\/])/\/$1/;
 6110: 
 6111:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6112:        =~/\Q$priv\E\&([^\:]*)/) {
 6113:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6114:             $thisallowed.=$1;
 6115:         }
 6116:     }
 6117: 
 6118: # URI is an uploaded document for this course, default permissions don't matter
 6119: # not allowing 'edit' access (editupload) to uploaded course docs
 6120:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6121: 	$thisallowed='';
 6122:         my ($match)=&is_on_map($uri);
 6123:         if ($match) {
 6124:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6125:                   =~/\Q$priv\E\&([^\:]*)/) {
 6126:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6127:                 if (@blockers > 0) {
 6128:                     $thisallowed = 'B';
 6129:                 } else {
 6130:                     $thisallowed.=$1;
 6131:                 }
 6132:             }
 6133:         } else {
 6134:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6135:             if ($refuri) {
 6136:                 if ($refuri =~ m|^/adm/|) {
 6137:                     $thisallowed='F';
 6138:                 } else {
 6139:                     $refuri=&declutter($refuri);
 6140:                     my ($match) = &is_on_map($refuri);
 6141:                     if ($match) {
 6142:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6143:                         if (@blockers > 0) {
 6144:                             $thisallowed = 'B';
 6145:                         } else {
 6146:                             $thisallowed='F';
 6147:                         }
 6148:                     }
 6149:                 }
 6150:             }
 6151:         }
 6152:     }
 6153: 
 6154:     if ($priv eq 'bre'
 6155: 	&& $thisallowed ne 'F' 
 6156: 	&& $thisallowed ne '2'
 6157: 	&& &is_portfolio_url($uri)) {
 6158: 	$thisallowed = &portfolio_access($uri);
 6159:     }
 6160:     
 6161: # Full access at system, domain or course-wide level? Exit.
 6162:     if ($thisallowed=~/F/) {
 6163: 	return 'F';
 6164:     }
 6165: 
 6166: # If this is generating or modifying users, exit with special codes
 6167: 
 6168:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6169: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6170: 	    my ($audom,$auname)=split('/',$uri);
 6171: # no author name given, so this just checks on the general right to make a co-author in this domain
 6172: 	    unless ($auname) { return $thisallowed; }
 6173: # an author name is given, so we are about to actually make a co-author for a certain account
 6174: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6175: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6176: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6177: 	}
 6178: 	return $thisallowed;
 6179:     }
 6180: #
 6181: # Gathered so far: system, domain and course wide privileges
 6182: #
 6183: # Course: See if uri or referer is an individual resource that is part of 
 6184: # the course
 6185: 
 6186:     if ($env{'request.course.id'}) {
 6187: 
 6188:        $courseprivid=$env{'request.course.id'};
 6189:        if ($env{'request.course.sec'}) {
 6190:           $courseprivid.='/'.$env{'request.course.sec'};
 6191:        }
 6192:        $courseprivid=~s/\_/\//;
 6193:        my $checkreferer=1;
 6194:        my ($match,$cond)=&is_on_map($uri);
 6195:        if ($match) {
 6196:            $statecond=$cond;
 6197:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6198:                =~/\Q$priv\E\&([^\:]*)/) {
 6199:                my $value = $1;
 6200:                if ($priv eq 'bre') {
 6201:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6202:                    if (@blockers > 0) {
 6203:                        $thisallowed = 'B';
 6204:                    } else {
 6205:                        $thisallowed.=$value;
 6206:                    }
 6207:                } else {
 6208:                    $thisallowed.=$value;
 6209:                }
 6210:                $checkreferer=0;
 6211:            }
 6212:        }
 6213:        
 6214:        if ($checkreferer) {
 6215: 	  my $refuri=$env{'httpref.'.$orguri};
 6216:             unless ($refuri) {
 6217:                 foreach my $key (keys(%env)) {
 6218: 		    if ($key=~/^httpref\..*\*/) {
 6219: 			my $pattern=$key;
 6220:                         $pattern=~s/^httpref\.\/res\///;
 6221:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6222:                         $pattern=~s/\//\\\//g;
 6223:                         if ($orguri=~/$pattern/) {
 6224: 			    $refuri=$env{$key};
 6225:                         }
 6226:                     }
 6227:                 }
 6228:             }
 6229: 
 6230:          if ($refuri) { 
 6231: 	  $refuri=&declutter($refuri);
 6232:           my ($match,$cond)=&is_on_map($refuri);
 6233:             if ($match) {
 6234:               my $refstatecond=$cond;
 6235:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6236:                   =~/\Q$priv\E\&([^\:]*)/) {
 6237:                   my $value = $1;
 6238:                   if ($priv eq 'bre') {
 6239:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6240:                       if (@blockers > 0) {
 6241:                           $thisallowed = 'B';
 6242:                       } else {
 6243:                           $thisallowed.=$value;
 6244:                       }
 6245:                   } else {
 6246:                       $thisallowed.=$value;
 6247:                   }
 6248:                   $uri=$refuri;
 6249:                   $statecond=$refstatecond;
 6250:               }
 6251:           }
 6252:         }
 6253:        }
 6254:    }
 6255: 
 6256: #
 6257: # Gathered now: all privileges that could apply, and condition number
 6258: # 
 6259: #
 6260: # Full or no access?
 6261: #
 6262: 
 6263:     if ($thisallowed=~/F/) {
 6264: 	return 'F';
 6265:     }
 6266: 
 6267:     unless ($thisallowed) {
 6268:         return '';
 6269:     }
 6270: 
 6271: # Restrictions exist, deal with them
 6272: #
 6273: #   C:according to course preferences
 6274: #   R:according to resource settings
 6275: #   L:unless locked
 6276: #   X:according to user session state
 6277: #
 6278: 
 6279: # Possibly locked functionality, check all courses
 6280: # Locks might take effect only after 10 minutes cache expiration for other
 6281: # courses, and 2 minutes for current course
 6282: 
 6283:     my $envkey;
 6284:     if ($thisallowed=~/L/) {
 6285:         foreach $envkey (keys(%env)) {
 6286:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6287:                my $courseid=$2;
 6288:                my $roleid=$1.'.'.$2;
 6289:                $courseid=~s/^\///;
 6290:                my $expiretime=600;
 6291:                if ($env{'request.role'} eq $roleid) {
 6292: 		  $expiretime=120;
 6293:                }
 6294: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6295:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6296:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6297: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6298:                }
 6299:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6300:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6301: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6302:                        &log($env{'user.domain'},$env{'user.name'},
 6303:                             $env{'user.home'},
 6304:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6305:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6306:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6307: 		       return '';
 6308:                    }
 6309:                }
 6310:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6311:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6312: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6313:                        &log($env{'user.domain'},$env{'user.name'},
 6314:                             $env{'user.home'},
 6315:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6316:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6317:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6318: 		       return '';
 6319:                    }
 6320:                }
 6321: 	   }
 6322:        }
 6323:     }
 6324:    
 6325: #
 6326: # Rest of the restrictions depend on selected course
 6327: #
 6328: 
 6329:     unless ($env{'request.course.id'}) {
 6330: 	if ($thisallowed eq 'A') {
 6331: 	    return 'A';
 6332:         } elsif ($thisallowed eq 'B') {
 6333:             return 'B';
 6334: 	} else {
 6335: 	    return '1';
 6336: 	}
 6337:     }
 6338: 
 6339: #
 6340: # Now user is definitely in a course
 6341: #
 6342: 
 6343: 
 6344: # Course preferences
 6345: 
 6346:    if ($thisallowed=~/C/) {
 6347:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6348:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6349:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6350: 	   =~/\Q$rolecode\E/) {
 6351: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6352: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6353: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6354: 			$env{'request.course.id'});
 6355: 	   }
 6356:            return '';
 6357:        }
 6358: 
 6359:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6360: 	   =~/\Q$unamedom\E/) {
 6361: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6362: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6363: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6364: 			$env{'request.course.id'});
 6365: 	   }
 6366:            return '';
 6367:        }
 6368:    }
 6369: 
 6370: # Resource preferences
 6371: 
 6372:    if ($thisallowed=~/R/) {
 6373:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6374:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6375: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6376: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6377: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6378: 	   }
 6379: 	   return '';
 6380:        }
 6381:    }
 6382: 
 6383: # Restricted by state or randomout?
 6384: 
 6385:    if ($thisallowed=~/X/) {
 6386:       if ($env{'acc.randomout'}) {
 6387: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6388:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6389:             return ''; 
 6390:          }
 6391:       }
 6392:       if (&condval($statecond)) {
 6393: 	 return '2';
 6394:       } else {
 6395:          return '';
 6396:       }
 6397:    }
 6398: 
 6399:     if ($thisallowed eq 'A') {
 6400: 	return 'A';
 6401:     } elsif ($thisallowed eq 'B') {
 6402:         return 'B';
 6403:     }
 6404:    return 'F';
 6405: }
 6406: 
 6407: sub get_comm_blocks {
 6408:     my ($cdom,$cnum) = @_;
 6409:     if ($cdom eq '' || $cnum eq '') {
 6410:         return unless ($env{'request.course.id'});
 6411:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6412:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6413:     }
 6414:     my %commblocks;
 6415:     my $hashid=$cdom.'_'.$cnum;
 6416:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6417:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6418:         %commblocks = %{$blocksref};
 6419:     } else {
 6420:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6421:         my $cachetime = 600;
 6422:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6423:     }
 6424:     return %commblocks;
 6425: }
 6426: 
 6427: sub has_comm_blocking {
 6428:     my ($priv,$symb,$uri,$blocks) = @_;
 6429:     return unless ($env{'request.course.id'});
 6430:     return unless ($priv eq 'bre');
 6431:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6432:     my %commblocks;
 6433:     if (ref($blocks) eq 'HASH') {
 6434:         %commblocks = %{$blocks};
 6435:     } else {
 6436:         %commblocks = &get_comm_blocks();
 6437:     }
 6438:     return unless (keys(%commblocks) > 0);
 6439:     if (!$symb) { $symb=&symbread($uri,1); }
 6440:     my ($map,$resid,undef)=&decode_symb($symb);
 6441:     my %tocheck = (
 6442:                     maps      => $map,
 6443:                     resources => $symb,
 6444:                   );
 6445:     my @blockers;
 6446:     my $now = time;
 6447:     my $navmap = Apache::lonnavmaps::navmap->new();
 6448:     foreach my $block (keys(%commblocks)) {
 6449:         if ($block =~ /^(\d+)____(\d+)$/) {
 6450:             my ($start,$end) = ($1,$2);
 6451:             if ($start <= $now && $end >= $now) {
 6452:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6453:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6454:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6455:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6456:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6457:                                     push(@blockers,$block);
 6458:                                 }
 6459:                             }
 6460:                         }
 6461:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6462:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6463:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6464:                                     push(@blockers,$block);
 6465:                                 }
 6466:                             }
 6467:                         }
 6468:                     }
 6469:                 }
 6470:             }
 6471:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6472:             my $item = $1;
 6473:             my @to_test;
 6474:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6475:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6476:                     my $check_interval;
 6477:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6478:                         my @interval;
 6479:                         my $type = 'map';
 6480:                         if ($item eq 'course') {
 6481:                             $type = 'course';
 6482:                             @interval=&EXT("resource.0.interval");
 6483:                         } else {
 6484:                             if ($item =~ /___\d+___/) {
 6485:                                 $type = 'resource';
 6486:                                 @interval=&EXT("resource.0.interval",$item);
 6487:                                 if (ref($navmap)) {                        
 6488:                                     my $res = $navmap->getBySymb($item); 
 6489:                                     push(@to_test,$res);
 6490:                                 }
 6491:                             } else {
 6492:                                 my $mapsymb = &symbread($item,1);
 6493:                                 if ($mapsymb) {
 6494:                                     if (ref($navmap)) {
 6495:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6496:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6497:                                         foreach my $res (@to_test) {
 6498:                                             my $symb = $res->symb();
 6499:                                             next if ($symb eq $mapsymb);
 6500:                                             if ($symb ne '') {
 6501:                                                 @interval=&EXT("resource.0.interval",$symb);
 6502:                                                 last;
 6503:                                             }
 6504:                                         }
 6505:                                     }
 6506:                                 }
 6507:                             }
 6508:                         }
 6509:                         if ($interval[0] =~ /\d+/) {
 6510:                             my $first_access;
 6511:                             if ($type eq 'resource') {
 6512:                                 $first_access=&get_first_access($interval[1],$item);
 6513:                             } elsif ($type eq 'map') {
 6514:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6515:                             } else {
 6516:                                 $first_access=&get_first_access($interval[1]);
 6517:                             }
 6518:                             if ($first_access) {
 6519:                                 my $timesup = $first_access+$interval[0];
 6520:                                 if ($timesup > $now) {
 6521:                                     foreach my $res (@to_test) {
 6522:                                         if ($res->is_problem()) {
 6523:                                             if ($res->completable()) {
 6524:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6525:                                                     push(@blockers,$block);
 6526:                                                 }
 6527:                                                 last;
 6528:                                             }
 6529:                                         }
 6530:                                     }
 6531:                                 }
 6532:                             }
 6533:                         }
 6534:                     }
 6535:                 }
 6536:             }
 6537:         }
 6538:     }
 6539:     return @blockers;
 6540: }
 6541: 
 6542: sub check_docs_block {
 6543:     my ($docsblock,$tocheck) =@_;
 6544:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6545:         return;
 6546:     }
 6547:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6548:         if ($tocheck->{'maps'}) {
 6549:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6550:                 return 1;
 6551:             }
 6552:         }
 6553:     }
 6554:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6555:         if ($tocheck->{'resources'}) {
 6556:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6557:                 return 1;
 6558:             }
 6559:         }
 6560:     }
 6561:     return;
 6562: }
 6563: 
 6564: #
 6565: #   Removes the versino from a URI and
 6566: #   splits it in to its filename and path to the filename.
 6567: #   Seems like File::Basename could have done this more clearly.
 6568: #   Parameters:
 6569: #      $uri   - input URI
 6570: #   Returns:
 6571: #     Two element list consisting of 
 6572: #     $pathname  - the URI up to and excluding the trailing /
 6573: #     $filename  - The part of the URI following the last /
 6574: #  NOTE:
 6575: #    Another realization of this is simply:
 6576: #    use File::Basename;
 6577: #    ...
 6578: #    $uri = shift;
 6579: #    $filename = basename($uri);
 6580: #    $path     = dirname($uri);
 6581: #    return ($filename, $path);
 6582: #
 6583: #     The implementation below is probably faster however.
 6584: #
 6585: sub split_uri_for_cond {
 6586:     my $uri=&deversion(&declutter(shift));
 6587:     my @uriparts=split(/\//,$uri);
 6588:     my $filename=pop(@uriparts);
 6589:     my $pathname=join('/',@uriparts);
 6590:     return ($pathname,$filename);
 6591: }
 6592: # --------------------------------------------------- Is a resource on the map?
 6593: 
 6594: sub is_on_map {
 6595:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6596:     #Trying to find the conditional for the file
 6597:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6598: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6599:     if ($match) {
 6600: 	return (1,$1);
 6601:     } else {
 6602: 	return (0,0);
 6603:     }
 6604: }
 6605: 
 6606: # --------------------------------------------------------- Get symb from alias
 6607: 
 6608: sub get_symb_from_alias {
 6609:     my $symb=shift;
 6610:     my ($map,$resid,$url)=&decode_symb($symb);
 6611: # Already is a symb
 6612:     if ($url) { return $symb; }
 6613: # Must be an alias
 6614:     my $aliassymb='';
 6615:     my %bighash;
 6616:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6617:                             &GDBM_READER(),0640)) {
 6618:         my $rid=$bighash{'mapalias_'.$symb};
 6619: 	if ($rid) {
 6620: 	    my ($mapid,$resid)=split(/\./,$rid);
 6621: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6622: 				    $resid,$bighash{'src_'.$rid});
 6623: 	}
 6624:         untie %bighash;
 6625:     }
 6626:     return $aliassymb;
 6627: }
 6628: 
 6629: # ----------------------------------------------------------------- Define Role
 6630: 
 6631: sub definerole {
 6632:   if (allowed('mcr','/')) {
 6633:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6634:     foreach my $role (split(':',$sysrole)) {
 6635: 	my ($crole,$cqual)=split(/\&/,$role);
 6636:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6637:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6638: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6639:                return "refused:s:$crole&$cqual"; 
 6640:             }
 6641:         }
 6642:     }
 6643:     foreach my $role (split(':',$domrole)) {
 6644: 	my ($crole,$cqual)=split(/\&/,$role);
 6645:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6646:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6647: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6648:                return "refused:d:$crole&$cqual"; 
 6649:             }
 6650:         }
 6651:     }
 6652:     foreach my $role (split(':',$courole)) {
 6653: 	my ($crole,$cqual)=split(/\&/,$role);
 6654:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6655:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6656: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6657:                return "refused:c:$crole&$cqual"; 
 6658:             }
 6659:         }
 6660:     }
 6661:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6662:                 "$env{'user.domain'}:$env{'user.name'}:".
 6663: 	        "rolesdef_$rolename=".
 6664:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6665:     return reply($command,$env{'user.home'});
 6666:   } else {
 6667:     return 'refused';
 6668:   }
 6669: }
 6670: 
 6671: # ---------------- Make a metadata query against the network of library servers
 6672: 
 6673: sub metadata_query {
 6674:     my ($query,$custom,$customshow,$server_array)=@_;
 6675:     my %rhash;
 6676:     my %libserv = &all_library();
 6677:     my @server_list = (defined($server_array) ? @$server_array
 6678:                                               : keys(%libserv) );
 6679:     for my $server (@server_list) {
 6680: 	unless ($custom or $customshow) {
 6681: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6682: 	    $rhash{$server}=$reply;
 6683: 	}
 6684: 	else {
 6685: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6686: 			     &escape($custom).':'.&escape($customshow),
 6687: 			     $server);
 6688: 	    $rhash{$server}=$reply;
 6689: 	}
 6690:     }
 6691:     return \%rhash;
 6692: }
 6693: 
 6694: # ----------------------------------------- Send log queries and wait for reply
 6695: 
 6696: sub log_query {
 6697:     my ($uname,$udom,$query,%filters)=@_;
 6698:     my $uhome=&homeserver($uname,$udom);
 6699:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6700:     my $uhost=&hostname($uhome);
 6701:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6702:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6703:                        $uhome);
 6704:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6705:     return get_query_reply($queryid);
 6706: }
 6707: 
 6708: # -------------------------- Update MySQL table for portfolio file
 6709: 
 6710: sub update_portfolio_table {
 6711:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6712:     if ($group ne '') {
 6713:         $file_name =~s /^\Q$group\E//;
 6714:     }
 6715:     my $homeserver = &homeserver($uname,$udom);
 6716:     my $queryid=
 6717:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6718:                ':'.&escape($file_name).':'.$action,$homeserver);
 6719:     my $reply = &get_query_reply($queryid);
 6720:     return $reply;
 6721: }
 6722: 
 6723: # -------------------------- Update MySQL allusers table
 6724: 
 6725: sub update_allusers_table {
 6726:     my ($uname,$udom,$names) = @_;
 6727:     my $homeserver = &homeserver($uname,$udom);
 6728:     my $queryid=
 6729:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6730:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6731:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6732:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6733:                'generation='.&escape($names->{'generation'}).'%%'.
 6734:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6735:                'id='.&escape($names->{'id'}),$homeserver);
 6736:     return;
 6737: }
 6738: 
 6739: # ------- Request retrieval of institutional classlists for course(s)
 6740: 
 6741: sub fetch_enrollment_query {
 6742:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6743:     my $homeserver;
 6744:     my $maxtries = 1;
 6745:     if ($context eq 'automated') {
 6746:         $homeserver = $perlvar{'lonHostID'};
 6747:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6748:     } else {
 6749:         $homeserver = &homeserver($cnum,$dom);
 6750:     }
 6751:     my $host=&hostname($homeserver);
 6752:     my $cmd = '';
 6753:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6754:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6755:     }
 6756:     $cmd =~ s/%%$//;
 6757:     $cmd = &escape($cmd);
 6758:     my $query = 'fetchenrollment';
 6759:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6760:     unless ($queryid=~/^\Q$host\E\_/) { 
 6761:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6762:         return 'error: '.$queryid;
 6763:     }
 6764:     my $reply = &get_query_reply($queryid);
 6765:     my $tries = 1;
 6766:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6767:         $reply = &get_query_reply($queryid);
 6768:         $tries ++;
 6769:     }
 6770:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6771:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6772:     } else {
 6773:         my @responses = split(/:/,$reply);
 6774:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6775:             foreach my $line (@responses) {
 6776:                 my ($key,$value) = split(/=/,$line,2);
 6777:                 $$replyref{$key} = $value;
 6778:             }
 6779:         } else {
 6780:             my $pathname = LONCAPA::tempdir();
 6781:             foreach my $line (@responses) {
 6782:                 my ($key,$value) = split(/=/,$line);
 6783:                 $$replyref{$key} = $value;
 6784:                 if ($value > 0) {
 6785:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6786:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6787:                         my $destname = $pathname.'/'.$filename;
 6788:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6789:                         if ($xml_classlist =~ /^error/) {
 6790:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6791:                         } else {
 6792:                             if ( open(FILE,">$destname") ) {
 6793:                                 print FILE &unescape($xml_classlist);
 6794:                                 close(FILE);
 6795:                             } else {
 6796:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6797:                             }
 6798:                         }
 6799:                     }
 6800:                 }
 6801:             }
 6802:         }
 6803:         return 'ok';
 6804:     }
 6805:     return 'error';
 6806: }
 6807: 
 6808: sub get_query_reply {
 6809:     my $queryid=shift;
 6810:     my $replyfile=LONCAPA::tempdir().$queryid;
 6811:     my $reply='';
 6812:     for (1..100) {
 6813: 	sleep 2;
 6814:         if (-e $replyfile.'.end') {
 6815: 	    if (open(my $fh,$replyfile)) {
 6816: 		$reply = join('',<$fh>);
 6817: 		close($fh);
 6818: 	   } else { return 'error: reply_file_error'; }
 6819:            return &unescape($reply);
 6820: 	}
 6821:     }
 6822:     return 'timeout:'.$queryid;
 6823: }
 6824: 
 6825: sub courselog_query {
 6826: #
 6827: # possible filters:
 6828: # url: url or symb
 6829: # username
 6830: # domain
 6831: # action: view, submit, grade
 6832: # start: timestamp
 6833: # end: timestamp
 6834: #
 6835:     my (%filters)=@_;
 6836:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6837:     if ($filters{'url'}) {
 6838: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6839:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6840:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6841:     }
 6842:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6843:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6844:     return &log_query($cname,$cdom,'courselog',%filters);
 6845: }
 6846: 
 6847: sub userlog_query {
 6848: #
 6849: # possible filters:
 6850: # action: log check role
 6851: # start: timestamp
 6852: # end: timestamp
 6853: #
 6854:     my ($uname,$udom,%filters)=@_;
 6855:     return &log_query($uname,$udom,'userlog',%filters);
 6856: }
 6857: 
 6858: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6859: 
 6860: sub auto_run {
 6861:     my ($cnum,$cdom) = @_;
 6862:     my $response = 0;
 6863:     my $settings;
 6864:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6865:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6866:         $settings = $domconfig{'autoenroll'};
 6867:         if ($settings->{'run'} eq '1') {
 6868:             $response = 1;
 6869:         }
 6870:     } else {
 6871:         my $homeserver;
 6872:         if (&is_course($cdom,$cnum)) {
 6873:             $homeserver = &homeserver($cnum,$cdom);
 6874:         } else {
 6875:             $homeserver = &domain($cdom,'primary');
 6876:         }
 6877:         if ($homeserver ne 'no_host') {
 6878:             $response = &reply('autorun:'.$cdom,$homeserver);
 6879:         }
 6880:     }
 6881:     return $response;
 6882: }
 6883: 
 6884: sub auto_get_sections {
 6885:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6886:     my $homeserver;
 6887:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6888:         $homeserver = &homeserver($cnum,$cdom);
 6889:     }
 6890:     if (!defined($homeserver)) { 
 6891:         if ($cdom =~ /^$match_domain$/) {
 6892:             $homeserver = &domain($cdom,'primary');
 6893:         }
 6894:     }
 6895:     my @secs;
 6896:     if (defined($homeserver)) {
 6897:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6898:         unless ($response eq 'refused') {
 6899:             @secs = split(/:/,$response);
 6900:         }
 6901:     }
 6902:     return @secs;
 6903: }
 6904: 
 6905: sub auto_new_course {
 6906:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6907:     my $homeserver = &homeserver($cnum,$cdom);
 6908:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6909:     return $response;
 6910: }
 6911: 
 6912: sub auto_validate_courseID {
 6913:     my ($cnum,$cdom,$inst_course_id) = @_;
 6914:     my $homeserver = &homeserver($cnum,$cdom);
 6915:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6916:     return $response;
 6917: }
 6918: 
 6919: sub auto_validate_instcode {
 6920:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6921:     my ($homeserver,$response);
 6922:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6923:         $homeserver = &homeserver($cnum,$cdom);
 6924:     }
 6925:     if (!defined($homeserver)) {
 6926:         if ($cdom =~ /^$match_domain$/) {
 6927:             $homeserver = &domain($cdom,'primary');
 6928:         }
 6929:     }
 6930:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6931:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6932:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6933:     return ($outcome,$description);
 6934: }
 6935: 
 6936: sub auto_create_password {
 6937:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6938:     my ($homeserver,$response);
 6939:     my $create_passwd = 0;
 6940:     my $authchk = '';
 6941:     if ($udom =~ /^$match_domain$/) {
 6942:         $homeserver = &domain($udom,'primary');
 6943:     }
 6944:     if ($homeserver eq '') {
 6945:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6946:             $homeserver = &homeserver($cnum,$cdom);
 6947:         }
 6948:     }
 6949:     if ($homeserver eq '') {
 6950:         $authchk = 'nodomain';
 6951:     } else {
 6952:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6953:         if ($response eq 'refused') {
 6954:             $authchk = 'refused';
 6955:         } else {
 6956:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6957:         }
 6958:     }
 6959:     return ($authparam,$create_passwd,$authchk);
 6960: }
 6961: 
 6962: sub auto_photo_permission {
 6963:     my ($cnum,$cdom,$students) = @_;
 6964:     my $homeserver = &homeserver($cnum,$cdom);
 6965:     my ($outcome,$perm_reqd,$conditions) = 
 6966: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6967:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6968: 	return (undef,undef);
 6969:     }
 6970:     return ($outcome,$perm_reqd,$conditions);
 6971: }
 6972: 
 6973: sub auto_checkphotos {
 6974:     my ($uname,$udom,$pid) = @_;
 6975:     my $homeserver = &homeserver($uname,$udom);
 6976:     my ($result,$resulttype);
 6977:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6978: 				   &escape($uname).':'.&escape($pid),
 6979: 				   $homeserver));
 6980:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6981: 	return (undef,undef);
 6982:     }
 6983:     if ($outcome) {
 6984:         ($result,$resulttype) = split(/:/,$outcome);
 6985:     } 
 6986:     return ($result,$resulttype);
 6987: }
 6988: 
 6989: sub auto_photochoice {
 6990:     my ($cnum,$cdom) = @_;
 6991:     my $homeserver = &homeserver($cnum,$cdom);
 6992:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6993: 						       &escape($cdom),
 6994: 						       $homeserver)));
 6995:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6996: 	return (undef,undef);
 6997:     }
 6998:     return ($update,$comment);
 6999: }
 7000: 
 7001: sub auto_photoupdate {
 7002:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7003:     my $homeserver = &homeserver($cnum,$dom);
 7004:     my $host=&hostname($homeserver);
 7005:     my $cmd = '';
 7006:     my $maxtries = 1;
 7007:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7008:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7009:     }
 7010:     $cmd =~ s/%%$//;
 7011:     $cmd = &escape($cmd);
 7012:     my $query = 'institutionalphotos';
 7013:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7014:     unless ($queryid=~/^\Q$host\E\_/) {
 7015:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7016:         return 'error: '.$queryid;
 7017:     }
 7018:     my $reply = &get_query_reply($queryid);
 7019:     my $tries = 1;
 7020:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7021:         $reply = &get_query_reply($queryid);
 7022:         $tries ++;
 7023:     }
 7024:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7025:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7026:     } else {
 7027:         my @responses = split(/:/,$reply);
 7028:         my $outcome = shift(@responses); 
 7029:         foreach my $item (@responses) {
 7030:             my ($key,$value) = split(/=/,$item);
 7031:             $$photo{$key} = $value;
 7032:         }
 7033:         return $outcome;
 7034:     }
 7035:     return 'error';
 7036: }
 7037: 
 7038: sub auto_instcode_format {
 7039:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7040: 	$cat_order) = @_;
 7041:     my $courses = '';
 7042:     my @homeservers;
 7043:     if ($caller eq 'global') {
 7044: 	my %servers = &get_servers($codedom,'library');
 7045: 	foreach my $tryserver (keys(%servers)) {
 7046: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7047: 		push(@homeservers,$tryserver);
 7048: 	    }
 7049:         }
 7050:     } elsif ($caller eq 'requests') {
 7051:         if ($codedom =~ /^$match_domain$/) {
 7052:             my $chome = &domain($codedom,'primary');
 7053:             unless ($chome eq 'no_host') {
 7054:                 push(@homeservers,$chome);
 7055:             }
 7056:         }
 7057:     } else {
 7058:         push(@homeservers,&homeserver($caller,$codedom));
 7059:     }
 7060:     foreach my $code (keys(%{$instcodes})) {
 7061:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7062:     }
 7063:     chop($courses);
 7064:     my $ok_response = 0;
 7065:     my $response;
 7066:     while (@homeservers > 0 && $ok_response == 0) {
 7067:         my $server = shift(@homeservers); 
 7068:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7069:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7070:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7071: 		split(/:/,$response);
 7072:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7073:             push(@{$codetitles},&str2array($codetitles_str));
 7074:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7075:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7076:             $ok_response = 1;
 7077:         }
 7078:     }
 7079:     if ($ok_response) {
 7080:         return 'ok';
 7081:     } else {
 7082:         return $response;
 7083:     }
 7084: }
 7085: 
 7086: sub auto_instcode_defaults {
 7087:     my ($domain,$returnhash,$code_order) = @_;
 7088:     my @homeservers;
 7089: 
 7090:     my %servers = &get_servers($domain,'library');
 7091:     foreach my $tryserver (keys(%servers)) {
 7092: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7093: 	    push(@homeservers,$tryserver);
 7094: 	}
 7095:     }
 7096: 
 7097:     my $response;
 7098:     foreach my $server (@homeservers) {
 7099:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7100:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7101: 	
 7102: 	foreach my $pair (split(/\&/,$response)) {
 7103: 	    my ($name,$value)=split(/\=/,$pair);
 7104: 	    if ($name eq 'code_order') {
 7105: 		@{$code_order} = split(/\&/,&unescape($value));
 7106: 	    } else {
 7107: 		$returnhash->{&unescape($name)}=&unescape($value);
 7108: 	    }
 7109: 	}
 7110: 	return 'ok';
 7111:     }
 7112: 
 7113:     return $response;
 7114: }
 7115: 
 7116: sub auto_possible_instcodes {
 7117:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7118:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7119:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7120:         return;
 7121:     }
 7122:     my (@homeservers,$uhome);
 7123:     if (defined(&domain($domain,'primary'))) {
 7124:         $uhome=&domain($domain,'primary');
 7125:         push(@homeservers,&domain($domain,'primary'));
 7126:     } else {
 7127:         my %servers = &get_servers($domain,'library');
 7128:         foreach my $tryserver (keys(%servers)) {
 7129:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7130:                 push(@homeservers,$tryserver);
 7131:             }
 7132:         }
 7133:     }
 7134:     my $response;
 7135:     foreach my $server (@homeservers) {
 7136:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7137:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7138:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7139:             split(':',$response);
 7140:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7141:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7142:         foreach my $item (split('&',$cat_title)) {   
 7143:             my ($name,$value)=split('=',$item);
 7144:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7145:         }
 7146:         foreach my $item (split('&',$cat_order)) {
 7147:             my ($name,$value)=split('=',$item);
 7148:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7149:         }
 7150:         return 'ok';
 7151:     }
 7152:     return $response;
 7153: }
 7154: 
 7155: sub auto_courserequest_checks {
 7156:     my ($dom) = @_;
 7157:     my ($homeserver,%validations);
 7158:     if ($dom =~ /^$match_domain$/) {
 7159:         $homeserver = &domain($dom,'primary');
 7160:     }
 7161:     unless ($homeserver eq 'no_host') {
 7162:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7163:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7164:             my @items = split(/&/,$response);
 7165:             foreach my $item (@items) {
 7166:                 my ($key,$value) = split('=',$item);
 7167:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7168:             }
 7169:         }
 7170:     }
 7171:     return %validations; 
 7172: }
 7173: 
 7174: sub auto_courserequest_validation {
 7175:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7176:     my ($homeserver,$response);
 7177:     if ($dom =~ /^$match_domain$/) {
 7178:         $homeserver = &domain($dom,'primary');
 7179:     }
 7180:     unless ($homeserver eq 'no_host') {  
 7181:           
 7182:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7183:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7184:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7185:                                     $homeserver));
 7186:     }
 7187:     return $response;
 7188: }
 7189: 
 7190: sub auto_validate_class_sec {
 7191:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7192:     my $homeserver = &homeserver($cnum,$cdom);
 7193:     my $ownerlist;
 7194:     if (ref($owners) eq 'ARRAY') {
 7195:         $ownerlist = join(',',@{$owners});
 7196:     } else {
 7197:         $ownerlist = $owners;
 7198:     }
 7199:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7200:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7201:     return $response;
 7202: }
 7203: 
 7204: # ------------------------------------------------------- Course Group routines
 7205: 
 7206: sub get_coursegroups {
 7207:     my ($cdom,$cnum,$group,$namespace) = @_;
 7208:     return(&dump($namespace,$cdom,$cnum,$group));
 7209: }
 7210: 
 7211: sub modify_coursegroup {
 7212:     my ($cdom,$cnum,$groupsettings) = @_;
 7213:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7214: }
 7215: 
 7216: sub toggle_coursegroup_status {
 7217:     my ($cdom,$cnum,$group,$action) = @_;
 7218:     my ($from_namespace,$to_namespace);
 7219:     if ($action eq 'delete') {
 7220:         $from_namespace = 'coursegroups';
 7221:         $to_namespace = 'deleted_groups';
 7222:     } else {
 7223:         $from_namespace = 'deleted_groups';
 7224:         $to_namespace = 'coursegroups';
 7225:     }
 7226:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7227:     if (my $tmp = &error(%curr_group)) {
 7228:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7229:         return ('read error',$tmp);
 7230:     } else {
 7231:         my %savedsettings = %curr_group; 
 7232:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7233:         my $deloutcome;
 7234:         if ($result eq 'ok') {
 7235:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7236:         } else {
 7237:             return ('write error',$result);
 7238:         }
 7239:         if ($deloutcome eq 'ok') {
 7240:             return 'ok';
 7241:         } else {
 7242:             return ('delete error',$deloutcome);
 7243:         }
 7244:     }
 7245: }
 7246: 
 7247: sub modify_group_roles {
 7248:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7249:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7250:     my $role = 'gr/'.&escape($userprivs);
 7251:     my ($uname,$udom) = split(/:/,$user);
 7252:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7253:     if ($result eq 'ok') {
 7254:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7255:     }
 7256:     return $result;
 7257: }
 7258: 
 7259: sub modify_coursegroup_membership {
 7260:     my ($cdom,$cnum,$membership) = @_;
 7261:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7262:     return $result;
 7263: }
 7264: 
 7265: sub get_active_groups {
 7266:     my ($udom,$uname,$cdom,$cnum) = @_;
 7267:     my $now = time;
 7268:     my %groups = ();
 7269:     foreach my $key (keys(%env)) {
 7270:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7271:             my ($start,$end) = split(/\./,$env{$key});
 7272:             if (($end!=0) && ($end<$now)) { next; }
 7273:             if (($start!=0) && ($start>$now)) { next; }
 7274:             if ($1 eq $cdom && $2 eq $cnum) {
 7275:                 $groups{$3} = $env{$key} ;
 7276:             }
 7277:         }
 7278:     }
 7279:     return %groups;
 7280: }
 7281: 
 7282: sub get_group_membership {
 7283:     my ($cdom,$cnum,$group) = @_;
 7284:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7285: }
 7286: 
 7287: sub get_users_groups {
 7288:     my ($udom,$uname,$courseid) = @_;
 7289:     my @usersgroups;
 7290:     my $cachetime=1800;
 7291: 
 7292:     my $hashid="$udom:$uname:$courseid";
 7293:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7294:     if (defined($cached)) {
 7295:         @usersgroups = split(/:/,$grouplist);
 7296:     } else {  
 7297:         $grouplist = '';
 7298:         my $courseurl = &courseid_to_courseurl($courseid);
 7299:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7300:         my $access_end = $env{'course.'.$courseid.
 7301:                               '.default_enrollment_end_date'};
 7302:         my $now = time;
 7303:         foreach my $key (keys(%roleshash)) {
 7304:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7305:                 my $group = $1;
 7306:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7307:                     my $start = $2;
 7308:                     my $end = $1;
 7309:                     if ($start == -1) { next; } # deleted from group
 7310:                     if (($start!=0) && ($start>$now)) { next; }
 7311:                     if (($end!=0) && ($end<$now)) {
 7312:                         if ($access_end && $access_end < $now) {
 7313:                             if ($access_end - $end < 86400) {
 7314:                                 push(@usersgroups,$group);
 7315:                             }
 7316:                         }
 7317:                         next;
 7318:                     }
 7319:                     push(@usersgroups,$group);
 7320:                 }
 7321:             }
 7322:         }
 7323:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7324:         $grouplist = join(':',@usersgroups);
 7325:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7326:     }
 7327:     return @usersgroups;
 7328: }
 7329: 
 7330: sub devalidate_getgroups_cache {
 7331:     my ($udom,$uname,$cdom,$cnum)=@_;
 7332:     my $courseid = $cdom.'_'.$cnum;
 7333: 
 7334:     my $hashid="$udom:$uname:$courseid";
 7335:     &devalidate_cache_new('getgroups',$hashid);
 7336: }
 7337: 
 7338: # ------------------------------------------------------------------ Plain Text
 7339: 
 7340: sub plaintext {
 7341:     my ($short,$type,$cid,$forcedefault) = @_;
 7342:     if ($short =~ m{^cr/}) {
 7343: 	return (split('/',$short))[-1];
 7344:     }
 7345:     if (!defined($cid)) {
 7346:         $cid = $env{'request.course.id'};
 7347:     }
 7348:     my %rolenames = (
 7349:                       Course    => 'std',
 7350:                       Community => 'alt1',
 7351:                     );
 7352:     if ($cid ne '') {
 7353:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7354:             unless ($forcedefault) {
 7355:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7356:                 &Apache::lonlocal::mt_escape(\$roletext);
 7357:                 return &Apache::lonlocal::mt($roletext);
 7358:             }
 7359:         }
 7360:     }
 7361:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7362:         (defined($rolenames{$type})) && 
 7363:         (defined($prp{$short}{$rolenames{$type}}))) {
 7364:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7365:     } elsif ($cid ne '') {
 7366:         my $crstype = $env{'course.'.$cid.'.type'};
 7367:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7368:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7369:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7370:         }
 7371:     }
 7372:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7373: }
 7374: 
 7375: # ----------------------------------------------------------------- Assign Role
 7376: 
 7377: sub assignrole {
 7378:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7379:         $context)=@_;
 7380:     my $mrole;
 7381:     if ($role =~ /^cr\//) {
 7382:         my $cwosec=$url;
 7383:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7384: 	unless (&allowed('ccr',$cwosec)) {
 7385:            my $refused = 1;
 7386:            if ($context eq 'requestcourses') {
 7387:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7388:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7389:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7390:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7391:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7392:                            if ($crsenv{'internal.courseowner'} eq
 7393:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7394:                                $refused = '';
 7395:                            }
 7396:                        }
 7397:                    }
 7398:                }
 7399:            }
 7400:            if ($refused) {
 7401:                &logthis('Refused custom assignrole: '.
 7402:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7403:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7404:                return 'refused';
 7405:            }
 7406:         }
 7407:         $mrole='cr';
 7408:     } elsif ($role =~ /^gr\//) {
 7409:         my $cwogrp=$url;
 7410:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7411:         unless (&allowed('mdg',$cwogrp)) {
 7412:             &logthis('Refused group assignrole: '.
 7413:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7414:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7415:             return 'refused';
 7416:         }
 7417:         $mrole='gr';
 7418:     } else {
 7419:         my $cwosec=$url;
 7420:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7421:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7422:             my $refused;
 7423:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7424:                 if (!(&allowed('c'.$role,$url))) {
 7425:                     $refused = 1;
 7426:                 }
 7427:             } else {
 7428:                 $refused = 1;
 7429:             }
 7430:             if ($refused) {
 7431:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7432:                 if (!$selfenroll && $context eq 'course') {
 7433:                     my %crsenv;
 7434:                     if ($role eq 'cc' || $role eq 'co') {
 7435:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7436:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7437:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7438:                                 if ($crsenv{'internal.courseowner'} eq 
 7439:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7440:                                     $refused = '';
 7441:                                 }
 7442:                             }
 7443:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7444:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7445:                                 if ($crsenv{'internal.courseowner'} eq 
 7446:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7447:                                     $refused = '';
 7448:                                 }
 7449:                             }
 7450:                         }
 7451:                     }
 7452:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7453:                     $refused = '';
 7454:                 } elsif ($context eq 'requestcourses') {
 7455:                     my @possroles = ('st','ta','ep','in','cc','co');
 7456:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7457:                         my $wrongcc;
 7458:                         if ($cnum =~ /^$match_community$/) {
 7459:                             $wrongcc = 1 if ($role eq 'cc');
 7460:                         } else {
 7461:                             $wrongcc = 1 if ($role eq 'co');
 7462:                         }
 7463:                         unless ($wrongcc) {
 7464:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7465:                             if ($crsenv{'internal.courseowner'} eq 
 7466:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7467:                                 $refused = '';
 7468:                             }
 7469:                         }
 7470:                     }
 7471:                 }
 7472:                 if ($refused) {
 7473:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7474:                              ' '.$role.' '.$end.' '.$start.' by '.
 7475: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7476:                     return 'refused';
 7477:                 }
 7478:             }
 7479:         } elsif ($role eq 'au') {
 7480:             if ($url ne '/'.$udom.'/') {
 7481:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7482:                          ' to assign author role for '.$uname.':'.$udom.
 7483:                          ' in domain: '.$url.' refused (wrong domain).');
 7484:                 return 'refused';
 7485:             }
 7486:         }
 7487:         $mrole=$role;
 7488:     }
 7489:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7490:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7491:     if ($end) { $command.='_'.$end; }
 7492:     if ($start) {
 7493: 	if ($end) { 
 7494:            $command.='_'.$start; 
 7495:         } else {
 7496:            $command.='_0_'.$start;
 7497:         }
 7498:     }
 7499:     my $origstart = $start;
 7500:     my $origend = $end;
 7501:     my $delflag;
 7502: # actually delete
 7503:     if ($deleteflag) {
 7504: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7505: # modify command to delete the role
 7506:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7507:                 "$udom:$uname:$url".'_'."$mrole";
 7508: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7509: # set start and finish to negative values for userrolelog
 7510:            $start=-1;
 7511:            $end=-1;
 7512:            $delflag = 1;
 7513:         }
 7514:     }
 7515: # send command
 7516:     my $answer=&reply($command,&homeserver($uname,$udom));
 7517: # log new user role if status is ok
 7518:     if ($answer eq 'ok') {
 7519: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7520: # for course roles, perform group memberships changes triggered by role change.
 7521:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7522:         unless ($role =~ /^gr/) {
 7523:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7524:                                              $origstart,$selfenroll,$context);
 7525:         }
 7526:         if ($role eq 'cc') {
 7527:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7528:         }
 7529:     }
 7530:     return $answer;
 7531: }
 7532: 
 7533: sub autoupdate_coowners {
 7534:     my ($url,$end,$start,$uname,$udom) = @_;
 7535:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7536:     if (($cdom ne '') && ($cnum ne '')) {
 7537:         my $now = time;
 7538:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7539:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7540:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7541:             my $instcode = $coursehash{'internal.coursecode'};
 7542:             if ($instcode ne '') {
 7543:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7544:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7545:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7546:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7547:                         if ($result eq 'valid') {
 7548:                             if ($coursehash{'internal.co-owners'}) {
 7549:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7550:                                     push(@newcoowners,$coowner);
 7551:                                 }
 7552:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7553:                                     push(@newcoowners,$uname.':'.$udom);
 7554:                                 }
 7555:                                 @newcoowners = sort(@newcoowners);
 7556:                             } else {
 7557:                                 push(@newcoowners,$uname.':'.$udom);
 7558:                             }
 7559:                         } else {
 7560:                             if ($coursehash{'internal.co-owners'}) {
 7561:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7562:                                     unless ($coowner eq $uname.':'.$udom) {
 7563:                                         push(@newcoowners,$coowner);
 7564:                                     }
 7565:                                 }
 7566:                                 unless (@newcoowners > 0) {
 7567:                                     $delcoowners = 1;
 7568:                                     $coowners = '';
 7569:                                 }
 7570:                             }
 7571:                         }
 7572:                         if (@newcoowners || $delcoowners) {
 7573:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7574:                                             $delcoowners,@newcoowners);
 7575:                         }
 7576:                     }
 7577:                 }
 7578:             }
 7579:         }
 7580:     }
 7581: }
 7582: 
 7583: sub store_coowners {
 7584:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7585:     my $cid = $cdom.'_'.$cnum;
 7586:     my ($coowners,$delresult,$putresult);
 7587:     if (@newcoowners) {
 7588:         $coowners = join(',',@newcoowners);
 7589:         my %coownershash = (
 7590:                             'internal.co-owners' => $coowners,
 7591:                            );
 7592:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7593:         if ($putresult eq 'ok') {
 7594:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7595:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7596:             }
 7597:         }
 7598:     }
 7599:     if ($delcoowners) {
 7600:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7601:         if ($delresult eq 'ok') {
 7602:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7603:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7604:             }
 7605:         }
 7606:     }
 7607:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7608:         my %crsinfo =
 7609:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7610:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7611:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7612:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7613:         }
 7614:     }
 7615: }
 7616: 
 7617: # -------------------------------------------------- Modify user authentication
 7618: # Overrides without validation
 7619: 
 7620: sub modifyuserauth {
 7621:     my ($udom,$uname,$umode,$upass)=@_;
 7622:     my $uhome=&homeserver($uname,$udom);
 7623:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7624:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7625:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7626:              ' in domain '.$env{'request.role.domain'});  
 7627:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7628: 		     &escape($upass),$uhome);
 7629:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7630:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7631:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7632:     &log($udom,,$uname,$uhome,
 7633:         'Authentication changed by '.$env{'user.domain'}.', '.
 7634:                                      $env{'user.name'}.', '.$umode.
 7635:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7636:     unless ($reply eq 'ok') {
 7637:         &logthis('Authentication mode error: '.$reply);
 7638: 	return 'error: '.$reply;
 7639:     }   
 7640:     return 'ok';
 7641: }
 7642: 
 7643: # --------------------------------------------------------------- Modify a user
 7644: 
 7645: sub modifyuser {
 7646:     my ($udom,    $uname, $uid,
 7647:         $umode,   $upass, $first,
 7648:         $middle,  $last,  $gene,
 7649:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7650:     $udom= &LONCAPA::clean_domain($udom);
 7651:     $uname=&LONCAPA::clean_username($uname);
 7652:     my $showcandelete = 'none';
 7653:     if (ref($candelete) eq 'ARRAY') {
 7654:         if (@{$candelete} > 0) {
 7655:             $showcandelete = join(', ',@{$candelete});
 7656:         }
 7657:     }
 7658:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7659:              $umode.', '.$first.', '.$middle.', '.
 7660: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7661:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7662:                                      ' desiredhome not specified'). 
 7663:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7664:              ' in domain '.$env{'request.role.domain'});
 7665:     my $uhome=&homeserver($uname,$udom,'true');
 7666:     my $newuser;
 7667:     if ($uhome eq 'no_host') {
 7668:         $newuser = 1;
 7669:     }
 7670: # ----------------------------------------------------------------- Create User
 7671:     if (($uhome eq 'no_host') && 
 7672: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7673:         my $unhome='';
 7674:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7675:             $unhome = $desiredhome;
 7676: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7677: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7678:         } else { # load balancing routine for determining $unhome
 7679:             my $loadm=10000000;
 7680: 	    my %servers = &get_servers($udom,'library');
 7681: 	    foreach my $tryserver (keys(%servers)) {
 7682: 		my $answer=reply('load',$tryserver);
 7683: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7684: 		    $loadm=$answer;
 7685: 		    $unhome=$tryserver;
 7686: 		}
 7687: 	    }
 7688:         }
 7689:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7690: 	    return 'error: unable to find a home server for '.$uname.
 7691:                    ' in domain '.$udom;
 7692:         }
 7693:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7694:                          &escape($upass),$unhome);
 7695: 	unless ($reply eq 'ok') {
 7696:             return 'error: '.$reply;
 7697:         }   
 7698:         $uhome=&homeserver($uname,$udom,'true');
 7699:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7700: 	    return 'error: unable verify users home machine.';
 7701:         }
 7702:     }   # End of creation of new user
 7703: # ---------------------------------------------------------------------- Add ID
 7704:     if ($uid) {
 7705:        $uid=~tr/A-Z/a-z/;
 7706:        my %uidhash=&idrget($udom,$uname);
 7707:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7708:          && (!$forceid)) {
 7709: 	  unless ($uid eq $uidhash{$uname}) {
 7710: 	      return 'error: user id "'.$uid.'" does not match '.
 7711:                   'current user id "'.$uidhash{$uname}.'".';
 7712:           }
 7713:        } else {
 7714: 	  &idput($udom,($uname => $uid));
 7715:        }
 7716:     }
 7717: # -------------------------------------------------------------- Add names, etc
 7718:     my @tmp=&get('environment',
 7719: 		   ['firstname','middlename','lastname','generation','id',
 7720:                     'permanentemail','inststatus'],
 7721: 		   $udom,$uname);
 7722:     my (%names,%oldnames);
 7723:     if ($tmp[0] =~ m/^error:.*/) { 
 7724:         %names=(); 
 7725:     } else {
 7726:         %names = @tmp;
 7727:         %oldnames = %names;
 7728:     }
 7729: #
 7730: # If name, email and/or uid are blank (e.g., because an uploaded file
 7731: # of users did not contain them), do not overwrite existing values
 7732: # unless field is in $candelete array ref.  
 7733: #
 7734: 
 7735:     my @fields = ('firstname','middlename','lastname','generation',
 7736:                   'permanentemail','id');
 7737:     my %newvalues;
 7738:     if (ref($candelete) eq 'ARRAY') {
 7739:         foreach my $field (@fields) {
 7740:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7741:                 if ($field eq 'firstname') {
 7742:                     $names{$field} = $first;
 7743:                 } elsif ($field eq 'middlename') {
 7744:                     $names{$field} = $middle;
 7745:                 } elsif ($field eq 'lastname') {
 7746:                     $names{$field} = $last;
 7747:                 } elsif ($field eq 'generation') { 
 7748:                     $names{$field} = $gene;
 7749:                 } elsif ($field eq 'permanentemail') {
 7750:                     $names{$field} = $email;
 7751:                 } elsif ($field eq 'id') {
 7752:                     $names{$field}  = $uid;
 7753:                 }
 7754:             }
 7755:         }
 7756:     }
 7757:     if ($first)  { $names{'firstname'}  = $first; }
 7758:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7759:     if ($last)   { $names{'lastname'}   = $last; }
 7760:     if (defined($gene))   { $names{'generation'} = $gene; }
 7761:     if ($email) {
 7762:        $email=~s/[^\w\@\.\-\,]//gs;
 7763:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7764:     }
 7765:     if ($uid) { $names{'id'}  = $uid; }
 7766:     if (defined($inststatus)) {
 7767:         $names{'inststatus'} = '';
 7768:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7769:         if (ref($usertypes) eq 'HASH') {
 7770:             my @okstatuses; 
 7771:             foreach my $item (split(/:/,$inststatus)) {
 7772:                 if (defined($usertypes->{$item})) {
 7773:                     push(@okstatuses,$item);  
 7774:                 }
 7775:             }
 7776:             if (@okstatuses) {
 7777:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7778:             }
 7779:         }
 7780:     }
 7781:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7782:                  $umode.', '.$first.', '.$middle.', '.
 7783:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7784:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7785:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7786:     } else {
 7787:         $logmsg .= ' during self creation';
 7788:     }
 7789:     my $changed;
 7790:     if ($newuser) {
 7791:         $changed = 1;
 7792:     } else {
 7793:         foreach my $field (@fields) {
 7794:             if ($names{$field} ne $oldnames{$field}) {
 7795:                 $changed = 1;
 7796:                 last;
 7797:             }
 7798:         }
 7799:     }
 7800:     unless ($changed) {
 7801:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7802:         &logthis($logmsg);
 7803:         return 'ok';
 7804:     }
 7805:     my $reply = &put('environment', \%names, $udom,$uname);
 7806:     if ($reply ne 'ok') { 
 7807:         return 'error: '.$reply;
 7808:     }
 7809:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7810:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7811:     }
 7812:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7813:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7814:     $logmsg = 'Success modifying user '.$logmsg;
 7815:     &logthis($logmsg);
 7816:     return 'ok';
 7817: }
 7818: 
 7819: # -------------------------------------------------------------- Modify student
 7820: 
 7821: sub modifystudent {
 7822:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7823:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7824:         $selfenroll,$context,$inststatus)=@_;
 7825:     if (!$cid) {
 7826: 	unless ($cid=$env{'request.course.id'}) {
 7827: 	    return 'not_in_class';
 7828: 	}
 7829:     }
 7830: # --------------------------------------------------------------- Make the user
 7831:     my $reply=&modifyuser
 7832: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7833:          $desiredhome,$email,$inststatus);
 7834:     unless ($reply eq 'ok') { return $reply; }
 7835:     # This will cause &modify_student_enrollment to get the uid from the
 7836:     # students environment
 7837:     $uid = undef if (!$forceid);
 7838:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7839: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7840:     return $reply;
 7841: }
 7842: 
 7843: sub modify_student_enrollment {
 7844:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7845:     my ($cdom,$cnum,$chome);
 7846:     if (!$cid) {
 7847: 	unless ($cid=$env{'request.course.id'}) {
 7848: 	    return 'not_in_class';
 7849: 	}
 7850: 	$cdom=$env{'course.'.$cid.'.domain'};
 7851: 	$cnum=$env{'course.'.$cid.'.num'};
 7852:     } else {
 7853: 	($cdom,$cnum)=split(/_/,$cid);
 7854:     }
 7855:     $chome=$env{'course.'.$cid.'.home'};
 7856:     if (!$chome) {
 7857: 	$chome=&homeserver($cnum,$cdom);
 7858:     }
 7859:     if (!$chome) { return 'unknown_course'; }
 7860:     # Make sure the user exists
 7861:     my $uhome=&homeserver($uname,$udom);
 7862:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7863: 	return 'error: no such user';
 7864:     }
 7865:     # Get student data if we were not given enough information
 7866:     if (!defined($first)  || $first  eq '' || 
 7867:         !defined($last)   || $last   eq '' || 
 7868:         !defined($uid)    || $uid    eq '' || 
 7869:         !defined($middle) || $middle eq '' || 
 7870:         !defined($gene)   || $gene   eq '') {
 7871:         # They did not supply us with enough data to enroll the student, so
 7872:         # we need to pick up more information.
 7873:         my %tmp = &get('environment',
 7874:                        ['firstname','middlename','lastname', 'generation','id']
 7875:                        ,$udom,$uname);
 7876: 
 7877:         #foreach my $key (keys(%tmp)) {
 7878:         #    &logthis("key $key = ".$tmp{$key});
 7879:         #}
 7880:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7881:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7882:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7883:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7884:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7885:     }
 7886:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7887:     my $user = "$uname:$udom";
 7888:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7889:     my $reply=cput('classlist',
 7890: 		   {$user => 
 7891: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7892: 		   $cdom,$cnum);
 7893:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7894:         &devalidate_getsection_cache($udom,$uname,$cid);
 7895:     } else { 
 7896: 	return 'error: '.$reply;
 7897:     }
 7898:     # Add student role to user
 7899:     my $uurl='/'.$cid;
 7900:     $uurl=~s/\_/\//g;
 7901:     if ($usec) {
 7902: 	$uurl.='/'.$usec;
 7903:     }
 7904:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7905:                              $selfenroll,$context);
 7906:     if ($result ne 'ok') {
 7907:         if ($old_entry{$user} ne '') {
 7908:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7909:         } else {
 7910:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7911:         }
 7912:     }
 7913:     return $result; 
 7914: }
 7915: 
 7916: sub format_name {
 7917:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7918:     my $name;
 7919:     if ($first ne 'lastname') {
 7920: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7921:     } else {
 7922: 	if ($lastname=~/\S/) {
 7923: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7924: 	    $name=~s/\s+,/,/;
 7925: 	} else {
 7926: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7927: 	}
 7928:     }
 7929:     $name=~s/^\s+//;
 7930:     $name=~s/\s+$//;
 7931:     $name=~s/\s+/ /g;
 7932:     return $name;
 7933: }
 7934: 
 7935: # ------------------------------------------------- Write to course preferences
 7936: 
 7937: sub writecoursepref {
 7938:     my ($courseid,%prefs)=@_;
 7939:     $courseid=~s/^\///;
 7940:     $courseid=~s/\_/\//g;
 7941:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7942:     my $chome=homeserver($cnum,$cdomain);
 7943:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7944: 	return 'error: no such course';
 7945:     }
 7946:     my $cstring='';
 7947:     foreach my $pref (keys(%prefs)) {
 7948: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7949:     }
 7950:     $cstring=~s/\&$//;
 7951:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7952: }
 7953: 
 7954: # ---------------------------------------------------------- Make/modify course
 7955: 
 7956: sub createcourse {
 7957:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7958:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7959:     $url=&declutter($url);
 7960:     my $cid='';
 7961:     if ($context eq 'requestcourses') {
 7962:         my $can_create = 0;
 7963:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7964:         if ($udom eq $ownerdom) {
 7965:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7966:                                   $context)) {
 7967:                 $can_create = 1;
 7968:             }
 7969:         } else {
 7970:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7971:                                            $category);
 7972:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7973:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7974:                 if (@curr > 0) {
 7975:                     my @options = qw(approval validate autolimit);
 7976:                     my $optregex = join('|',@options);
 7977:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7978:                         $can_create = 1;
 7979:                     }
 7980:                 }
 7981:             }
 7982:         }
 7983:         if ($can_create) {
 7984:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7985:                 unless (&allowed('ccc',$udom)) {
 7986:                     return 'refused'; 
 7987:                 }
 7988:             }
 7989:         } else {
 7990:             return 'refused';
 7991:         }
 7992:     } elsif (!&allowed('ccc',$udom)) {
 7993:         return 'refused';
 7994:     }
 7995: # --------------------------------------------------------------- Get Unique ID
 7996:     my $uname;
 7997:     if ($cnum =~ /^$match_courseid$/) {
 7998:         my $chome=&homeserver($cnum,$udom,'true');
 7999:         if (($chome eq '') || ($chome eq 'no_host')) {
 8000:             $uname = $cnum;
 8001:         } else {
 8002:             $uname = &generate_coursenum($udom,$crstype);
 8003:         }
 8004:     } else {
 8005:         $uname = &generate_coursenum($udom,$crstype);
 8006:     }
 8007:     return $uname if ($uname =~ /^error/);
 8008: # -------------------------------------------------- Check supplied server name
 8009:     if (!defined($course_server)) {
 8010:         if (defined(&domain($udom,'primary'))) {
 8011:             $course_server = &domain($udom,'primary');
 8012:         } else {
 8013:             $course_server = $env{'user.home'}; 
 8014:         }
 8015:     }
 8016:     my %host_servers =
 8017:         &Apache::lonnet::get_servers($udom,'library');
 8018:     unless ($host_servers{$course_server}) {
 8019:         return 'error: invalid home server for course: '.$course_server;
 8020:     }
 8021: # ------------------------------------------------------------- Make the course
 8022:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8023:                       $course_server);
 8024:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8025:     my $uhome=&homeserver($uname,$udom,'true');
 8026:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8027: 	return 'error: no such course';
 8028:     }
 8029: # ----------------------------------------------------------------- Course made
 8030: # log existence
 8031:     my $now = time;
 8032:     my $newcourse = {
 8033:                     $udom.'_'.$uname => {
 8034:                                      description => $description,
 8035:                                      inst_code   => $inst_code,
 8036:                                      owner       => $course_owner,
 8037:                                      type        => $crstype,
 8038:                                      creator     => $env{'user.name'}.':'.
 8039:                                                     $env{'user.domain'},
 8040:                                      created     => $now,
 8041:                                      context     => $context,
 8042:                                                 },
 8043:                     };
 8044:     &courseidput($udom,$newcourse,$uhome,'notime');
 8045: # set toplevel url
 8046:     my $topurl=$url;
 8047:     unless ($nonstandard) {
 8048: # ------------------------------------------ For standard courses, make top url
 8049:         my $mapurl=&clutter($url);
 8050:         if ($mapurl eq '/res/') { $mapurl=''; }
 8051:         $env{'form.initmap'}=(<<ENDINITMAP);
 8052: <map>
 8053: <resource id="1" type="start"></resource>
 8054: <resource id="2" src="$mapurl"></resource>
 8055: <resource id="3" type="finish"></resource>
 8056: <link index="1" from="1" to="2"></link>
 8057: <link index="2" from="2" to="3"></link>
 8058: </map>
 8059: ENDINITMAP
 8060:         $topurl=&declutter(
 8061:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8062:                           );
 8063:     }
 8064: # ----------------------------------------------------------- Write preferences
 8065:     &writecoursepref($udom.'_'.$uname,
 8066:                      ('description'              => $description,
 8067:                       'url'                      => $topurl,
 8068:                       'internal.creator'         => $env{'user.name'}.':'.
 8069:                                                     $env{'user.domain'},
 8070:                       'internal.created'         => $now,
 8071:                       'internal.creationcontext' => $context)
 8072:                     );
 8073:     return '/'.$udom.'/'.$uname;
 8074: }
 8075: 
 8076: # ------------------------------------------------------------------- Create ID
 8077: sub generate_coursenum {
 8078:     my ($udom,$crstype) = @_;
 8079:     my $domdesc = &domain($udom);
 8080:     return 'error: invalid domain' if ($domdesc eq '');
 8081:     my $first;
 8082:     if ($crstype eq 'Community') {
 8083:         $first = '0';
 8084:     } else {
 8085:         $first = int(1+rand(9)); 
 8086:     } 
 8087:     my $uname=$first.
 8088:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8089:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8090:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8091: # ----------------------------------------------- Make sure that does not exist
 8092:     my $uhome=&homeserver($uname,$udom,'true');
 8093:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8094:         if ($crstype eq 'Community') {
 8095:             $first = '0';
 8096:         } else {
 8097:             $first = int(1+rand(9));
 8098:         }
 8099:         $uname=$first.
 8100:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8101:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8102:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8103:         $uhome=&homeserver($uname,$udom,'true');
 8104:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8105:             return 'error: unable to generate unique course-ID';
 8106:         }
 8107:     }
 8108:     return $uname;
 8109: }
 8110: 
 8111: sub is_course {
 8112:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8113:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8114: 
 8115:     return unless $cdom and $cnum;
 8116: 
 8117:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8118:         '.');
 8119: 
 8120:     return unless exists($courses{$cdom.'_'.$cnum});
 8121:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8122: }
 8123: 
 8124: sub store_userdata {
 8125:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8126:     my $result;
 8127:     if ($datakey ne '') {
 8128:         if (ref($storehash) eq 'HASH') {
 8129:             if ($udom eq '' || $uname eq '') {
 8130:                 $udom = $env{'user.domain'};
 8131:                 $uname = $env{'user.name'};
 8132:             }
 8133:             my $uhome=&homeserver($uname,$udom);
 8134:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8135:                 $result = 'error: no_host';
 8136:             } else {
 8137:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8138:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8139: 
 8140:                 my $namevalue='';
 8141:                 foreach my $key (keys(%{$storehash})) {
 8142:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8143:                 }
 8144:                 $namevalue=~s/\&$//;
 8145:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8146:                                   $namevalue,$uhome);
 8147:             }
 8148:         } else {
 8149:             $result = 'error: data to store was not a hash reference'; 
 8150:         }
 8151:     } else {
 8152:         $result= 'error: invalid requestkey'; 
 8153:     }
 8154:     return $result;
 8155: }
 8156: 
 8157: # ---------------------------------------------------------- Assign Custom Role
 8158: 
 8159: sub assigncustomrole {
 8160:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8161:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8162:                        $end,$start,$deleteflag,$selfenroll,$context);
 8163: }
 8164: 
 8165: # ----------------------------------------------------------------- Revoke Role
 8166: 
 8167: sub revokerole {
 8168:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8169:     my $now=time;
 8170:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8171: }
 8172: 
 8173: # ---------------------------------------------------------- Revoke Custom Role
 8174: 
 8175: sub revokecustomrole {
 8176:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8177:     my $now=time;
 8178:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8179:            $deleteflag,$selfenroll,$context);
 8180: }
 8181: 
 8182: # ------------------------------------------------------------ Disk usage
 8183: sub diskusage {
 8184:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8185:     $directorypath =~ s/\/$//;
 8186:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8187:                        .&escape($getpropath).':'.&escape($uname).':'
 8188:                        .&escape($udom),homeserver($uname,$udom));
 8189:     if ($listing eq 'unknown_cmd') {
 8190:         if ($getpropath) {
 8191:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8192:         }
 8193:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8194:     }
 8195:     return $listing;
 8196: }
 8197: 
 8198: sub is_locked {
 8199:     my ($file_name, $domain, $user, $which) = @_;
 8200:     my @check;
 8201:     my $is_locked;
 8202:     push (@check,$file_name);
 8203:     my %locked = &get('file_permissions',\@check,
 8204: 		      $env{'user.domain'},$env{'user.name'});
 8205:     my ($tmp)=keys(%locked);
 8206:     if ($tmp=~/^error:/) { undef(%locked); }
 8207:     
 8208:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8209:         $is_locked = 'false';
 8210:         foreach my $entry (@{$locked{$file_name}}) {
 8211:            if (ref($entry) eq 'ARRAY') {
 8212:                $is_locked = 'true';
 8213:                if (ref($which) eq 'ARRAY') {
 8214:                    push(@{$which},$entry);
 8215:                } else {
 8216:                    last;
 8217:                }
 8218:            }
 8219:        }
 8220:     } else {
 8221:         $is_locked = 'false';
 8222:     }
 8223:     return $is_locked;
 8224: }
 8225: 
 8226: sub declutter_portfile {
 8227:     my ($file) = @_;
 8228:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8229:     return $file;
 8230: }
 8231: 
 8232: # ------------------------------------------------------------- Mark as Read Only
 8233: 
 8234: sub mark_as_readonly {
 8235:     my ($domain,$user,$files,$what) = @_;
 8236:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8237:     my ($tmp)=keys(%current_permissions);
 8238:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8239:     foreach my $file (@{$files}) {
 8240: 	$file = &declutter_portfile($file);
 8241:         push(@{$current_permissions{$file}},$what);
 8242:     }
 8243:     &put('file_permissions',\%current_permissions,$domain,$user);
 8244:     return;
 8245: }
 8246: 
 8247: # ------------------------------------------------------------Save Selected Files
 8248: 
 8249: sub save_selected_files {
 8250:     my ($user, $path, @files) = @_;
 8251:     my $filename = $user."savedfiles";
 8252:     my @other_files = &files_not_in_path($user, $path);
 8253:     open (OUT, '>'.$tmpdir.$filename);
 8254:     foreach my $file (@files) {
 8255:         print (OUT $env{'form.currentpath'}.$file."\n");
 8256:     }
 8257:     foreach my $file (@other_files) {
 8258:         print (OUT $file."\n");
 8259:     }
 8260:     close (OUT);
 8261:     return 'ok';
 8262: }
 8263: 
 8264: sub clear_selected_files {
 8265:     my ($user) = @_;
 8266:     my $filename = $user."savedfiles";
 8267:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8268:     print (OUT undef);
 8269:     close (OUT);
 8270:     return ("ok");    
 8271: }
 8272: 
 8273: sub files_in_path {
 8274:     my ($user, $path) = @_;
 8275:     my $filename = $user."savedfiles";
 8276:     my %return_files;
 8277:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8278:     while (my $line_in = <IN>) {
 8279:         chomp ($line_in);
 8280:         my @paths_and_file = split (m!/!, $line_in);
 8281:         my $file_part = pop (@paths_and_file);
 8282:         my $path_part = join ('/', @paths_and_file);
 8283:         $path_part.='/';
 8284:         my $path_and_file = $path_part.$file_part;
 8285:         if ($path_part eq $path) {
 8286:             $return_files{$file_part}= 'selected';
 8287:         }
 8288:     }
 8289:     close (IN);
 8290:     return (\%return_files);
 8291: }
 8292: 
 8293: # called in portfolio select mode, to show files selected NOT in current directory
 8294: sub files_not_in_path {
 8295:     my ($user, $path) = @_;
 8296:     my $filename = $user."savedfiles";
 8297:     my @return_files;
 8298:     my $path_part;
 8299:     open(IN, '<'.LONCAPA::.$filename);
 8300:     while (my $line = <IN>) {
 8301:         #ok, I know it's clunky, but I want it to work
 8302:         my @paths_and_file = split(m|/|, $line);
 8303:         my $file_part = pop(@paths_and_file);
 8304:         chomp($file_part);
 8305:         my $path_part = join('/', @paths_and_file);
 8306:         $path_part .= '/';
 8307:         my $path_and_file = $path_part.$file_part;
 8308:         if ($path_part ne $path) {
 8309:             push(@return_files, ($path_and_file));
 8310:         }
 8311:     }
 8312:     close(OUT);
 8313:     return (@return_files);
 8314: }
 8315: 
 8316: #----------------------------------------------Get portfolio file permissions
 8317: 
 8318: sub get_portfile_permissions {
 8319:     my ($domain,$user) = @_;
 8320:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8321:     my ($tmp)=keys(%current_permissions);
 8322:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8323:     return \%current_permissions;
 8324: }
 8325: 
 8326: #---------------------------------------------Get portfolio file access controls
 8327: 
 8328: sub get_access_controls {
 8329:     my ($current_permissions,$group,$file) = @_;
 8330:     my %access;
 8331:     my $real_file = $file;
 8332:     $file =~ s/\.meta$//;
 8333:     if (defined($file)) {
 8334:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8335:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8336:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8337:             }
 8338:         }
 8339:     } else {
 8340:         foreach my $key (keys(%{$current_permissions})) {
 8341:             if ($key =~ /\0accesscontrol$/) {
 8342:                 if (defined($group)) {
 8343:                     if ($key !~ m-^\Q$group\E/-) {
 8344:                         next;
 8345:                     }
 8346:                 }
 8347:                 my ($fullpath) = split(/\0/,$key);
 8348:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8349:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8350:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8351:                     }
 8352:                 }
 8353:             }
 8354:         }
 8355:     }
 8356:     return %access;
 8357: }
 8358: 
 8359: sub modify_access_controls {
 8360:     my ($file_name,$changes,$domain,$user)=@_;
 8361:     my ($outcome,$deloutcome);
 8362:     my %store_permissions;
 8363:     my %new_values;
 8364:     my %new_control;
 8365:     my %translation;
 8366:     my @deletions = ();
 8367:     my $now = time;
 8368:     if (exists($$changes{'activate'})) {
 8369:         if (ref($$changes{'activate'}) eq 'HASH') {
 8370:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8371:             my $numnew = scalar(@newitems);
 8372:             for (my $i=0; $i<$numnew; $i++) {
 8373:                 my $newkey = $newitems[$i];
 8374:                 my $newid = &Apache::loncommon::get_cgi_id();
 8375:                 if ($newkey =~ /^\d+:/) { 
 8376:                     $newkey =~ s/^(\d+)/$newid/;
 8377:                     $translation{$1} = $newid;
 8378:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8379:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8380:                     $translation{$1} = $newid;
 8381:                 }
 8382:                 $new_values{$file_name."\0".$newkey} = 
 8383:                                           $$changes{'activate'}{$newitems[$i]};
 8384:                 $new_control{$newkey} = $now;
 8385:             }
 8386:         }
 8387:     }
 8388:     my %todelete;
 8389:     my %changed_items;
 8390:     foreach my $action ('delete','update') {
 8391:         if (exists($$changes{$action})) {
 8392:             if (ref($$changes{$action}) eq 'HASH') {
 8393:                 foreach my $key (keys(%{$$changes{$action}})) {
 8394:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8395:                     if ($action eq 'delete') { 
 8396:                         $todelete{$itemnum} = 1;
 8397:                     } else {
 8398:                         $changed_items{$itemnum} = $key;
 8399:                     }
 8400:                 }
 8401:             }
 8402:         }
 8403:     }
 8404:     # get lock on access controls for file.
 8405:     my $lockhash = {
 8406:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8407:                                                        ':'.$env{'user.domain'},
 8408:                    }; 
 8409:     my $tries = 0;
 8410:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8411:    
 8412:     while (($gotlock ne 'ok') && $tries <3) {
 8413:         $tries ++;
 8414:         sleep 1;
 8415:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8416:     }
 8417:     if ($gotlock eq 'ok') {
 8418:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8419:         my ($tmp)=keys(%curr_permissions);
 8420:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8421:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8422:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8423:             if (ref($curr_controls) eq 'HASH') {
 8424:                 foreach my $control_item (keys(%{$curr_controls})) {
 8425:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8426:                     if (defined($todelete{$itemnum})) {
 8427:                         push(@deletions,$file_name."\0".$control_item);
 8428:                     } else {
 8429:                         if (defined($changed_items{$itemnum})) {
 8430:                             $new_control{$changed_items{$itemnum}} = $now;
 8431:                             push(@deletions,$file_name."\0".$control_item);
 8432:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8433:                         } else {
 8434:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8435:                         }
 8436:                     }
 8437:                 }
 8438:             }
 8439:         }
 8440:         my ($group);
 8441:         if (&is_course($domain,$user)) {
 8442:             ($group,my $file) = split(/\//,$file_name,2);
 8443:         }
 8444:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8445:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8446:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8447:         #  remove lock
 8448:         my @del_lock = ($file_name."\0".'locked_access_records');
 8449:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8450:         my $sqlresult =
 8451:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8452:                                     $group);
 8453:     } else {
 8454:         $outcome = "error: could not obtain lockfile\n";  
 8455:     }
 8456:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8457: }
 8458: 
 8459: sub make_public_indefinitely {
 8460:     my ($requrl) = @_;
 8461:     my $now = time;
 8462:     my $action = 'activate';
 8463:     my $aclnum = 0;
 8464:     if (&is_portfolio_url($requrl)) {
 8465:         my (undef,$udom,$unum,$file_name,$group) =
 8466:             &parse_portfolio_url($requrl);
 8467:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8468:         my %access_controls = &get_access_controls($current_perms,
 8469:                                                    $group,$file_name);
 8470:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8471:             my ($num,$scope,$end,$start) = 
 8472:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8473:             if ($scope eq 'public') {
 8474:                 if ($start <= $now && $end == 0) {
 8475:                     $action = 'none';
 8476:                 } else {
 8477:                     $action = 'update';
 8478:                     $aclnum = $num;
 8479:                 }
 8480:                 last;
 8481:             }
 8482:         }
 8483:         if ($action eq 'none') {
 8484:              return 'ok';
 8485:         } else {
 8486:             my %changes;
 8487:             my $newend = 0;
 8488:             my $newstart = $now;
 8489:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8490:             $changes{$action}{$newkey} = {
 8491:                 type => 'public',
 8492:                 time => {
 8493:                     start => $newstart,
 8494:                     end   => $newend,
 8495:                 },
 8496:             };
 8497:             my ($outcome,$deloutcome,$new_values,$translation) =
 8498:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8499:             return $outcome;
 8500:         }
 8501:     } else {
 8502:         return 'invalid';
 8503:     }
 8504: }
 8505: 
 8506: #------------------------------------------------------Get Marked as Read Only
 8507: 
 8508: sub get_marked_as_readonly {
 8509:     my ($domain,$user,$what,$group) = @_;
 8510:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8511:     my @readonly_files;
 8512:     my $cmp1=$what;
 8513:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8514:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8515:         if (defined($group)) {
 8516:             if ($file_name !~ m-^\Q$group\E/-) {
 8517:                 next;
 8518:             }
 8519:         }
 8520:         if (ref($value) eq "ARRAY"){
 8521:             foreach my $stored_what (@{$value}) {
 8522:                 my $cmp2=$stored_what;
 8523:                 if (ref($stored_what) eq 'ARRAY') {
 8524:                     $cmp2=join('',@{$stored_what});
 8525:                 }
 8526:                 if ($cmp1 eq $cmp2) {
 8527:                     push(@readonly_files, $file_name);
 8528:                     last;
 8529:                 } elsif (!defined($what)) {
 8530:                     push(@readonly_files, $file_name);
 8531:                     last;
 8532:                 }
 8533:             }
 8534:         }
 8535:     }
 8536:     return @readonly_files;
 8537: }
 8538: #-----------------------------------------------------------Get Marked as Read Only Hash
 8539: 
 8540: sub get_marked_as_readonly_hash {
 8541:     my ($current_permissions,$group,$what) = @_;
 8542:     my %readonly_files;
 8543:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8544:         if (defined($group)) {
 8545:             if ($file_name !~ m-^\Q$group\E/-) {
 8546:                 next;
 8547:             }
 8548:         }
 8549:         if (ref($value) eq "ARRAY"){
 8550:             foreach my $stored_what (@{$value}) {
 8551:                 if (ref($stored_what) eq 'ARRAY') {
 8552:                     foreach my $lock_descriptor(@{$stored_what}) {
 8553:                         if ($lock_descriptor eq 'graded') {
 8554:                             $readonly_files{$file_name} = 'graded';
 8555:                         } elsif ($lock_descriptor eq 'handback') {
 8556:                             $readonly_files{$file_name} = 'handback';
 8557:                         } else {
 8558:                             if (!exists($readonly_files{$file_name})) {
 8559:                                 $readonly_files{$file_name} = 'locked';
 8560:                             }
 8561:                         }
 8562:                     }
 8563:                 } 
 8564:             }
 8565:         } 
 8566:     }
 8567:     return %readonly_files;
 8568: }
 8569: # ------------------------------------------------------------ Unmark as Read Only
 8570: 
 8571: sub unmark_as_readonly {
 8572:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8573:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8574:     my ($domain,$user,$what,$file_name,$group) = @_;
 8575:     $file_name = &declutter_portfile($file_name);
 8576:     my $symb_crs = $what;
 8577:     if (ref($what)) { $symb_crs=join('',@$what); }
 8578:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8579:     my ($tmp)=keys(%current_permissions);
 8580:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8581:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8582:     foreach my $file (@readonly_files) {
 8583: 	my $clean_file = &declutter_portfile($file);
 8584: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8585: 	my $current_locks = $current_permissions{$file};
 8586:         my @new_locks;
 8587:         my @del_keys;
 8588:         if (ref($current_locks) eq "ARRAY"){
 8589:             foreach my $locker (@{$current_locks}) {
 8590:                 my $compare=$locker;
 8591:                 if (ref($locker) eq 'ARRAY') {
 8592:                     $compare=join('',@{$locker});
 8593:                     if ($compare ne $symb_crs) {
 8594:                         push(@new_locks, $locker);
 8595:                     }
 8596:                 }
 8597:             }
 8598:             if (scalar(@new_locks) > 0) {
 8599:                 $current_permissions{$file} = \@new_locks;
 8600:             } else {
 8601:                 push(@del_keys, $file);
 8602:                 &del('file_permissions',\@del_keys, $domain, $user);
 8603:                 delete($current_permissions{$file});
 8604:             }
 8605:         }
 8606:     }
 8607:     &put('file_permissions',\%current_permissions,$domain,$user);
 8608:     return;
 8609: }
 8610: 
 8611: # ------------------------------------------------------------ Directory lister
 8612: 
 8613: sub dirlist {
 8614:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8615:     $uri=~s/^\///;
 8616:     $uri=~s/\/$//;
 8617:     my ($udom, $uname);
 8618:     if ($getuserdir) {
 8619:         $udom = $userdomain;
 8620:         $uname = $username;
 8621:     } else {
 8622:         (undef,$udom,$uname)=split(/\//,$uri);
 8623:         if(defined($userdomain)) {
 8624:             $udom = $userdomain;
 8625:         }
 8626:         if(defined($username)) {
 8627:             $uname = $username;
 8628:         }
 8629:     }
 8630:     my ($dirRoot,$listing,@listing_results);
 8631: 
 8632:     $dirRoot = $perlvar{'lonDocRoot'};
 8633:     if (defined($getpropath)) {
 8634:         $dirRoot = &propath($udom,$uname);
 8635:         $dirRoot =~ s/\/$//;
 8636:     } elsif (defined($getuserdir)) {
 8637:         my $subdir=$uname.'__';
 8638:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8639:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8640:                    ."/$udom/$subdir/$uname";
 8641:     } elsif (defined($alternateRoot)) {
 8642:         $dirRoot = $alternateRoot;
 8643:     }
 8644: 
 8645:     if($udom) {
 8646:         if($uname) {
 8647:             my $uhome = &homeserver($uname,$udom);
 8648:             if ($uhome eq 'no_host') {
 8649:                 return ([],'no_host');
 8650:             }
 8651:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8652:                               .$getuserdir.':'.&escape($dirRoot)
 8653:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8654:             if ($listing eq 'unknown_cmd') {
 8655:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8656:             } else {
 8657:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8658:             }
 8659:             if ($listing eq 'unknown_cmd') {
 8660:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8661:                 @listing_results = split(/:/,$listing);
 8662:             } else {
 8663:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8664:             }
 8665:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8666:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8667:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8668:                 return ([],$listing);
 8669:             } else {
 8670:                 return (\@listing_results);
 8671:             }
 8672:         } elsif(!$alternateRoot) {
 8673:             my (%allusers,%listerror);
 8674: 	    my %servers = &get_servers($udom,'library');
 8675:  	    foreach my $tryserver (keys(%servers)) {
 8676:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8677:                                   &escape($udom),$tryserver);
 8678:                 if ($listing eq 'unknown_cmd') {
 8679: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8680: 				      $udom, $tryserver);
 8681:                 } else {
 8682:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8683:                 }
 8684: 		if ($listing eq 'unknown_cmd') {
 8685: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8686: 				      $udom, $tryserver);
 8687: 		    @listing_results = split(/:/,$listing);
 8688: 		} else {
 8689: 		    @listing_results =
 8690: 			map { &unescape($_); } split(/:/,$listing);
 8691: 		}
 8692:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8693:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8694:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8695:                     $listerror{$tryserver} = $listing;
 8696:                 } else {
 8697: 		    foreach my $line (@listing_results) {
 8698: 			my ($entry) = split(/&/,$line,2);
 8699: 			$allusers{$entry} = 1;
 8700: 		    }
 8701: 		}
 8702:             }
 8703:             my @alluserslist=();
 8704:             foreach my $user (sort(keys(%allusers))) {
 8705:                 push(@alluserslist,$user.'&user');
 8706:             }
 8707:             return (\@alluserslist);
 8708:         } else {
 8709:             return ([],'missing username');
 8710:         }
 8711:     } elsif(!defined($getpropath)) {
 8712:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8713:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8714:         return (\@all_domains);
 8715:     } else {
 8716:         return ([],'missing domain');
 8717:     }
 8718: }
 8719: 
 8720: # --------------------------------------------- GetFileTimestamp
 8721: # This function utilizes dirlist and returns the date stamp for
 8722: # when it was last modified.  It will also return an error of -1
 8723: # if an error occurs
 8724: 
 8725: sub GetFileTimestamp {
 8726:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8727:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8728:     $studentName   = &LONCAPA::clean_username($studentName);
 8729:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8730:                                     undef,$getuserdir);
 8731:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8732:         return -1;
 8733:     }
 8734:     if (ref($fileref) eq 'ARRAY') {
 8735:         my @stats = split('&',$fileref->[0]);
 8736:         # @stats contains first the filename, then the stat output
 8737:         return $stats[10]; # so this is 10 instead of 9.
 8738:     } else {
 8739:         return -1;
 8740:     }
 8741: }
 8742: 
 8743: sub stat_file {
 8744:     my ($uri) = @_;
 8745:     $uri = &clutter_with_no_wrapper($uri);
 8746: 
 8747:     my ($udom,$uname,$file);
 8748:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8749: 	($udom,$uname,$file) =
 8750: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8751: 	$file = 'userfiles/'.$file;
 8752:     }
 8753:     if ($uri =~ m-^/res/-) {
 8754: 	($udom,$uname) = 
 8755: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8756: 	$file = $uri;
 8757:     }
 8758: 
 8759:     if (!$udom || !$uname || !$file) {
 8760: 	# unable to handle the uri
 8761: 	return ();
 8762:     }
 8763:     my $getpropath;
 8764:     if ($file =~ /^userfiles\//) {
 8765:         $getpropath = 1;
 8766:     }
 8767:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8768:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8769:         return ();
 8770:     } else {
 8771:         if (ref($listref) eq 'ARRAY') {
 8772:             my @stats = split('&',$listref->[0]);
 8773: 	    shift(@stats); #filename is first
 8774: 	    return @stats;
 8775:         }
 8776:     }
 8777:     return ();
 8778: }
 8779: 
 8780: # -------------------------------------------------------- Value of a Condition
 8781: 
 8782: # gets the value of a specific preevaluated condition
 8783: #    stored in the string  $env{user.state.<cid>}
 8784: # or looks up a condition reference in the bighash and if if hasn't
 8785: # already been evaluated recurses into docondval to get the value of
 8786: # the condition, then memoizing it to 
 8787: #   $env{user.state.<cid>.<condition>}
 8788: sub directcondval {
 8789:     my $number=shift;
 8790:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8791: 	&Apache::lonuserstate::evalstate();
 8792:     }
 8793:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8794: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8795:     } elsif ($number =~ /^_/) {
 8796: 	my $sub_condition;
 8797: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8798: 		&GDBM_READER(),0640)) {
 8799: 	    $sub_condition=$bighash{'conditions'.$number};
 8800: 	    untie(%bighash);
 8801: 	}
 8802: 	my $value = &docondval($sub_condition);
 8803: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8804: 	return $value;
 8805:     }
 8806:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8807:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8808:     } else {
 8809:        return 2;
 8810:     }
 8811: }
 8812: 
 8813: # get the collection of conditions for this resource
 8814: sub condval {
 8815:     my $condidx=shift;
 8816:     my $allpathcond='';
 8817:     foreach my $cond (split(/\|/,$condidx)) {
 8818: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8819: 	    $allpathcond.=
 8820: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8821: 	}
 8822:     }
 8823:     $allpathcond=~s/\|$//;
 8824:     return &docondval($allpathcond);
 8825: }
 8826: 
 8827: #evaluates an expression of conditions
 8828: sub docondval {
 8829:     my ($allpathcond) = @_;
 8830:     my $result=0;
 8831:     if ($env{'request.course.id'}
 8832: 	&& defined($allpathcond)) {
 8833: 	my $operand='|';
 8834: 	my @stack;
 8835: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8836: 	    if ($chunk eq '(') {
 8837: 		push @stack,($operand,$result);
 8838: 	    } elsif ($chunk eq ')') {
 8839: 		my $before=pop @stack;
 8840: 		if (pop @stack eq '&') {
 8841: 		    $result=$result>$before?$before:$result;
 8842: 		} else {
 8843: 		    $result=$result>$before?$result:$before;
 8844: 		}
 8845: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8846: 		$operand=$chunk;
 8847: 	    } else {
 8848: 		my $new=directcondval($chunk);
 8849: 		if ($operand eq '&') {
 8850: 		    $result=$result>$new?$new:$result;
 8851: 		} else {
 8852: 		    $result=$result>$new?$result:$new;
 8853: 		}
 8854: 	    }
 8855: 	}
 8856:     }
 8857:     return $result;
 8858: }
 8859: 
 8860: # ---------------------------------------------------- Devalidate courseresdata
 8861: 
 8862: sub devalidatecourseresdata {
 8863:     my ($coursenum,$coursedomain)=@_;
 8864:     my $hashid=$coursenum.':'.$coursedomain;
 8865:     &devalidate_cache_new('courseres',$hashid);
 8866: }
 8867: 
 8868: 
 8869: # --------------------------------------------------- Course Resourcedata Query
 8870: #
 8871: #  Parameters:
 8872: #      $coursenum    - Number of the course.
 8873: #      $coursedomain - Domain at which the course was created.
 8874: #  Returns:
 8875: #     A hash of the course parameters along (I think) with timestamps
 8876: #     and version info.
 8877: 
 8878: sub get_courseresdata {
 8879:     my ($coursenum,$coursedomain)=@_;
 8880:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8881:     my $hashid=$coursenum.':'.$coursedomain;
 8882:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8883:     my %dumpreply;
 8884:     unless (defined($cached)) {
 8885: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8886: 	$result=\%dumpreply;
 8887: 	my ($tmp) = keys(%dumpreply);
 8888: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8889: 	    &do_cache_new('courseres',$hashid,$result,600);
 8890: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8891: 	    return $tmp;
 8892: 	} elsif ($tmp =~ /^(error)/) {
 8893: 	    $result=undef;
 8894: 	    &do_cache_new('courseres',$hashid,$result,600);
 8895: 	}
 8896:     }
 8897:     return $result;
 8898: }
 8899: 
 8900: sub devalidateuserresdata {
 8901:     my ($uname,$udom)=@_;
 8902:     my $hashid="$udom:$uname";
 8903:     &devalidate_cache_new('userres',$hashid);
 8904: }
 8905: 
 8906: sub get_userresdata {
 8907:     my ($uname,$udom)=@_;
 8908:     #most student don\'t have any data set, check if there is some data
 8909:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8910: 
 8911:     my $hashid="$udom:$uname";
 8912:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8913:     if (!defined($cached)) {
 8914: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8915: 	$result=\%resourcedata;
 8916: 	&do_cache_new('userres',$hashid,$result,600);
 8917:     }
 8918:     my ($tmp)=keys(%$result);
 8919:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8920: 	return $result;
 8921:     }
 8922:     #error 2 occurs when the .db doesn't exist
 8923:     if ($tmp!~/error: 2 /) {
 8924: 	&logthis("<font color=\"blue\">WARNING:".
 8925: 		 " Trying to get resource data for ".
 8926: 		 $uname." at ".$udom.": ".
 8927: 		 $tmp."</font>");
 8928:     } elsif ($tmp=~/error: 2 /) {
 8929: 	#&EXT_cache_set($udom,$uname);
 8930: 	&do_cache_new('userres',$hashid,undef,600);
 8931: 	undef($tmp); # not really an error so don't send it back
 8932:     }
 8933:     return $tmp;
 8934: }
 8935: #----------------------------------------------- resdata - return resource data
 8936: #  Purpose:
 8937: #    Return resource data for either users or for a course.
 8938: #  Parameters:
 8939: #     $name      - Course/user name.
 8940: #     $domain    - Name of the domain the user/course is registered on.
 8941: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8942: #     @which     - Array of names of resources desired.
 8943: #  Returns:
 8944: #     The value of the first reasource in @which that is found in the
 8945: #     resource hash.
 8946: #  Exceptional Conditions:
 8947: #     If the $type passed in is not valid (not the string 'course' or 
 8948: #     'user', an undefined  reference is returned.
 8949: #     If none of the resources are found, an undef is returned
 8950: sub resdata {
 8951:     my ($name,$domain,$type,@which)=@_;
 8952:     my $result;
 8953:     if ($type eq 'course') {
 8954: 	$result=&get_courseresdata($name,$domain);
 8955:     } elsif ($type eq 'user') {
 8956: 	$result=&get_userresdata($name,$domain);
 8957:     }
 8958:     if (!ref($result)) { return $result; }    
 8959:     foreach my $item (@which) {
 8960: 	if (defined($result->{$item->[0]})) {
 8961: 	    return [$result->{$item->[0]},$item->[1]];
 8962: 	}
 8963:     }
 8964:     return undef;
 8965: }
 8966: 
 8967: #
 8968: # EXT resource caching routines
 8969: #
 8970: 
 8971: sub clear_EXT_cache_status {
 8972:     &delenv('cache.EXT.');
 8973: }
 8974: 
 8975: sub EXT_cache_status {
 8976:     my ($target_domain,$target_user) = @_;
 8977:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8978:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8979:         # We know already the user has no data
 8980:         return 1;
 8981:     } else {
 8982:         return 0;
 8983:     }
 8984: }
 8985: 
 8986: sub EXT_cache_set {
 8987:     my ($target_domain,$target_user) = @_;
 8988:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8989:     #&appenv({$cachename => time});
 8990: }
 8991: 
 8992: # --------------------------------------------------------- Value of a Variable
 8993: sub EXT {
 8994: 
 8995:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8996:     unless ($varname) { return ''; }
 8997:     #get real user name/domain, courseid and symb
 8998:     my $courseid;
 8999:     my $publicuser;
 9000:     if ($symbparm) {
 9001: 	$symbparm=&get_symb_from_alias($symbparm);
 9002:     }
 9003:     if (!($uname && $udom)) {
 9004:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9005:       if (!$symbparm) {	$symbparm=$cursymb; }
 9006:     } else {
 9007: 	$courseid=$env{'request.course.id'};
 9008:     }
 9009:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9010:     my $rest;
 9011:     if (defined($therest[0])) {
 9012:        $rest=join('.',@therest);
 9013:     } else {
 9014:        $rest='';
 9015:     }
 9016: 
 9017:     my $qualifierrest=$qualifier;
 9018:     if ($rest) { $qualifierrest.='.'.$rest; }
 9019:     my $spacequalifierrest=$space;
 9020:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9021:     if ($realm eq 'user') {
 9022: # --------------------------------------------------------------- user.resource
 9023: 	if ($space eq 'resource') {
 9024: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9025: 		  || defined($Apache::lonhomework::parsing_a_task))
 9026: 		 &&
 9027: 		 ($symbparm eq &symbread()) ) {	
 9028: 		# if we are in the middle of processing the resource the
 9029: 		# get the value we are planning on committing
 9030:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9031:                     return $Apache::lonhomework::results{$qualifierrest};
 9032:                 } else {
 9033:                     return $Apache::lonhomework::history{$qualifierrest};
 9034:                 }
 9035: 	    } else {
 9036: 		my %restored;
 9037: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9038: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9039: 		} else {
 9040: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9041: 		}
 9042: 		return $restored{$qualifierrest};
 9043: 	    }
 9044: # ----------------------------------------------------------------- user.access
 9045:         } elsif ($space eq 'access') {
 9046: 	    # FIXME - not supporting calls for a specific user
 9047:             return &allowed($qualifier,$rest);
 9048: # ------------------------------------------ user.preferences, user.environment
 9049:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9050: 	    if (($uname eq $env{'user.name'}) &&
 9051: 		($udom eq $env{'user.domain'})) {
 9052: 		return $env{join('.',('environment',$qualifierrest))};
 9053: 	    } else {
 9054: 		my %returnhash;
 9055: 		if (!$publicuser) {
 9056: 		    %returnhash=&userenvironment($udom,$uname,
 9057: 						 $qualifierrest);
 9058: 		}
 9059: 		return $returnhash{$qualifierrest};
 9060: 	    }
 9061: # ----------------------------------------------------------------- user.course
 9062:         } elsif ($space eq 'course') {
 9063: 	    # FIXME - not supporting calls for a specific user
 9064:             return $env{join('.',('request.course',$qualifier))};
 9065: # ------------------------------------------------------------------- user.role
 9066:         } elsif ($space eq 'role') {
 9067: 	    # FIXME - not supporting calls for a specific user
 9068:             my ($role,$where)=split(/\./,$env{'request.role'});
 9069:             if ($qualifier eq 'value') {
 9070: 		return $role;
 9071:             } elsif ($qualifier eq 'extent') {
 9072:                 return $where;
 9073:             }
 9074: # ----------------------------------------------------------------- user.domain
 9075:         } elsif ($space eq 'domain') {
 9076:             return $udom;
 9077: # ------------------------------------------------------------------- user.name
 9078:         } elsif ($space eq 'name') {
 9079:             return $uname;
 9080: # ---------------------------------------------------- Any other user namespace
 9081:         } else {
 9082: 	    my %reply;
 9083: 	    if (!$publicuser) {
 9084: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9085: 	    }
 9086: 	    return $reply{$qualifierrest};
 9087:         }
 9088:     } elsif ($realm eq 'query') {
 9089: # ---------------------------------------------- pull stuff out of query string
 9090:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9091: 						[$spacequalifierrest]);
 9092: 	return $env{'form.'.$spacequalifierrest}; 
 9093:    } elsif ($realm eq 'request') {
 9094: # ------------------------------------------------------------- request.browser
 9095:         if ($space eq 'browser') {
 9096:             return $env{'browser.'.$qualifier};
 9097: # ------------------------------------------------------------ request.filename
 9098:         } else {
 9099:             return $env{'request.'.$spacequalifierrest};
 9100:         }
 9101:     } elsif ($realm eq 'course') {
 9102: # ---------------------------------------------------------- course.description
 9103:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9104:     } elsif ($realm eq 'resource') {
 9105: 
 9106: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9107: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9108: 	}
 9109: 
 9110: 	if ($space eq 'title') {
 9111: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9112: 	    return &gettitle($symbparm);
 9113: 	}
 9114: 	
 9115: 	if ($space eq 'map') {
 9116: 	    my ($map) = &decode_symb($symbparm);
 9117: 	    return &symbread($map);
 9118: 	}
 9119: 	if ($space eq 'filename') {
 9120: 	    if ($symbparm) {
 9121: 		return &clutter((&decode_symb($symbparm))[2]);
 9122: 	    }
 9123: 	    return &hreflocation('',$env{'request.filename'});
 9124: 	}
 9125: 
 9126: 	my ($section, $group, @groups);
 9127: 	my ($courselevelm,$courselevel);
 9128: 	if ($symbparm && defined($courseid) && 
 9129: 	    $courseid eq $env{'request.course.id'}) {
 9130: 
 9131: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9132: 
 9133: # ----------------------------------------------------- Cascading lookup scheme
 9134: 	    my $symbp=$symbparm;
 9135: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9136: 
 9137: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9138: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9139: 
 9140: 	    if (($env{'user.name'} eq $uname) &&
 9141: 		($env{'user.domain'} eq $udom)) {
 9142: 		$section=$env{'request.course.sec'};
 9143:                 @groups = split(/:/,$env{'request.course.groups'});  
 9144:                 @groups=&sort_course_groups($courseid,@groups); 
 9145: 	    } else {
 9146: 		if (! defined($usection)) {
 9147: 		    $section=&getsection($udom,$uname,$courseid);
 9148: 		} else {
 9149: 		    $section = $usection;
 9150: 		}
 9151:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9152: 	    }
 9153: 
 9154: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9155: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9156: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9157: 
 9158: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9159: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9160: 	    $courselevelm=$courseid.'.'.$mapparm;
 9161: 
 9162: # ----------------------------------------------------------- first, check user
 9163: 
 9164: 	    my $userreply=&resdata($uname,$udom,'user',
 9165: 				       ([$courselevelr,'resource'],
 9166: 					[$courselevelm,'map'     ],
 9167: 					[$courselevel, 'course'  ]));
 9168: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9169: 
 9170: # ------------------------------------------------ second, check some of course
 9171:             my $coursereply;
 9172:             if (@groups > 0) {
 9173:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9174:                                        $mapparm,$spacequalifierrest);
 9175:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9176:             }
 9177: 
 9178: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9179: 				  $env{'course.'.$courseid.'.domain'},
 9180: 				  'course',
 9181: 				  ([$seclevelr,   'resource'],
 9182: 				   [$seclevelm,   'map'     ],
 9183: 				   [$seclevel,    'course'  ],
 9184: 				   [$courselevelr,'resource']));
 9185: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9186: 
 9187: # ------------------------------------------------------ third, check map parms
 9188: 	    my %parmhash=();
 9189: 	    my $thisparm='';
 9190: 	    if (tie(%parmhash,'GDBM_File',
 9191: 		    $env{'request.course.fn'}.'_parms.db',
 9192: 		    &GDBM_READER(),0640)) {
 9193: 		$thisparm=$parmhash{$symbparm};
 9194: 		untie(%parmhash);
 9195: 	    }
 9196: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9197: 	}
 9198: # ------------------------------------------ fourth, look in resource metadata
 9199: 
 9200: 	$spacequalifierrest=~s/\./\_/;
 9201: 	my $filename;
 9202: 	if (!$symbparm) { $symbparm=&symbread(); }
 9203: 	if ($symbparm) {
 9204: 	    $filename=(&decode_symb($symbparm))[2];
 9205: 	} else {
 9206: 	    $filename=$env{'request.filename'};
 9207: 	}
 9208: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9209: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9210: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9211: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9212: 
 9213: # ---------------------------------------------- fourth, look in rest of course
 9214: 	if ($symbparm && defined($courseid) && 
 9215: 	    $courseid eq $env{'request.course.id'}) {
 9216: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9217: 				     $env{'course.'.$courseid.'.domain'},
 9218: 				     'course',
 9219: 				     ([$courselevelm,'map'   ],
 9220: 				      [$courselevel, 'course']));
 9221: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9222: 	}
 9223: # ------------------------------------------------------------------ Cascade up
 9224: 	unless ($space eq '0') {
 9225: 	    my @parts=split(/_/,$space);
 9226: 	    my $id=pop(@parts);
 9227: 	    my $part=join('_',@parts);
 9228: 	    if ($part eq '') { $part='0'; }
 9229: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9230: 				 $symbparm,$udom,$uname,$section,1);
 9231: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9232: 	}
 9233: 	if ($recurse) { return undef; }
 9234: 	my $pack_def=&packages_tab_default($filename,$varname);
 9235: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9236: # ---------------------------------------------------- Any other user namespace
 9237:     } elsif ($realm eq 'environment') {
 9238: # ----------------------------------------------------------------- environment
 9239: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9240: 	    return $env{'environment.'.$spacequalifierrest};
 9241: 	} else {
 9242: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9243: 		return '';
 9244: 	    }
 9245: 	    my %returnhash=&userenvironment($udom,$uname,
 9246: 					    $spacequalifierrest);
 9247: 	    return $returnhash{$spacequalifierrest};
 9248: 	}
 9249:     } elsif ($realm eq 'system') {
 9250: # ----------------------------------------------------------------- system.time
 9251: 	if ($space eq 'time') {
 9252: 	    return time;
 9253:         }
 9254:     } elsif ($realm eq 'server') {
 9255: # ----------------------------------------------------------------- system.time
 9256: 	if ($space eq 'name') {
 9257: 	    return $ENV{'SERVER_NAME'};
 9258:         }
 9259:     }
 9260:     return '';
 9261: }
 9262: 
 9263: sub get_reply {
 9264:     my ($reply_value) = @_;
 9265:     if (ref($reply_value) eq 'ARRAY') {
 9266:         if (wantarray) {
 9267: 	    return @$reply_value;
 9268:         }
 9269:         return $reply_value->[0];
 9270:     } else {
 9271:         return $reply_value;
 9272:     }
 9273: }
 9274: 
 9275: sub check_group_parms {
 9276:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9277:     my @groupitems = ();
 9278:     my $resultitem;
 9279:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9280:     foreach my $group (@{$groups}) {
 9281:         foreach my $level (@levels) {
 9282:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9283:              push(@groupitems,[$item,$level->[1]]);
 9284:         }
 9285:     }
 9286:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9287:                             $env{'course.'.$courseid.'.domain'},
 9288:                                      'course',@groupitems);
 9289:     return $coursereply;
 9290: }
 9291: 
 9292: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9293:     my ($courseid,@groups) = @_;
 9294:     @groups = sort(@groups);
 9295:     return @groups;
 9296: }
 9297: 
 9298: sub packages_tab_default {
 9299:     my ($uri,$varname)=@_;
 9300:     my (undef,$part,$name)=split(/\./,$varname);
 9301: 
 9302:     my (@extension,@specifics,$do_default);
 9303:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9304: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9305: 	if ($pack_type eq 'default') {
 9306: 	    $do_default=1;
 9307: 	} elsif ($pack_type eq 'extension') {
 9308: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9309: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9310: 	    # only look at packages defaults for packages that this id is
 9311: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9312: 	}
 9313:     }
 9314:     # first look for a package that matches the requested part id
 9315:     foreach my $package (@specifics) {
 9316: 	my (undef,$pack_type,$pack_part)=@{$package};
 9317: 	next if ($pack_part ne $part);
 9318: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9319: 	    return $packagetab{"$pack_type&$name&default"};
 9320: 	}
 9321:     }
 9322:     # look for any possible matching non extension_ package
 9323:     foreach my $package (@specifics) {
 9324: 	my (undef,$pack_type,$pack_part)=@{$package};
 9325: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9326: 	    return $packagetab{"$pack_type&$name&default"};
 9327: 	}
 9328: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9329: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9330: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9331: 	}
 9332:     }
 9333:     # look for any posible extension_ match
 9334:     foreach my $package (@extension) {
 9335: 	my ($package,$pack_type)=@{$package};
 9336: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9337: 	    return $packagetab{"$pack_type&$name&default"};
 9338: 	}
 9339: 	if (defined($packagetab{$package."&$name&default"})) {
 9340: 	    return $packagetab{$package."&$name&default"};
 9341: 	}
 9342:     }
 9343:     # look for a global default setting
 9344:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9345: 	return $packagetab{"default&$name&default"};
 9346:     }
 9347:     return undef;
 9348: }
 9349: 
 9350: sub add_prefix_and_part {
 9351:     my ($prefix,$part)=@_;
 9352:     my $keyroot;
 9353:     if (defined($prefix) && $prefix !~ /^__/) {
 9354: 	# prefix that has a part already
 9355: 	$keyroot=$prefix;
 9356:     } elsif (defined($prefix)) {
 9357: 	# prefix that is missing a part
 9358: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9359:     } else {
 9360: 	# no prefix at all
 9361: 	if (defined($part)) { $keyroot='_'.$part; }
 9362:     }
 9363:     return $keyroot;
 9364: }
 9365: 
 9366: # ---------------------------------------------------------------- Get metadata
 9367: 
 9368: my %metaentry;
 9369: my %importedpartids;
 9370: sub metadata {
 9371:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9372:     $uri=&declutter($uri);
 9373:     # if it is a non metadata possible uri return quickly
 9374:     if (($uri eq '') || 
 9375: 	(($uri =~ m|^/*adm/|) && 
 9376: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9377:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9378: 	return undef;
 9379:     }
 9380:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9381: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9382: 	return undef;
 9383:     }
 9384:     my $filename=$uri;
 9385:     $uri=~s/\.meta$//;
 9386: #
 9387: # Is the metadata already cached?
 9388: # Look at timestamp of caching
 9389: # Everything is cached by the main uri, libraries are never directly cached
 9390: #
 9391:     if (!defined($liburi)) {
 9392: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9393: 	if (defined($cached)) { return $result->{':'.$what}; }
 9394:     }
 9395:     {
 9396: # Imported parts would go here
 9397:         my %importedids=();
 9398:         my @origfileimportpartids=();
 9399:         my $importedparts=0;
 9400: #
 9401: # Is this a recursive call for a library?
 9402: #
 9403: #	if (! exists($metacache{$uri})) {
 9404: #	    $metacache{$uri}={};
 9405: #	}
 9406: 	my $cachetime = 60*60;
 9407:         if ($liburi) {
 9408: 	    $liburi=&declutter($liburi);
 9409:             $filename=$liburi;
 9410:         } else {
 9411: 	    &devalidate_cache_new('meta',$uri);
 9412: 	    undef(%metaentry);
 9413: 	}
 9414:         my %metathesekeys=();
 9415:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9416: 	my $metastring;
 9417: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9418: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9419: 	    $metastring = 
 9420: 		&Apache::lonnet::ssi_body($which,
 9421: 					  ('grade_target' => 'meta'));
 9422: 	    $cachetime = 1; # only want this cached in the child not long term
 9423: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9424:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9425: 	    my $file=&filelocation('',&clutter($filename));
 9426: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9427: 	    $metastring=&getfile($file);
 9428: 	}
 9429:         my $parser=HTML::LCParser->new(\$metastring);
 9430:         my $token;
 9431:         undef %metathesekeys;
 9432:         while ($token=$parser->get_token) {
 9433: 	    if ($token->[0] eq 'S') {
 9434: 		if (defined($token->[2]->{'package'})) {
 9435: #
 9436: # This is a package - get package info
 9437: #
 9438: 		    my $package=$token->[2]->{'package'};
 9439: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9440: 		    if (defined($token->[2]->{'id'})) { 
 9441: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9442: 		    }
 9443: 		    if ($metaentry{':packages'}) {
 9444: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9445: 		    } else {
 9446: 			$metaentry{':packages'}=$package.$keyroot;
 9447: 		    }
 9448: 		    foreach my $pack_entry (keys(%packagetab)) {
 9449: 			my $part=$keyroot;
 9450: 			$part=~s/^\_//;
 9451: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9452: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9453: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9454: 			    # ignore package.tab specified default values
 9455:                             # here &package_tab_default() will fetch those
 9456: 			    if ($subp eq 'default') { next; }
 9457: 			    my $value=$packagetab{$pack_entry};
 9458: 			    my $unikey;
 9459: 			    if ($pack =~ /_0$/) {
 9460: 				$unikey='parameter_0_'.$name;
 9461: 				$part=0;
 9462: 			    } else {
 9463: 				$unikey='parameter'.$keyroot.'_'.$name;
 9464: 			    }
 9465: 			    if ($subp eq 'display') {
 9466: 				$value.=' [Part: '.$part.']';
 9467: 			    }
 9468: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9469: 			    $metathesekeys{$unikey}=1;
 9470: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9471: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9472: 			    }
 9473: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9474: 				$metaentry{':'.$unikey}=
 9475: 				    $metaentry{':'.$unikey.'.default'};
 9476: 			    }
 9477: 			}
 9478: 		    }
 9479: 		} else {
 9480: #
 9481: # This is not a package - some other kind of start tag
 9482: #
 9483: 		    my $entry=$token->[1];
 9484: 		    my $unikey='';
 9485: 
 9486: 		    if ($entry eq 'import') {
 9487: #
 9488: # Importing a library here
 9489: #
 9490:                         my $location=$parser->get_text('/import');
 9491:                         my $dir=$filename;
 9492:                         $dir=~s|[^/]*$||;
 9493:                         $location=&filelocation($dir,$location);
 9494:                        
 9495:                         my $importmode=$token->[2]->{'importmode'};
 9496:                         if ($importmode eq 'problem') {
 9497: # Import as problem/response
 9498:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9499:                         } elsif ($importmode eq 'part') {
 9500: # Import as part(s)
 9501:                            $importedparts=1;
 9502: # We need to get the original file and the imported file to get the part order correct
 9503: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9504: # Load and inspect original file
 9505:                            if ($#origfileimportpartids<0) {
 9506:                               undef(%importedpartids);
 9507:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9508:                               my $origfile=&getfile($origfilelocation);
 9509:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9510:                            }
 9511: 
 9512: # Load and inspect imported file
 9513:                            my $impfile=&getfile($location);
 9514:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9515:                            if ($#impfilepartids>=0) {
 9516: # This problem had parts
 9517:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9518:                            } else {
 9519: # Importing by turning a single problem into a problem part
 9520: # It gets the import-tags ID as part-ID
 9521:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9522:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9523:                            }
 9524:                         } else {
 9525: # Normal import
 9526:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9527:                            if (defined($token->[2]->{'id'})) {
 9528:                               $unikey.='_'.$token->[2]->{'id'};
 9529:                            }
 9530:                         }
 9531: 
 9532: 			if ($depthcount<20) {
 9533: 			    my $metadata = 
 9534: 				&metadata($uri,'keys', $location,$unikey,
 9535: 					  $depthcount+1);
 9536: 			    foreach my $meta (split(',',$metadata)) {
 9537: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9538: 				$metathesekeys{$meta}=1;
 9539: 			    }
 9540: 			
 9541:                         }
 9542: 		    } else {
 9543: #
 9544: # Not importing, some other kind of non-package, non-library start tag
 9545: # 
 9546:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9547:                         if (defined($token->[2]->{'id'})) {
 9548:                             $unikey.='_'.$token->[2]->{'id'};
 9549:                         }
 9550: 			if (defined($token->[2]->{'name'})) { 
 9551: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9552: 			}
 9553: 			$metathesekeys{$unikey}=1;
 9554: 			foreach my $param (@{$token->[3]}) {
 9555: 			    $metaentry{':'.$unikey.'.'.$param} =
 9556: 				$token->[2]->{$param};
 9557: 			}
 9558: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9559: 			my $default=$metaentry{':'.$unikey.'.default'};
 9560: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9561: 		 # only ws inside the tag, and not in default, so use default
 9562: 		 # as value
 9563: 			    $metaentry{':'.$unikey}=$default;
 9564: 			} elsif ( $internaltext =~ /\S/ ) {
 9565: 		  # something interesting inside the tag
 9566: 			    $metaentry{':'.$unikey}=$internaltext;
 9567: 			} else {
 9568: 		  # no interesting values, don't set a default
 9569: 			}
 9570: # end of not-a-package not-a-library import
 9571: 		    }
 9572: # end of not-a-package start tag
 9573: 		}
 9574: # the next is the end of "start tag"
 9575: 	    }
 9576: 	}
 9577: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9578: 	$extension = lc($extension);
 9579: 	if ($extension eq 'htm') { $extension='html'; }
 9580: 
 9581: 	foreach my $key (keys(%packagetab)) {
 9582: 	    #no specific packages #how's our extension
 9583: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9584: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9585: 					 \%metathesekeys);
 9586: 	}
 9587: 
 9588: 	if (!exists($metaentry{':packages'})
 9589: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9590: 	    foreach my $key (keys(%packagetab)) {
 9591: 		#no specific packages well let's get default then
 9592: 		if ($key!~/^default&/) { next; }
 9593: 		&metadata_create_package_def($uri,$key,'default',
 9594: 					     \%metathesekeys);
 9595: 	    }
 9596: 	}
 9597: # are there custom rights to evaluate
 9598: 	if ($metaentry{':copyright'} eq 'custom') {
 9599: 
 9600:     #
 9601:     # Importing a rights file here
 9602:     #
 9603: 	    unless ($depthcount) {
 9604: 		my $location=$metaentry{':customdistributionfile'};
 9605: 		my $dir=$filename;
 9606: 		$dir=~s|[^/]*$||;
 9607: 		$location=&filelocation($dir,$location);
 9608: 		my $rights_metadata =
 9609: 		    &metadata($uri,'keys',$location,'_rights',
 9610: 			      $depthcount+1);
 9611: 		foreach my $rights (split(',',$rights_metadata)) {
 9612: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9613: 		    $metathesekeys{$rights}=1;
 9614: 		}
 9615: 	    }
 9616: 	}
 9617: 	# uniqifiy package listing
 9618: 	my %seen;
 9619: 	my @uniq_packages =
 9620: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9621: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9622: 
 9623:         if ($importedparts) {
 9624: # We had imported parts and need to rebuild partorder
 9625:            $metaentry{':partorder'}='';
 9626:            $metathesekeys{'partorder'}=1;
 9627:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9628:                if ($origfileimportpartids[$index] eq 'part') {
 9629: # original part, part of the problem
 9630:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9631:                } else {
 9632: # we have imported parts at this position
 9633:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9634:                }
 9635:            }
 9636:            $metaentry{':partorder'}=~s/^\,//;
 9637:         }
 9638: 
 9639: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9640: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9641: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9642: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9643: # this is the end of "was not already recently cached
 9644:     }
 9645:     return $metaentry{':'.$what};
 9646: }
 9647: 
 9648: sub metadata_create_package_def {
 9649:     my ($uri,$key,$package,$metathesekeys)=@_;
 9650:     my ($pack,$name,$subp)=split(/\&/,$key);
 9651:     if ($subp eq 'default') { next; }
 9652:     
 9653:     if (defined($metaentry{':packages'})) {
 9654: 	$metaentry{':packages'}.=','.$package;
 9655:     } else {
 9656: 	$metaentry{':packages'}=$package;
 9657:     }
 9658:     my $value=$packagetab{$key};
 9659:     my $unikey;
 9660:     $unikey='parameter_0_'.$name;
 9661:     $metaentry{':'.$unikey.'.part'}=0;
 9662:     $$metathesekeys{$unikey}=1;
 9663:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9664: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9665:     }
 9666:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9667: 	$metaentry{':'.$unikey}=
 9668: 	    $metaentry{':'.$unikey.'.default'};
 9669:     }
 9670: }
 9671: 
 9672: sub metadata_generate_part0 {
 9673:     my ($metadata,$metacache,$uri) = @_;
 9674:     my %allnames;
 9675:     foreach my $metakey (keys(%$metadata)) {
 9676: 	if ($metakey=~/^parameter\_(.*)/) {
 9677: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9678: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9679: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9680: 	    $allnames{$name}=$part;
 9681: 	  }
 9682: 	}
 9683:     }
 9684:     foreach my $name (keys(%allnames)) {
 9685:       $$metadata{"parameter_0_$name"}=1;
 9686:       my $key=":parameter_0_$name";
 9687:       $$metacache{"$key.part"}='0';
 9688:       $$metacache{"$key.name"}=$name;
 9689:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9690: 					   $allnames{$name}.'_'.$name.
 9691: 					   '.type'};
 9692:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9693: 			     '.display'};
 9694:       my $expr='[Part: '.$allnames{$name}.']';
 9695:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9696:       $$metacache{"$key.display"}=$olddis;
 9697:     }
 9698: }
 9699: 
 9700: # ------------------------------------------------------ Devalidate title cache
 9701: 
 9702: sub devalidate_title_cache {
 9703:     my ($url)=@_;
 9704:     if (!$env{'request.course.id'}) { return; }
 9705:     my $symb=&symbread($url);
 9706:     if (!$symb) { return; }
 9707:     my $key=$env{'request.course.id'}."\0".$symb;
 9708:     &devalidate_cache_new('title',$key);
 9709: }
 9710: 
 9711: # ------------------------------------------------- Get the title of a course
 9712: 
 9713: sub current_course_title {
 9714:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9715: }
 9716: # ------------------------------------------------- Get the title of a resource
 9717: 
 9718: sub gettitle {
 9719:     my $urlsymb=shift;
 9720:     my $symb=&symbread($urlsymb);
 9721:     if ($symb) {
 9722: 	my $key=$env{'request.course.id'}."\0".$symb;
 9723: 	my ($result,$cached)=&is_cached_new('title',$key);
 9724: 	if (defined($cached)) { 
 9725: 	    return $result;
 9726: 	}
 9727: 	my ($map,$resid,$url)=&decode_symb($symb);
 9728: 	my $title='';
 9729: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9730: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9731: 	} else {
 9732: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9733: 		    &GDBM_READER(),0640)) {
 9734: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9735: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9736: 		untie(%bighash);
 9737: 	    }
 9738: 	}
 9739: 	$title=~s/\&colon\;/\:/gs;
 9740: 	if ($title) {
 9741: # Remember both $symb and $title for dynamic metadata
 9742:             $accesshash{$symb.'___crstitle'}=$title;
 9743:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9744: # Cache this title and then return it
 9745: 	    return &do_cache_new('title',$key,$title,600);
 9746: 	}
 9747: 	$urlsymb=$url;
 9748:     }
 9749:     my $title=&metadata($urlsymb,'title');
 9750:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9751:     return $title;
 9752: }
 9753: 
 9754: sub get_slot {
 9755:     my ($which,$cnum,$cdom)=@_;
 9756:     if (!$cnum || !$cdom) {
 9757: 	(undef,my $courseid)=&whichuser();
 9758: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9759: 	$cnum=$env{'course.'.$courseid.'.num'};
 9760:     }
 9761:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9762:     my %slotinfo;
 9763:     if (exists($remembered{$key})) {
 9764: 	$slotinfo{$which} = $remembered{$key};
 9765:     } else {
 9766: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9767: 	&Apache::lonhomework::showhash(%slotinfo);
 9768: 	my ($tmp)=keys(%slotinfo);
 9769: 	if ($tmp=~/^error:/) { return (); }
 9770: 	$remembered{$key} = $slotinfo{$which};
 9771:     }
 9772:     if (ref($slotinfo{$which}) eq 'HASH') {
 9773: 	return %{$slotinfo{$which}};
 9774:     }
 9775:     return $slotinfo{$which};
 9776: }
 9777: 
 9778: sub get_reservable_slots {
 9779:     my ($cnum,$cdom,$uname,$udom) = @_;
 9780:     my $now = time;
 9781:     my $reservable_info;
 9782:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9783:     if (exists($remembered{$key})) {
 9784:         $reservable_info = $remembered{$key};
 9785:     } else {
 9786:         my %resv;
 9787:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9788:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9789:         $reservable_info = \%resv;
 9790:         $remembered{$key} = $reservable_info;
 9791:     }
 9792:     return $reservable_info;
 9793: }
 9794: 
 9795: sub get_course_slots {
 9796:     my ($cnum,$cdom) = @_;
 9797:     my $hashid=$cnum.':'.$cdom;
 9798:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9799:     if (defined($cached)) {
 9800:         if (ref($result) eq 'HASH') {
 9801:             return %{$result};
 9802:         }
 9803:     } else {
 9804:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9805:         my ($tmp) = keys(%slots);
 9806:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9807:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9808:             return %slots;
 9809:         }
 9810:     }
 9811:     return;
 9812: }
 9813: 
 9814: sub devalidate_slots_cache {
 9815:     my ($cnum,$cdom)=@_;
 9816:     my $hashid=$cnum.':'.$cdom;
 9817:     &devalidate_cache_new('allslots',$hashid);
 9818: }
 9819: 
 9820: # ------------------------------------------------- Update symbolic store links
 9821: 
 9822: sub symblist {
 9823:     my ($mapname,%newhash)=@_;
 9824:     $mapname=&deversion(&declutter($mapname));
 9825:     my %hash;
 9826:     if (($env{'request.course.fn'}) && (%newhash)) {
 9827:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9828:                       &GDBM_WRCREAT(),0640)) {
 9829: 	    foreach my $url (keys(%newhash)) {
 9830: 		next if ($url eq 'last_known'
 9831: 			 && $env{'form.no_update_last_known'});
 9832: 		$hash{declutter($url)}=&encode_symb($mapname,
 9833: 						    $newhash{$url}->[1],
 9834: 						    $newhash{$url}->[0]);
 9835:             }
 9836:             if (untie(%hash)) {
 9837: 		return 'ok';
 9838:             }
 9839:         }
 9840:     }
 9841:     return 'error';
 9842: }
 9843: 
 9844: # --------------------------------------------------------------- Verify a symb
 9845: 
 9846: sub symbverify {
 9847:     my ($symb,$thisurl)=@_;
 9848:     my $thisfn=$thisurl;
 9849:     $thisfn=&declutter($thisfn);
 9850: # direct jump to resource in page or to a sequence - will construct own symbs
 9851:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9852: # check URL part
 9853:     my ($map,$resid,$url)=&decode_symb($symb);
 9854: 
 9855:     unless ($url eq $thisfn) { return 0; }
 9856: 
 9857:     $symb=&symbclean($symb);
 9858:     $thisurl=&deversion($thisurl);
 9859:     $thisfn=&deversion($thisfn);
 9860: 
 9861:     my %bighash;
 9862:     my $okay=0;
 9863: 
 9864:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9865:                             &GDBM_READER(),0640)) {
 9866:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9867:             $thisurl =~ s/\?.+$//;
 9868:         }
 9869:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9870:         unless ($ids) {
 9871:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9872:             $ids=$bighash{$idkey};
 9873:         }
 9874:         if ($ids) {
 9875: # ------------------------------------------------------------------- Has ID(s)
 9876: 	    foreach my $id (split(/\,/,$ids)) {
 9877: 	       my ($mapid,$resid)=split(/\./,$id);
 9878:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9879:                    $symb =~ s/\?.+$//;
 9880:                }
 9881:                if (
 9882:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9883:    eq $symb) { 
 9884: 		   if (($env{'request.role.adv'}) ||
 9885: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9886:                        ($thisurl eq '/adm/navmaps')) {
 9887: 		       $okay=1; 
 9888: 		   }
 9889: 	       }
 9890: 	   }
 9891:         }
 9892: 	untie(%bighash);
 9893:     }
 9894:     return $okay;
 9895: }
 9896: 
 9897: # --------------------------------------------------------------- Clean-up symb
 9898: 
 9899: sub symbclean {
 9900:     my $symb=shift;
 9901:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9902: # remove version from map
 9903:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9904: 
 9905: # remove version from URL
 9906:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9907: 
 9908: # remove wrapper
 9909: 
 9910:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9911:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9912:     return $symb;
 9913: }
 9914: 
 9915: # ---------------------------------------------- Split symb to find map and url
 9916: 
 9917: sub encode_symb {
 9918:     my ($map,$resid,$url)=@_;
 9919:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9920: }
 9921: 
 9922: sub decode_symb {
 9923:     my $symb=shift;
 9924:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9925:     my ($map,$resid,$url)=split(/___/,$symb);
 9926:     return (&fixversion($map),$resid,&fixversion($url));
 9927: }
 9928: 
 9929: sub fixversion {
 9930:     my $fn=shift;
 9931:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9932:     my %bighash;
 9933:     my $uri=&clutter($fn);
 9934:     my $key=$env{'request.course.id'}.'_'.$uri;
 9935: # is this cached?
 9936:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9937:     if (defined($cached)) { return $result; }
 9938: # unfortunately not cached, or expired
 9939:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9940: 	    &GDBM_READER(),0640)) {
 9941:  	if ($bighash{'version_'.$uri}) {
 9942:  	    my $version=$bighash{'version_'.$uri};
 9943:  	    unless (($version eq 'mostrecent') || 
 9944: 		    ($version==&getversion($uri))) {
 9945:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9946:  	    }
 9947:  	}
 9948:  	untie %bighash;
 9949:     }
 9950:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9951: }
 9952: 
 9953: sub deversion {
 9954:     my $url=shift;
 9955:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9956:     return $url;
 9957: }
 9958: 
 9959: # ------------------------------------------------------ Return symb list entry
 9960: 
 9961: sub symbread {
 9962:     my ($thisfn,$donotrecurse)=@_;
 9963:     my $cache_str='request.symbread.cached.'.$thisfn;
 9964:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9965: # no filename provided? try from environment
 9966:     unless ($thisfn) {
 9967:         if ($env{'request.symb'}) {
 9968: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9969: 	}
 9970: 	$thisfn=$env{'request.filename'};
 9971:     }
 9972:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9973: # is that filename actually a symb? Verify, clean, and return
 9974:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9975: 	if (&symbverify($thisfn,$1)) {
 9976: 	    return $env{$cache_str}=&symbclean($thisfn);
 9977: 	}
 9978:     }
 9979:     $thisfn=declutter($thisfn);
 9980:     my %hash;
 9981:     my %bighash;
 9982:     my $syval='';
 9983:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9984:         my $targetfn = $thisfn;
 9985:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9986:             $targetfn = 'adm/wrapper/'.$thisfn;
 9987:         }
 9988: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9989: 	    $targetfn=$1;
 9990: 	}
 9991:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9992:                       &GDBM_READER(),0640)) {
 9993: 	    $syval=$hash{$targetfn};
 9994:             untie(%hash);
 9995:         }
 9996: # ---------------------------------------------------------- There was an entry
 9997:         if ($syval) {
 9998: 	    #unless ($syval=~/\_\d+$/) {
 9999: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10000: 		    #&appenv({'request.ambiguous' => $thisfn});
10001: 		    #return $env{$cache_str}='';
10002: 		#}    
10003: 		#$syval.=$1;
10004: 	    #}
10005:         } else {
10006: # ------------------------------------------------------- Was not in symb table
10007:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10008:                             &GDBM_READER(),0640)) {
10009: # ---------------------------------------------- Get ID(s) for current resource
10010:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10011:               unless ($ids) { 
10012:                  $ids=$bighash{'ids_/'.$thisfn};
10013:               }
10014:               unless ($ids) {
10015: # alias?
10016: 		  $ids=$bighash{'mapalias_'.$thisfn};
10017:               }
10018:               if ($ids) {
10019: # ------------------------------------------------------------------- Has ID(s)
10020:                  my @possibilities=split(/\,/,$ids);
10021:                  if ($#possibilities==0) {
10022: # ----------------------------------------------- There is only one possibility
10023: 		     my ($mapid,$resid)=split(/\./,$ids);
10024: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10025: 						    $resid,$thisfn);
10026:                  } elsif (!$donotrecurse) {
10027: # ------------------------------------------ There is more than one possibility
10028:                      my $realpossible=0;
10029:                      foreach my $id (@possibilities) {
10030: 			 my $file=$bighash{'src_'.$id};
10031:                          if (&allowed('bre',$file)) {
10032:          		    my ($mapid,$resid)=split(/\./,$id);
10033:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10034: 				$realpossible++;
10035:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10036: 						    $resid,$thisfn);
10037:                             }
10038: 			 }
10039:                      }
10040: 		     if ($realpossible!=1) { $syval=''; }
10041:                  } else {
10042:                      $syval='';
10043:                  }
10044: 	      }
10045:               untie(%bighash)
10046:            }
10047:         }
10048:         if ($syval) {
10049: 	    return $env{$cache_str}=$syval;
10050:         }
10051:     }
10052:     &appenv({'request.ambiguous' => $thisfn});
10053:     return $env{$cache_str}='';
10054: }
10055: 
10056: # ---------------------------------------------------------- Return random seed
10057: 
10058: sub numval {
10059:     my $txt=shift;
10060:     $txt=~tr/A-J/0-9/;
10061:     $txt=~tr/a-j/0-9/;
10062:     $txt=~tr/K-T/0-9/;
10063:     $txt=~tr/k-t/0-9/;
10064:     $txt=~tr/U-Z/0-5/;
10065:     $txt=~tr/u-z/0-5/;
10066:     $txt=~s/\D//g;
10067:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10068:     return int($txt);
10069: }
10070: 
10071: sub numval2 {
10072:     my $txt=shift;
10073:     $txt=~tr/A-J/0-9/;
10074:     $txt=~tr/a-j/0-9/;
10075:     $txt=~tr/K-T/0-9/;
10076:     $txt=~tr/k-t/0-9/;
10077:     $txt=~tr/U-Z/0-5/;
10078:     $txt=~tr/u-z/0-5/;
10079:     $txt=~s/\D//g;
10080:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10081:     my $total;
10082:     foreach my $val (@txts) { $total+=$val; }
10083:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10084:     return int($total);
10085: }
10086: 
10087: sub numval3 {
10088:     use integer;
10089:     my $txt=shift;
10090:     $txt=~tr/A-J/0-9/;
10091:     $txt=~tr/a-j/0-9/;
10092:     $txt=~tr/K-T/0-9/;
10093:     $txt=~tr/k-t/0-9/;
10094:     $txt=~tr/U-Z/0-5/;
10095:     $txt=~tr/u-z/0-5/;
10096:     $txt=~s/\D//g;
10097:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10098:     my $total;
10099:     foreach my $val (@txts) { $total+=$val; }
10100:     if ($_64bit) { $total=(($total<<32)>>32); }
10101:     return $total;
10102: }
10103: 
10104: sub digest {
10105:     my ($data)=@_;
10106:     my $digest=&Digest::MD5::md5($data);
10107:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10108:     my ($e,$f);
10109:     {
10110:         use integer;
10111:         $e=($a+$b);
10112:         $f=($c+$d);
10113:         if ($_64bit) {
10114:             $e=(($e<<32)>>32);
10115:             $f=(($f<<32)>>32);
10116:         }
10117:     }
10118:     if (wantarray) {
10119: 	return ($e,$f);
10120:     } else {
10121: 	my $g;
10122: 	{
10123: 	    use integer;
10124: 	    $g=($e+$f);
10125: 	    if ($_64bit) {
10126: 		$g=(($g<<32)>>32);
10127: 	    }
10128: 	}
10129: 	return $g;
10130:     }
10131: }
10132: 
10133: sub latest_rnd_algorithm_id {
10134:     return '64bit5';
10135: }
10136: 
10137: sub get_rand_alg {
10138:     my ($courseid)=@_;
10139:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10140:     if ($courseid) {
10141: 	return $env{"course.$courseid.rndseed"};
10142:     }
10143:     return &latest_rnd_algorithm_id();
10144: }
10145: 
10146: sub validCODE {
10147:     my ($CODE)=@_;
10148:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10149:     return 0;
10150: }
10151: 
10152: sub getCODE {
10153:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10154:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10155: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10156: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10157: 	return $Apache::lonhomework::history{'resource.CODE'};
10158:     }
10159:     return undef;
10160: }
10161: #
10162: #  Determines the random seed for a specific context:
10163: #
10164: # parameters:
10165: #   symb      - in course context the symb for the seed.
10166: #   course_id - The course id of the form domain_coursenum.
10167: #   domain    - Domain for the user.
10168: #   course    - Course for the user.
10169: #   cenv      - environment of the course.
10170: #
10171: # NOTE:
10172: #   All parameters are picked out of the environment if missing
10173: #   or not defined.
10174: #   If a symb cannot be determined the current time is used instead.
10175: #
10176: #  For a given well defined symb, courside, domain, username,
10177: #  and course environment, the seed is reproducible.
10178: #
10179: sub rndseed {
10180:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10181:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10182:     if (!defined($symb)) {
10183: 	unless ($symb=$wsymb) { return time; }
10184:     }
10185:     if (!defined $courseid) { 
10186: 	$courseid=$wcourseid; 
10187:     }
10188:     if (!defined $domain) { $domain=$wdomain; }
10189:     if (!defined $username) { $username=$wusername }
10190: 
10191:     my $which;
10192:     if (defined($cenv->{'rndseed'})) {
10193: 	$which = $cenv->{'rndseed'};
10194:     } else {
10195: 	$which =&get_rand_alg($courseid);
10196:     }
10197:     if (defined(&getCODE())) {
10198: 
10199: 	if ($which eq '64bit5') {
10200: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10201: 	} elsif ($which eq '64bit4') {
10202: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10203: 	} else {
10204: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10205: 	}
10206:     } elsif ($which eq '64bit5') {
10207: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10208:     } elsif ($which eq '64bit4') {
10209: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10210:     } elsif ($which eq '64bit3') {
10211: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10212:     } elsif ($which eq '64bit2') {
10213: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10214:     } elsif ($which eq '64bit') {
10215: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10216:     }
10217:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10218: }
10219: 
10220: sub rndseed_32bit {
10221:     my ($symb,$courseid,$domain,$username)=@_;
10222:     {
10223: 	use integer;
10224: 	my $symbchck=unpack("%32C*",$symb) << 27;
10225: 	my $symbseed=numval($symb) << 22;
10226: 	my $namechck=unpack("%32C*",$username) << 17;
10227: 	my $nameseed=numval($username) << 12;
10228: 	my $domainseed=unpack("%32C*",$domain) << 7;
10229: 	my $courseseed=unpack("%32C*",$courseid);
10230: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10231: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10232: 	#&logthis("rndseed :$num:$symb");
10233: 	if ($_64bit) { $num=(($num<<32)>>32); }
10234: 	return $num;
10235:     }
10236: }
10237: 
10238: sub rndseed_64bit {
10239:     my ($symb,$courseid,$domain,$username)=@_;
10240:     {
10241: 	use integer;
10242: 	my $symbchck=unpack("%32S*",$symb) << 21;
10243: 	my $symbseed=numval($symb) << 10;
10244: 	my $namechck=unpack("%32S*",$username);
10245: 	
10246: 	my $nameseed=numval($username) << 21;
10247: 	my $domainseed=unpack("%32S*",$domain) << 10;
10248: 	my $courseseed=unpack("%32S*",$courseid);
10249: 	
10250: 	my $num1=$symbchck+$symbseed+$namechck;
10251: 	my $num2=$nameseed+$domainseed+$courseseed;
10252: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10253: 	#&logthis("rndseed :$num:$symb");
10254: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10255: 	return "$num1,$num2";
10256:     }
10257: }
10258: 
10259: sub rndseed_64bit2 {
10260:     my ($symb,$courseid,$domain,$username)=@_;
10261:     {
10262: 	use integer;
10263: 	# strings need to be an even # of cahracters long, it it is odd the
10264:         # last characters gets thrown away
10265: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10266: 	my $symbseed=numval($symb) << 10;
10267: 	my $namechck=unpack("%32S*",$username.' ');
10268: 	
10269: 	my $nameseed=numval($username) << 21;
10270: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10271: 	my $courseseed=unpack("%32S*",$courseid.' ');
10272: 	
10273: 	my $num1=$symbchck+$symbseed+$namechck;
10274: 	my $num2=$nameseed+$domainseed+$courseseed;
10275: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10276: 	#&logthis("rndseed :$num:$symb");
10277: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10278: 	return "$num1,$num2";
10279:     }
10280: }
10281: 
10282: sub rndseed_64bit3 {
10283:     my ($symb,$courseid,$domain,$username)=@_;
10284:     {
10285: 	use integer;
10286: 	# strings need to be an even # of cahracters long, it it is odd the
10287:         # last characters gets thrown away
10288: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10289: 	my $symbseed=numval2($symb) << 10;
10290: 	my $namechck=unpack("%32S*",$username.' ');
10291: 	
10292: 	my $nameseed=numval2($username) << 21;
10293: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10294: 	my $courseseed=unpack("%32S*",$courseid.' ');
10295: 	
10296: 	my $num1=$symbchck+$symbseed+$namechck;
10297: 	my $num2=$nameseed+$domainseed+$courseseed;
10298: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10299: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10300: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10301: 	
10302: 	return "$num1:$num2";
10303:     }
10304: }
10305: 
10306: sub rndseed_64bit4 {
10307:     my ($symb,$courseid,$domain,$username)=@_;
10308:     {
10309: 	use integer;
10310: 	# strings need to be an even # of cahracters long, it it is odd the
10311:         # last characters gets thrown away
10312: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10313: 	my $symbseed=numval3($symb) << 10;
10314: 	my $namechck=unpack("%32S*",$username.' ');
10315: 	
10316: 	my $nameseed=numval3($username) << 21;
10317: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10318: 	my $courseseed=unpack("%32S*",$courseid.' ');
10319: 	
10320: 	my $num1=$symbchck+$symbseed+$namechck;
10321: 	my $num2=$nameseed+$domainseed+$courseseed;
10322: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10323: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10324: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10325: 	
10326: 	return "$num1:$num2";
10327:     }
10328: }
10329: 
10330: sub rndseed_64bit5 {
10331:     my ($symb,$courseid,$domain,$username)=@_;
10332:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10333:     return "$num1:$num2";
10334: }
10335: 
10336: sub rndseed_CODE_64bit {
10337:     my ($symb,$courseid,$domain,$username)=@_;
10338:     {
10339: 	use integer;
10340: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10341: 	my $symbseed=numval2($symb);
10342: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10343: 	my $CODEseed=numval(&getCODE());
10344: 	my $courseseed=unpack("%32S*",$courseid.' ');
10345: 	my $num1=$symbseed+$CODEchck;
10346: 	my $num2=$CODEseed+$courseseed+$symbchck;
10347: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10348: 	#&logthis("rndseed :$num1:$num2:$symb");
10349: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10350: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10351: 	return "$num1:$num2";
10352:     }
10353: }
10354: 
10355: sub rndseed_CODE_64bit4 {
10356:     my ($symb,$courseid,$domain,$username)=@_;
10357:     {
10358: 	use integer;
10359: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10360: 	my $symbseed=numval3($symb);
10361: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10362: 	my $CODEseed=numval3(&getCODE());
10363: 	my $courseseed=unpack("%32S*",$courseid.' ');
10364: 	my $num1=$symbseed+$CODEchck;
10365: 	my $num2=$CODEseed+$courseseed+$symbchck;
10366: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10367: 	#&logthis("rndseed :$num1:$num2:$symb");
10368: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10369: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10370: 	return "$num1:$num2";
10371:     }
10372: }
10373: 
10374: sub rndseed_CODE_64bit5 {
10375:     my ($symb,$courseid,$domain,$username)=@_;
10376:     my $code = &getCODE();
10377:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10378:     return "$num1:$num2";
10379: }
10380: 
10381: sub setup_random_from_rndseed {
10382:     my ($rndseed)=@_;
10383:     if ($rndseed =~/([,:])/) {
10384: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10385: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10386:     } else {
10387: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10388:     }
10389: }
10390: 
10391: sub latest_receipt_algorithm_id {
10392:     return 'receipt3';
10393: }
10394: 
10395: sub recunique {
10396:     my $fucourseid=shift;
10397:     my $unique;
10398:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10399: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10400: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10401:     } else {
10402: 	$unique=$perlvar{'lonReceipt'};
10403:     }
10404:     return unpack("%32C*",$unique);
10405: }
10406: 
10407: sub recprefix {
10408:     my $fucourseid=shift;
10409:     my $prefix;
10410:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10411: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10412: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10413:     } else {
10414: 	$prefix=$perlvar{'lonHostID'};
10415:     }
10416:     return unpack("%32C*",$prefix);
10417: }
10418: 
10419: sub ireceipt {
10420:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10421: 
10422:     my $return =&recprefix($fucourseid).'-';
10423: 
10424:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10425: 	$env{'request.state'} eq 'construct') {
10426: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10427: 	return $return;
10428:     }
10429: 
10430:     my $cuname=unpack("%32C*",$funame);
10431:     my $cudom=unpack("%32C*",$fudom);
10432:     my $cucourseid=unpack("%32C*",$fucourseid);
10433:     my $cusymb=unpack("%32C*",$fusymb);
10434:     my $cunique=&recunique($fucourseid);
10435:     my $cpart=unpack("%32S*",$part);
10436:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10437: 
10438: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10439: 			       
10440: 	$return.= ($cunique%$cuname+
10441: 		   $cunique%$cudom+
10442: 		   $cusymb%$cuname+
10443: 		   $cusymb%$cudom+
10444: 		   $cucourseid%$cuname+
10445: 		   $cucourseid%$cudom+
10446: 		   $cpart%$cuname+
10447: 		   $cpart%$cudom);
10448:     } else {
10449: 	$return.= ($cunique%$cuname+
10450: 		   $cunique%$cudom+
10451: 		   $cusymb%$cuname+
10452: 		   $cusymb%$cudom+
10453: 		   $cucourseid%$cuname+
10454: 		   $cucourseid%$cudom);
10455:     }
10456:     return $return;
10457: }
10458: 
10459: sub receipt {
10460:     my ($part)=@_;
10461:     my ($symb,$courseid,$domain,$name) = &whichuser();
10462:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10463: }
10464: 
10465: sub whichuser {
10466:     my ($passedsymb)=@_;
10467:     my ($symb,$courseid,$domain,$name,$publicuser);
10468:     if (defined($env{'form.grade_symb'})) {
10469: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10470: 	my $allowed=&allowed('vgr',$tmp_courseid);
10471: 	if (!$allowed &&
10472: 	    exists($env{'request.course.sec'}) &&
10473: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10474: 	    $allowed=&allowed('vgr',$tmp_courseid.
10475: 			      '/'.$env{'request.course.sec'});
10476: 	}
10477: 	if ($allowed) {
10478: 	    ($symb)=&get_env_multiple('form.grade_symb');
10479: 	    $courseid=$tmp_courseid;
10480: 	    ($domain)=&get_env_multiple('form.grade_domain');
10481: 	    ($name)=&get_env_multiple('form.grade_username');
10482: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10483: 	}
10484:     }
10485:     if (!$passedsymb) {
10486: 	$symb=&symbread();
10487:     } else {
10488: 	$symb=$passedsymb;
10489:     }
10490:     $courseid=$env{'request.course.id'};
10491:     $domain=$env{'user.domain'};
10492:     $name=$env{'user.name'};
10493:     if ($name eq 'public' && $domain eq 'public') {
10494: 	if (!defined($env{'form.username'})) {
10495: 	    $env{'form.username'}.=time.rand(10000000);
10496: 	}
10497: 	$name.=$env{'form.username'};
10498:     }
10499:     return ($symb,$courseid,$domain,$name,$publicuser);
10500: 
10501: }
10502: 
10503: # ------------------------------------------------------------ Serves up a file
10504: # returns either the contents of the file or 
10505: # -1 if the file doesn't exist
10506: #
10507: # if the target is a file that was uploaded via DOCS, 
10508: # a check will be made to see if a current copy exists on the local server,
10509: # if it does this will be served, otherwise a copy will be retrieved from
10510: # the home server for the course and stored in /home/httpd/html/userfiles on
10511: # the local server.   
10512: 
10513: sub getfile {
10514:     my ($file) = @_;
10515:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10516:     &repcopy($file);
10517:     return &readfile($file);
10518: }
10519: 
10520: sub repcopy_userfile {
10521:     my ($file)=@_;
10522:     my $londocroot = $perlvar{'lonDocRoot'};
10523:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10524:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10525:     my ($cdom,$cnum,$filename) = 
10526: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10527:     my $uri="/uploaded/$cdom/$cnum/$filename";
10528:     if (-e "$file") {
10529: # we already have a local copy, check it out
10530: 	my @fileinfo = stat($file);
10531: 	my $rtncode;
10532: 	my $info;
10533: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10534: 	if ($lwpresp ne 'ok') {
10535: # there is no such file anymore, even though we had a local copy
10536: 	    if ($rtncode eq '404') {
10537: 		unlink($file);
10538: 	    }
10539: 	    return -1;
10540: 	}
10541: 	if ($info < $fileinfo[9]) {
10542: # nice, the file we have is up-to-date, just say okay
10543: 	    return 'ok';
10544: 	} else {
10545: # the file is outdated, get rid of it
10546: 	    unlink($file);
10547: 	}
10548:     }
10549: # one way or the other, at this point, we don't have the file
10550: # construct the correct path for the file
10551:     my @parts = ($cdom,$cnum); 
10552:     if ($filename =~ m|^(.+)/[^/]+$|) {
10553: 	push @parts, split(/\//,$1);
10554:     }
10555:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10556:     foreach my $part (@parts) {
10557: 	$path .= '/'.$part;
10558: 	if (!-e $path) {
10559: 	    mkdir($path,0770);
10560: 	}
10561:     }
10562: # now the path exists for sure
10563: # get a user agent
10564:     my $ua=new LWP::UserAgent;
10565:     my $transferfile=$file.'.in.transfer';
10566: # FIXME: this should flock
10567:     if (-e $transferfile) { return 'ok'; }
10568:     my $request;
10569:     $uri=~s/^\///;
10570:     my $homeserver = &homeserver($cnum,$cdom);
10571:     my $protocol = $protocol{$homeserver};
10572:     $protocol = 'http' if ($protocol ne 'https');
10573:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10574:     my $response=$ua->request($request,$transferfile);
10575: # did it work?
10576:     if ($response->is_error()) {
10577: 	unlink($transferfile);
10578: 	&logthis("Userfile repcopy failed for $uri");
10579: 	return -1;
10580:     }
10581: # worked, rename the transfer file
10582:     rename($transferfile,$file);
10583:     return 'ok';
10584: }
10585: 
10586: sub tokenwrapper {
10587:     my $uri=shift;
10588:     $uri=~s|^https?\://([^/]+)||;
10589:     $uri=~s|^/||;
10590:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10591:     my $token=$1;
10592:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10593:     if ($udom && $uname && $file) {
10594: 	$file=~s|(\?\.*)*$||;
10595:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10596:         my $homeserver = &homeserver($uname,$udom);
10597:         my $protocol = $protocol{$homeserver};
10598:         $protocol = 'http' if ($protocol ne 'https');
10599:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10600:                (($uri=~/\?/)?'&':'?').'token='.$token.
10601:                                '&tokenissued='.$perlvar{'lonHostID'};
10602:     } else {
10603:         return '/adm/notfound.html';
10604:     }
10605: }
10606: 
10607: # call with reqtype HEAD: get last modification time
10608: # call with reqtype GET: get the file contents
10609: # Do not call this with reqtype GET for large files! It loads everything into memory
10610: #
10611: sub getuploaded {
10612:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10613:     $uri=~s/^\///;
10614:     my $homeserver = &homeserver($cnum,$cdom);
10615:     my $protocol = $protocol{$homeserver};
10616:     $protocol = 'http' if ($protocol ne 'https');
10617:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10618:     my $ua=new LWP::UserAgent;
10619:     my $request=new HTTP::Request($reqtype,$uri);
10620:     my $response=$ua->request($request);
10621:     $$rtncode = $response->code;
10622:     if (! $response->is_success()) {
10623: 	return 'failed';
10624:     }      
10625:     if ($reqtype eq 'HEAD') {
10626: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10627:     } elsif ($reqtype eq 'GET') {
10628: 	$$info = $response->content;
10629:     }
10630:     return 'ok';
10631: }
10632: 
10633: sub readfile {
10634:     my $file = shift;
10635:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10636:     my $fh;
10637:     open($fh,"<$file");
10638:     my $a='';
10639:     while (my $line = <$fh>) { $a .= $line; }
10640:     return $a;
10641: }
10642: 
10643: sub filelocation {
10644:     my ($dir,$file) = @_;
10645:     my $location;
10646:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10647: 
10648:     if ($file =~ m-^/adm/-) {
10649: 	$file=~s-^/adm/wrapper/-/-;
10650: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10651:     }
10652: 
10653:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10654:         $location = $file;
10655:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10656:         my ($udom,$uname,$filename)=
10657:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10658:         my $home=&homeserver($uname,$udom);
10659:         my $is_me=0;
10660:         my @ids=&current_machine_ids();
10661:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10662:         if ($is_me) {
10663:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10664:         } else {
10665:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10666:   	      $udom.'/'.$uname.'/'.$filename;
10667:         }
10668:     } elsif ($file =~ m-^/adm/-) {
10669: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10670:     } else {
10671:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10672:         $file=~s:^/(res|priv)/:/:;
10673:         my $space=$1;
10674:         if ( !( $file =~ m:^/:) ) {
10675:             $location = $dir. '/'.$file;
10676:         } else {
10677:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10678:         }
10679:     }
10680:     $location=~s://+:/:g; # remove duplicate /
10681:     while ($location=~m{/\.\./}) {
10682: 	if ($location =~ m{/[^/]+/\.\./}) {
10683: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10684: 	} else {
10685: 	    $location=~ s{/\.\./}{/}g;
10686: 	}
10687:     } #remove dir/..
10688:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10689:     return $location;
10690: }
10691: 
10692: sub hreflocation {
10693:     my ($dir,$file)=@_;
10694:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10695: 	$file=filelocation($dir,$file);
10696:     } elsif ($file=~m-^/adm/-) {
10697: 	$file=~s-^/adm/wrapper/-/-;
10698: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10699:     }
10700:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10701: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10702:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10703: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10704: 	        {/uploaded/$1/$2/}x;
10705:     }
10706:     if ($file=~ m{^/userfiles/}) {
10707: 	$file =~ s{^/userfiles/}{/uploaded/};
10708:     }
10709:     return $file;
10710: }
10711: 
10712: 
10713: 
10714: 
10715: 
10716: sub current_machine_domains {
10717:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10718: }
10719: 
10720: sub machine_domains {
10721:     my ($hostname) = @_;
10722:     my @domains;
10723:     my %hostname = &all_hostnames();
10724:     while( my($id, $name) = each(%hostname)) {
10725: #	&logthis("-$id-$name-$hostname-");
10726: 	if ($hostname eq $name) {
10727: 	    push(@domains,&host_domain($id));
10728: 	}
10729:     }
10730:     return @domains;
10731: }
10732: 
10733: sub current_machine_ids {
10734:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10735: }
10736: 
10737: sub machine_ids {
10738:     my ($hostname) = @_;
10739:     $hostname ||= &hostname($perlvar{'lonHostID'});
10740:     my @ids;
10741:     my %name_to_host = &all_names();
10742:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10743: 	return @{ $name_to_host{$hostname} };
10744:     }
10745:     return;
10746: }
10747: 
10748: sub additional_machine_domains {
10749:     my @domains;
10750:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10751:     while( my $line = <$fh>) {
10752:         $line =~ s/\s//g;
10753:         push(@domains,$line);
10754:     }
10755:     return @domains;
10756: }
10757: 
10758: sub default_login_domain {
10759:     my $domain = $perlvar{'lonDefDomain'};
10760:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10761:     foreach my $posdom (&current_machine_domains(),
10762:                         &additional_machine_domains()) {
10763:         if (lc($posdom) eq lc($testdomain)) {
10764:             $domain=$posdom;
10765:             last;
10766:         }
10767:     }
10768:     return $domain;
10769: }
10770: 
10771: # ------------------------------------------------------------- Declutters URLs
10772: 
10773: sub declutter {
10774:     my $thisfn=shift;
10775:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10776:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10777:     $thisfn=~s/^\///;
10778:     $thisfn=~s|^adm/wrapper/||;
10779:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10780:     $thisfn=~s/^res\///;
10781:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10782:         $thisfn=~s/\?.+$//;
10783:     }
10784:     return $thisfn;
10785: }
10786: 
10787: # ------------------------------------------------------------- Clutter up URLs
10788: 
10789: sub clutter {
10790:     my $thisfn='/'.&declutter(shift);
10791:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10792: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10793:        $thisfn='/res'.$thisfn; 
10794:     }
10795:     if ($thisfn !~m|^/adm|) {
10796: 	if ($thisfn =~ m|^/ext/|) {
10797: 	    $thisfn='/adm/wrapper'.$thisfn;
10798: 	} else {
10799: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10800: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10801: 	    if ($embstyle eq 'ssi'
10802: 		|| ($embstyle eq 'hdn')
10803: 		|| ($embstyle eq 'rat')
10804: 		|| ($embstyle eq 'prv')
10805: 		|| ($embstyle eq 'ign')) {
10806: 		#do nothing with these
10807: 	    } elsif (($embstyle eq 'img') 
10808: 		|| ($embstyle eq 'emb')
10809: 		|| ($embstyle eq 'wrp')) {
10810: 		$thisfn='/adm/wrapper'.$thisfn;
10811: 	    } elsif ($embstyle eq 'unk'
10812: 		     && $thisfn!~/\.(sequence|page)$/) {
10813: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10814: 	    } else {
10815: #		&logthis("Got a blank emb style");
10816: 	    }
10817: 	}
10818:     }
10819:     return $thisfn;
10820: }
10821: 
10822: sub clutter_with_no_wrapper {
10823:     my $uri = &clutter(shift);
10824:     if ($uri =~ m-^/adm/-) {
10825: 	$uri =~ s-^/adm/wrapper/-/-;
10826: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10827:     }
10828:     return $uri;
10829: }
10830: 
10831: sub freeze_escape {
10832:     my ($value)=@_;
10833:     if (ref($value)) {
10834: 	$value=&nfreeze($value);
10835: 	return '__FROZEN__'.&escape($value);
10836:     }
10837:     return &escape($value);
10838: }
10839: 
10840: 
10841: sub thaw_unescape {
10842:     my ($value)=@_;
10843:     if ($value =~ /^__FROZEN__/) {
10844: 	substr($value,0,10,undef);
10845: 	$value=&unescape($value);
10846: 	return &thaw($value);
10847:     }
10848:     return &unescape($value);
10849: }
10850: 
10851: sub correct_line_ends {
10852:     my ($result)=@_;
10853:     $$result =~s/\r\n/\n/mg;
10854:     $$result =~s/\r/\n/mg;
10855: }
10856: # ================================================================ Main Program
10857: 
10858: sub goodbye {
10859:    &logthis("Starting Shut down");
10860: #not converted to using infrastruture and probably shouldn't be
10861:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10862: #converted
10863: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10864:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10865: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10866: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10867: #1.1 only
10868: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10869: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10870: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10871: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10872:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10873:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10874:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10875:    &flushcourselogs();
10876:    &logthis("Shutting down");
10877: }
10878: 
10879: sub get_dns {
10880:     my ($url,$func,$ignore_cache) = @_;
10881:     if (!$ignore_cache) {
10882: 	my ($content,$cached)=
10883: 	    &Apache::lonnet::is_cached_new('dns',$url);
10884: 	if ($cached) {
10885: 	    &$func($content);
10886: 	    return;
10887: 	}
10888:     }
10889: 
10890:     my %alldns;
10891:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10892:     foreach my $dns (<$config>) {
10893: 	next if ($dns !~ /^\^(\S*)/x);
10894:         my $line = $1;
10895:         my ($host,$protocol) = split(/:/,$line);
10896:         if ($protocol ne 'https') {
10897:             $protocol = 'http';
10898:         }
10899: 	$alldns{$host} = $protocol;
10900:     }
10901:     while (%alldns) {
10902: 	my ($dns) = keys(%alldns);
10903: 	my $ua=new LWP::UserAgent;
10904:         $ua->timeout(30);
10905: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10906: 	my $response=$ua->request($request);
10907:         delete($alldns{$dns});
10908: 	next if ($response->is_error());
10909: 	my @content = split("\n",$response->content);
10910: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10911: 	&$func(\@content);
10912: 	return;
10913:     }
10914:     close($config);
10915:     my $which = (split('/',$url))[3];
10916:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10917:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10918:     my @content = <$config>;
10919:     &$func(\@content);
10920:     return;
10921: }
10922: # ------------------------------------------------------------ Read domain file
10923: {
10924:     my $loaded;
10925:     my %domain;
10926: 
10927:     sub parse_domain_tab {
10928: 	my ($lines) = @_;
10929: 	foreach my $line (@$lines) {
10930: 	    next if ($line =~ /^(\#|\s*$ )/x);
10931: 
10932: 	    chomp($line);
10933: 	    my ($name,@elements) = split(/:/,$line,9);
10934: 	    my %this_domain;
10935: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10936: 			       'lang_def', 'city', 'longi', 'lati',
10937: 			       'primary') {
10938: 		$this_domain{$field} = shift(@elements);
10939: 	    }
10940: 	    $domain{$name} = \%this_domain;
10941: 	}
10942:     }
10943: 
10944:     sub reset_domain_info {
10945: 	undef($loaded);
10946: 	undef(%domain);
10947:     }
10948: 
10949:     sub load_domain_tab {
10950: 	my ($ignore_cache) = @_;
10951: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10952: 	my $fh;
10953: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10954: 	    my @lines = <$fh>;
10955: 	    &parse_domain_tab(\@lines);
10956: 	}
10957: 	close($fh);
10958: 	$loaded = 1;
10959:     }
10960: 
10961:     sub domain {
10962: 	&load_domain_tab() if (!$loaded);
10963: 
10964: 	my ($name,$what) = @_;
10965: 	return if ( !exists($domain{$name}) );
10966: 
10967: 	if (!$what) {
10968: 	    return $domain{$name}{'description'};
10969: 	}
10970: 	return $domain{$name}{$what};
10971:     }
10972: 
10973:     sub domain_info {
10974:         &load_domain_tab() if (!$loaded);
10975:         return %domain;
10976:     }
10977: 
10978: }
10979: 
10980: 
10981: # ------------------------------------------------------------- Read hosts file
10982: {
10983:     my %hostname;
10984:     my %hostdom;
10985:     my %libserv;
10986:     my $loaded;
10987:     my %name_to_host;
10988:     my %internetdom;
10989:     my %LC_dns_serv;
10990: 
10991:     sub parse_hosts_tab {
10992: 	my ($file) = @_;
10993: 	foreach my $configline (@$file) {
10994: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10995:             chomp($configline);
10996: 	    if ($configline =~ /^\^/) {
10997:                 if ($configline =~ /^\^([\w.\-]+)/) {
10998:                     $LC_dns_serv{$1} = 1;
10999:                 }
11000:                 next;
11001:             }
11002: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11003: 	    $name=~s/\s//g;
11004: 	    if ($id && $domain && $role && $name) {
11005: 		$hostname{$id}=$name;
11006: 		push(@{$name_to_host{$name}}, $id);
11007: 		$hostdom{$id}=$domain;
11008: 		if ($role eq 'library') { $libserv{$id}=$name; }
11009:                 if (defined($protocol)) {
11010:                     if ($protocol eq 'https') {
11011:                         $protocol{$id} = $protocol;
11012:                     } else {
11013:                         $protocol{$id} = 'http'; 
11014:                     }
11015:                 } else {
11016:                     $protocol{$id} = 'http';
11017:                 }
11018:                 if (defined($intdom)) {
11019:                     $internetdom{$id} = $intdom;
11020:                 }
11021: 	    }
11022: 	}
11023:     }
11024:     
11025:     sub reset_hosts_info {
11026: 	&purge_remembered();
11027: 	&reset_domain_info();
11028: 	&reset_hosts_ip_info();
11029: 	undef(%name_to_host);
11030: 	undef(%hostname);
11031: 	undef(%hostdom);
11032: 	undef(%libserv);
11033: 	undef($loaded);
11034:     }
11035: 
11036:     sub load_hosts_tab {
11037: 	my ($ignore_cache) = @_;
11038: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11039: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11040: 	my @config = <$config>;
11041: 	&parse_hosts_tab(\@config);
11042: 	close($config);
11043: 	$loaded=1;
11044:     }
11045: 
11046:     sub hostname {
11047: 	&load_hosts_tab() if (!$loaded);
11048: 
11049: 	my ($lonid) = @_;
11050: 	return $hostname{$lonid};
11051:     }
11052: 
11053:     sub all_hostnames {
11054: 	&load_hosts_tab() if (!$loaded);
11055: 
11056: 	return %hostname;
11057:     }
11058: 
11059:     sub all_names {
11060: 	&load_hosts_tab() if (!$loaded);
11061: 
11062: 	return %name_to_host;
11063:     }
11064: 
11065:     sub all_host_domain {
11066:         &load_hosts_tab() if (!$loaded);
11067:         return %hostdom;
11068:     }
11069: 
11070:     sub is_library {
11071: 	&load_hosts_tab() if (!$loaded);
11072: 
11073: 	return exists($libserv{$_[0]});
11074:     }
11075: 
11076:     sub all_library {
11077: 	&load_hosts_tab() if (!$loaded);
11078: 
11079: 	return %libserv;
11080:     }
11081: 
11082:     sub unique_library {
11083: 	#2x reverse removes all hostnames that appear more than once
11084:         my %unique = reverse &all_library();
11085:         return reverse %unique;
11086:     }
11087: 
11088:     sub get_servers {
11089: 	&load_hosts_tab() if (!$loaded);
11090: 
11091: 	my ($domain,$type) = @_;
11092: 	my %possible_hosts = ($type eq 'library') ? %libserv
11093: 	                                          : %hostname;
11094: 	my %result;
11095: 	if (ref($domain) eq 'ARRAY') {
11096: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11097: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11098: 		    $result{$host} = $hostname;
11099: 		}
11100: 	    }
11101: 	} else {
11102: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11103: 		if ($hostdom{$host} eq $domain) {
11104: 		    $result{$host} = $hostname;
11105: 		}
11106: 	    }
11107: 	}
11108: 	return %result;
11109:     }
11110: 
11111:     sub get_unique_servers {
11112:         my %unique = reverse &get_servers(@_);
11113: 	return reverse %unique;
11114:     }
11115: 
11116:     sub host_domain {
11117: 	&load_hosts_tab() if (!$loaded);
11118: 
11119: 	my ($lonid) = @_;
11120: 	return $hostdom{$lonid};
11121:     }
11122: 
11123:     sub all_domains {
11124: 	&load_hosts_tab() if (!$loaded);
11125: 
11126: 	my %seen;
11127: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11128: 	return @uniq;
11129:     }
11130: 
11131:     sub internet_dom {
11132:         &load_hosts_tab() if (!$loaded);
11133: 
11134:         my ($lonid) = @_;
11135:         return $internetdom{$lonid};
11136:     }
11137: 
11138:     sub is_LC_dns {
11139:         &load_hosts_tab() if (!$loaded);
11140: 
11141:         my ($hostname) = @_;
11142:         return exists($LC_dns_serv{$hostname});
11143:     }
11144: 
11145: }
11146: 
11147: { 
11148:     my %iphost;
11149:     my %name_to_ip;
11150:     my %lonid_to_ip;
11151: 
11152:     sub get_hosts_from_ip {
11153: 	my ($ip) = @_;
11154: 	my %iphosts = &get_iphost();
11155: 	if (ref($iphosts{$ip})) {
11156: 	    return @{$iphosts{$ip}};
11157: 	}
11158: 	return;
11159:     }
11160:     
11161:     sub reset_hosts_ip_info {
11162: 	undef(%iphost);
11163: 	undef(%name_to_ip);
11164: 	undef(%lonid_to_ip);
11165:     }
11166: 
11167:     sub get_host_ip {
11168: 	my ($lonid) = @_;
11169: 	if (exists($lonid_to_ip{$lonid})) {
11170: 	    return $lonid_to_ip{$lonid};
11171: 	}
11172: 	my $name=&hostname($lonid);
11173:    	my $ip = gethostbyname($name);
11174: 	return if (!$ip || length($ip) ne 4);
11175: 	$ip=inet_ntoa($ip);
11176: 	$name_to_ip{$name}   = $ip;
11177: 	$lonid_to_ip{$lonid} = $ip;
11178: 	return $ip;
11179:     }
11180:     
11181:     sub get_iphost {
11182: 	my ($ignore_cache) = @_;
11183: 
11184: 	if (!$ignore_cache) {
11185: 	    if (%iphost) {
11186: 		return %iphost;
11187: 	    }
11188: 	    my ($ip_info,$cached)=
11189: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11190: 	    if ($cached) {
11191: 		%iphost      = %{$ip_info->[0]};
11192: 		%name_to_ip  = %{$ip_info->[1]};
11193: 		%lonid_to_ip = %{$ip_info->[2]};
11194: 		return %iphost;
11195: 	    }
11196: 	}
11197: 
11198: 	# get yesterday's info for fallback
11199: 	my %old_name_to_ip;
11200: 	my ($ip_info,$cached)=
11201: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11202: 	if ($cached) {
11203: 	    %old_name_to_ip = %{$ip_info->[1]};
11204: 	}
11205: 
11206: 	my %name_to_host = &all_names();
11207: 	foreach my $name (keys(%name_to_host)) {
11208: 	    my $ip;
11209: 	    if (!exists($name_to_ip{$name})) {
11210: 		$ip = gethostbyname($name);
11211: 		if (!$ip || length($ip) ne 4) {
11212: 		    if (defined($old_name_to_ip{$name})) {
11213: 			$ip = $old_name_to_ip{$name};
11214: 			&logthis("Can't find $name defaulting to old $ip");
11215: 		    } else {
11216: 			&logthis("Name $name no IP found");
11217: 			next;
11218: 		    }
11219: 		} else {
11220: 		    $ip=inet_ntoa($ip);
11221: 		}
11222: 		$name_to_ip{$name} = $ip;
11223: 	    } else {
11224: 		$ip = $name_to_ip{$name};
11225: 	    }
11226: 	    foreach my $id (@{ $name_to_host{$name} }) {
11227: 		$lonid_to_ip{$id} = $ip;
11228: 	    }
11229: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11230: 	}
11231: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11232: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11233: 				      48*60*60);
11234: 
11235: 	return %iphost;
11236:     }
11237: 
11238:     #
11239:     #  Given a DNS returns the loncapa host name for that DNS 
11240:     # 
11241:     sub host_from_dns {
11242:         my ($dns) = @_;
11243:         my @hosts;
11244:         my $ip;
11245: 
11246:         if (exists($name_to_ip{$dns})) {
11247:             $ip = $name_to_ip{$dns};
11248:         }
11249:         if (!$ip) {
11250:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11251:             if (length($ip) == 4) { 
11252: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11253:             }
11254:         }
11255:         if ($ip) {
11256: 	    @hosts = get_hosts_from_ip($ip);
11257: 	    return $hosts[0];
11258:         }
11259:         return undef;
11260:     }
11261: 
11262:     sub get_internet_names {
11263:         my ($lonid) = @_;
11264:         return if ($lonid eq '');
11265:         my ($idnref,$cached)=
11266:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11267:         if ($cached) {
11268:             return $idnref;
11269:         }
11270:         my $ip = &get_host_ip($lonid);
11271:         my @hosts = &get_hosts_from_ip($ip);
11272:         my %iphost = &get_iphost();
11273:         my (@idns,%seen);
11274:         foreach my $id (@hosts) {
11275:             my $dom = &host_domain($id);
11276:             my $prim_id = &domain($dom,'primary');
11277:             my $prim_ip = &get_host_ip($prim_id);
11278:             next if ($seen{$prim_ip});
11279:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11280:                 foreach my $id (@{$iphost{$prim_ip}}) {
11281:                     my $intdom = &internet_dom($id);
11282:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11283:                         push(@idns,$intdom);
11284:                     }
11285:                 }
11286:             }
11287:             $seen{$prim_ip} = 1;
11288:         }
11289:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11290:     }
11291: 
11292: }
11293: 
11294: sub all_loncaparevs {
11295:     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);
11296: }
11297: 
11298: BEGIN {
11299: 
11300: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11301:     unless ($readit) {
11302: {
11303:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11304:     %perlvar = (%perlvar,%{$configvars});
11305: }
11306: 
11307: 
11308: # ------------------------------------------------------ Read spare server file
11309: {
11310:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11311: 
11312:     while (my $configline=<$config>) {
11313:        chomp($configline);
11314:        if ($configline) {
11315: 	   my ($host,$type) = split(':',$configline,2);
11316: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11317: 	   push(@{ $spareid{$type} }, $host);
11318:        }
11319:     }
11320:     close($config);
11321: }
11322: # ------------------------------------------------------------ Read permissions
11323: {
11324:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11325: 
11326:     while (my $configline=<$config>) {
11327: 	chomp($configline);
11328: 	if ($configline) {
11329: 	    my ($role,$perm)=split(/ /,$configline);
11330: 	    if ($perm ne '') { $pr{$role}=$perm; }
11331: 	}
11332:     }
11333:     close($config);
11334: }
11335: 
11336: # -------------------------------------------- Read plain texts for permissions
11337: {
11338:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11339: 
11340:     while (my $configline=<$config>) {
11341: 	chomp($configline);
11342: 	if ($configline) {
11343: 	    my ($short,@plain)=split(/:/,$configline);
11344:             %{$prp{$short}} = ();
11345: 	    if (@plain > 0) {
11346:                 $prp{$short}{'std'} = $plain[0];
11347:                 for (my $i=1; $i<@plain; $i++) {
11348:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11349:                 }
11350:             }
11351: 	}
11352:     }
11353:     close($config);
11354: }
11355: 
11356: # ---------------------------------------------------------- Read package table
11357: {
11358:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11359: 
11360:     while (my $configline=<$config>) {
11361: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11362: 	chomp($configline);
11363: 	my ($short,$plain)=split(/:/,$configline);
11364: 	my ($pack,$name)=split(/\&/,$short);
11365: 	if ($plain ne '') {
11366: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11367: 	    $packagetab{$short}=$plain; 
11368: 	}
11369:     }
11370:     close($config);
11371: }
11372: 
11373: # ---------------------------------------------------------- Read loncaparev table
11374: {
11375:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11376:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11377:             while (my $configline=<$config>) {
11378:                 chomp($configline);
11379:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11380:                 $loncaparevs{$hostid}=$loncaparev;
11381:             }
11382:             close($config);
11383:         }
11384:     }
11385: }
11386: 
11387: # ---------------------------------------------------------- Read serverhostID table
11388: {
11389:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11390:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11391:             while (my $configline=<$config>) {
11392:                 chomp($configline);
11393:                 my ($name,$id)=split(/:/,$configline);
11394:                 $serverhomeIDs{$name}=$id;
11395:             }
11396:             close($config);
11397:         }
11398:     }
11399: }
11400: 
11401: {
11402:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11403:     if (-e $file) {
11404:         my $parser = HTML::LCParser->new($file);
11405:         while (my $token = $parser->get_token()) {
11406:             if ($token->[0] eq 'S') {
11407:                 my $item = $token->[1];
11408:                 my $name = $token->[2]{'name'};
11409:                 my $value = $token->[2]{'value'};
11410:                 if ($item ne '' && $name ne '' && $value ne '') {
11411:                     my $release = $parser->get_text();
11412:                     $release =~ s/(^\s*|\s*$ )//gx;
11413:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11414:                 }
11415:             }
11416:         }
11417:     }
11418: }
11419: 
11420: # ---------------------------------------------------------- Read managers table
11421: {
11422:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11423:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11424:             while (my $configline=<$config>) {
11425:                 chomp($configline);
11426:                 next if ($configline =~ /^\#/);
11427:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11428:                     $managerstab{$configline} = 1;
11429:                 }
11430:             }
11431:             close($config);
11432:         }
11433:     }
11434: }
11435: 
11436: # ------------- set up temporary directory
11437: {
11438:     $tmpdir = LONCAPA::tempdir();
11439: 
11440: }
11441: 
11442: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11443: 				'compress_threshold'=> 20_000,
11444:  			        });
11445: 
11446: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11447: $dumpcount=0;
11448: $locknum=0;
11449: 
11450: &logtouch();
11451: &logthis('<font color="yellow">INFO: Read configuration</font>');
11452: $readit=1;
11453:     {
11454: 	use integer;
11455: 	my $test=(2**32)+1;
11456: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11457: 	&logthis(" Detected 64bit platform ($_64bit)");
11458:     }
11459: }
11460: }
11461: 
11462: 1;
11463: __END__
11464: 
11465: =pod
11466: 
11467: =head1 NAME
11468: 
11469: Apache::lonnet - Subroutines to ask questions about things in the network.
11470: 
11471: =head1 SYNOPSIS
11472: 
11473: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11474: 
11475:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11476: 
11477: Common parameters:
11478: 
11479: =over 4
11480: 
11481: =item *
11482: 
11483: $uname : an internal username (if $cname expecting a course Id specifically)
11484: 
11485: =item *
11486: 
11487: $udom : a domain (if $cdom expecting a course's domain specifically)
11488: 
11489: =item *
11490: 
11491: $symb : a resource instance identifier
11492: 
11493: =item *
11494: 
11495: $namespace : the name of a .db file that contains the data needed or
11496: being set.
11497: 
11498: =back
11499: 
11500: =head1 OVERVIEW
11501: 
11502: lonnet provides subroutines which interact with the
11503: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11504: about classes, users, and resources.
11505: 
11506: For many of these objects you can also use this to store data about
11507: them or modify them in various ways.
11508: 
11509: =head2 Symbs
11510: 
11511: To identify a specific instance of a resource, LON-CAPA uses symbols
11512: or "symbs"X<symb>. These identifiers are built from the URL of the
11513: map, the resource number of the resource in the map, and the URL of
11514: the resource itself. The latter is somewhat redundant, but might help
11515: if maps change.
11516: 
11517: An example is
11518: 
11519:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11520: 
11521: The respective map entry is
11522: 
11523:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11524:   title="Problem 2">
11525:  </resource>
11526: 
11527: Symbs are used by the random number generator, as well as to store and
11528: restore data specific to a certain instance of for example a problem.
11529: 
11530: =head2 Storing And Retrieving Data
11531: 
11532: X<store()>X<cstore()>X<restore()>Three of the most important functions
11533: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11534: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11535: is is the non-critical message twin of cstore. These functions are for
11536: handlers to store a perl hash to a user's permanent data space in an
11537: easy manner, and to retrieve it again on another call. It is expected
11538: that a handler would use this once at the beginning to retrieve data,
11539: and then again once at the end to send only the new data back.
11540: 
11541: The data is stored in the user's data directory on the user's
11542: homeserver under the ID of the course.
11543: 
11544: The hash that is returned by restore will have all of the previous
11545: value for all of the elements of the hash.
11546: 
11547: Example:
11548: 
11549:  #creating a hash
11550:  my %hash;
11551:  $hash{'foo'}='bar';
11552: 
11553:  #storing it
11554:  &Apache::lonnet::cstore(\%hash);
11555: 
11556:  #changing a value
11557:  $hash{'foo'}='notbar';
11558: 
11559:  #adding a new value
11560:  $hash{'bar'}='foo';
11561:  &Apache::lonnet::cstore(\%hash);
11562: 
11563:  #retrieving the hash
11564:  my %history=&Apache::lonnet::restore();
11565: 
11566:  #print the hash
11567:  foreach my $key (sort(keys(%history))) {
11568:    print("\%history{$key} = $history{$key}");
11569:  }
11570: 
11571: Will print out:
11572: 
11573:  %history{1:foo} = bar
11574:  %history{1:keys} = foo:timestamp
11575:  %history{1:timestamp} = 990455579
11576:  %history{2:bar} = foo
11577:  %history{2:foo} = notbar
11578:  %history{2:keys} = foo:bar:timestamp
11579:  %history{2:timestamp} = 990455580
11580:  %history{bar} = foo
11581:  %history{foo} = notbar
11582:  %history{timestamp} = 990455580
11583:  %history{version} = 2
11584: 
11585: Note that the special hash entries C<keys>, C<version> and
11586: C<timestamp> were added to the hash. C<version> will be equal to the
11587: total number of versions of the data that have been stored. The
11588: C<timestamp> attribute will be the UNIX time the hash was
11589: stored. C<keys> is available in every historical section to list which
11590: keys were added or changed at a specific historical revision of a
11591: hash.
11592: 
11593: B<Warning>: do not store the hash that restore returns directly. This
11594: will cause a mess since it will restore the historical keys as if the
11595: were new keys. I.E. 1:foo will become 1:1:foo etc.
11596: 
11597: Calling convention:
11598: 
11599:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11600:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11601: 
11602: For more detailed information, see lonnet specific documentation.
11603: 
11604: =head1 RETURN MESSAGES
11605: 
11606: =over 4
11607: 
11608: =item * B<con_lost>: unable to contact remote host
11609: 
11610: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11611: when the connection is brought back up
11612: 
11613: =item * B<con_failed>: unable to contact remote host and unable to save message
11614: for later delivery
11615: 
11616: =item * B<error:>: an error a occurred, a description of the error follows the :
11617: 
11618: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11619: that was requested
11620: 
11621: =back
11622: 
11623: =head1 PUBLIC SUBROUTINES
11624: 
11625: =head2 Session Environment Functions
11626: 
11627: =over 4
11628: 
11629: =item * 
11630: X<appenv()>
11631: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11632: the user envirnoment file, and will be restored for each access this
11633: user makes during this session, also modifies the %env for the current
11634: process. Optional rolesarrayref - if defined contains a reference to an array
11635: of roles which are exempt from the restriction on modifying user.role entries 
11636: in the user's environment.db and in %env.    
11637: 
11638: =item *
11639: X<delenv()>
11640: B<delenv($delthis,$regexp)>: removes all items from the session
11641: environment file that begin with $delthis. If the 
11642: optional second arg - $regexp - is true, $delthis is treated as a 
11643: regular expression, otherwise \Q$delthis\E is used. 
11644: The values are also deleted from the current processes %env.
11645: 
11646: =item * get_env_multiple($name) 
11647: 
11648: gets $name from the %env hash, it seemlessly handles the cases where multiple
11649: values may be defined and end up as an array ref.
11650: 
11651: returns an array of values
11652: 
11653: =back
11654: 
11655: =head2 User Information
11656: 
11657: =over 4
11658: 
11659: =item *
11660: X<queryauthenticate()>
11661: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11662: authentication scheme
11663: 
11664: =item *
11665: X<authenticate()>
11666: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11667: authenticate user from domain's lib servers (first use the current
11668: one). C<$upass> should be the users password.
11669: $checkdefauth is optional (value is 1 if a check should be made to
11670:    authenticate user using default authentication method, and allow
11671:    account creation if username does not have account in the domain).
11672: $clientcancheckhost is optional (value is 1 if checking whether the
11673:    server can host will occur on the client side in lonauth.pm).   
11674: 
11675: =item *
11676: X<homeserver()>
11677: B<homeserver($uname,$udom)>: find the server which has
11678: the user's directory and files (there must be only one), this caches
11679: the answer, and also caches if there is a borken connection.
11680: 
11681: =item *
11682: X<idget()>
11683: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11684: (IDs are a unique resource in a domain, there must be only 1 ID per
11685: username, and only 1 username per ID in a specific domain) (returns
11686: hash: id=>name,id=>name)
11687: 
11688: =item *
11689: X<idrget()>
11690: B<idrget($udom,@unames)>: find the IDs behind a list of
11691: usernames (returns hash: name=>id,name=>id)
11692: 
11693: =item *
11694: X<idput()>
11695: B<idput($udom,%ids)>: store away a list of names and associated IDs
11696: 
11697: =item *
11698: X<rolesinit()>
11699: B<rolesinit($udom,$username,$authhost)>: get user privileges
11700: 
11701: =item *
11702: X<getsection()>
11703: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11704: course $cname, return section name/number or '' for "not in course"
11705: and '-1' for "no section"
11706: 
11707: =item *
11708: X<userenvironment()>
11709: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11710: passed in @what from the requested user's environment, returns a hash
11711: 
11712: =item * 
11713: X<userlog_query()>
11714: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11715: activity.log file. %filters defines filters applied when parsing the
11716: log file. These can be start or end timestamps, or the type of action
11717: - log to look for Login or Logout events, check for Checkin or
11718: Checkout, role for role selection. The response is in the form
11719: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11720: escaped strings of the action recorded in the activity.log file.
11721: 
11722: =back
11723: 
11724: =head2 User Roles
11725: 
11726: =over 4
11727: 
11728: =item *
11729: 
11730: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11731:  F: full access
11732:  U,I,K: authentication modes (cxx only)
11733:  '': forbidden
11734:  1: user needs to choose course
11735:  2: browse allowed
11736:  A: passphrase authentication needed
11737: 
11738: =item *
11739: 
11740: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11741: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11742: and course level
11743: 
11744: =item *
11745: 
11746: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11747: (rolesplain.tab); plain text explanation of a user role term.
11748: $type is Course (default) or Community.
11749: If $forcedefault evaluates to true, text returned will be default 
11750: text for $type. Otherwise, if this is a course, the text returned 
11751: will be a custom name for the role (if defined in the course's 
11752: environment).  If no custom name is defined the default is returned.
11753:    
11754: =item *
11755: 
11756: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11757: All arguments are optional. Returns a hash of a roles, either for
11758: co-author/assistant author roles for a user's Construction Space
11759: (default), or if $context is 'userroles', roles for the user himself,
11760: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11761: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11762: For each key, value is set to colon-separated start and end times for
11763: the role.  If no username and domain are specified, will default to
11764: current user/domain. Types, roles, and roledoms are references to arrays
11765: of role statuses (active, future or previous), roles 
11766: (e.g., cc,in, st etc.) and domains of the roles which can be used
11767: to restrict the list of roles reported. If no array ref is 
11768: provided for types, will default to return only active roles.
11769: 
11770: =back
11771: 
11772: =head2 User Modification
11773: 
11774: =over 4
11775: 
11776: =item *
11777: 
11778: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11779: user for the level given by URL.  Optional start and end dates (leave empty
11780: string or zero for "no date")
11781: 
11782: =item *
11783: 
11784: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11785: change a users, password, possible return values are: ok,
11786: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11787: refused
11788: 
11789: =item *
11790: 
11791: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11792: 
11793: =item *
11794: 
11795: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11796:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11797: 
11798: will update user information (firstname,middlename,lastname,generation,
11799: permanentemail), and if forceid is true, student/employee ID also.
11800: A user's institutional affiliation(s) can also be updated.
11801: User information fields will not be overwritten with empty entries 
11802: unless the field is included in the $candelete array reference.
11803: This array is included when a single user is modified via "Manage Users",
11804: or when Autoupdate.pl is run by cron in a domain.
11805: 
11806: =item *
11807: 
11808: modifystudent
11809: 
11810: modify a student's enrollment and identification information.
11811: The course id is resolved based on the current users environment.  
11812: This means the envoking user must be a course coordinator or otherwise
11813: associated with a course.
11814: 
11815: This call is essentially a wrapper for lonnet::modifyuser and
11816: lonnet::modify_student_enrollment
11817: 
11818: Inputs: 
11819: 
11820: =over 4
11821: 
11822: =item B<$udom> Student's loncapa domain
11823: 
11824: =item B<$uname> Student's loncapa login name
11825: 
11826: =item B<$uid> Student/Employee ID
11827: 
11828: =item B<$umode> Student's authentication mode
11829: 
11830: =item B<$upass> Student's password
11831: 
11832: =item B<$first> Student's first name
11833: 
11834: =item B<$middle> Student's middle name
11835: 
11836: =item B<$last> Student's last name
11837: 
11838: =item B<$gene> Student's generation
11839: 
11840: =item B<$usec> Student's section in course
11841: 
11842: =item B<$end> Unix time of the roles expiration
11843: 
11844: =item B<$start> Unix time of the roles start date
11845: 
11846: =item B<$forceid> If defined, allow $uid to be changed
11847: 
11848: =item B<$desiredhome> server to use as home server for student
11849: 
11850: =item B<$email> Student's permanent e-mail address
11851: 
11852: =item B<$type> Type of enrollment (auto or manual)
11853: 
11854: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11855: 
11856: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11857: 
11858: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11859: 
11860: =item B<$context> role change context (shown in User Management Logs display in a course)
11861: 
11862: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11863: 
11864: =back
11865: 
11866: =item *
11867: 
11868: modify_student_enrollment
11869: 
11870: Change a students enrollment status in a class.  The environment variable
11871: 'role.request.course' must be defined for this function to proceed.
11872: 
11873: Inputs:
11874: 
11875: =over 4
11876: 
11877: =item $udom, students domain
11878: 
11879: =item $uname, students name
11880: 
11881: =item $uid, students user id
11882: 
11883: =item $first, students first name
11884: 
11885: =item $middle
11886: 
11887: =item $last
11888: 
11889: =item $gene
11890: 
11891: =item $usec
11892: 
11893: =item $end
11894: 
11895: =item $start
11896: 
11897: =item $type
11898: 
11899: =item $locktype
11900: 
11901: =item $cid
11902: 
11903: =item $selfenroll
11904: 
11905: =item $context
11906: 
11907: =back
11908: 
11909: 
11910: =item *
11911: 
11912: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11913: custom role; give a custom role to a user for the level given by URL.  Specify
11914: name and domain of role author, and role name
11915: 
11916: =item *
11917: 
11918: revokerole($udom,$uname,$url,$role) : revoke a role for url
11919: 
11920: =item *
11921: 
11922: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11923: 
11924: =back
11925: 
11926: =head2 Course Infomation
11927: 
11928: =over 4
11929: 
11930: =item *
11931: 
11932: coursedescription($courseid,$options) : returns a hash of information about the
11933: specified course id, including all environment settings for the
11934: course, the description of the course will be in the hash under the
11935: key 'description'
11936: 
11937: $options is an optional parameter that if supplied is a hash reference that controls
11938: what how this function works.  It has the following key/values:
11939: 
11940: =over 4
11941: 
11942: =item freshen_cache
11943: 
11944: If defined, and the environment cache for the course is valid, it is 
11945: returned in the returned hash.
11946: 
11947: =item one_time
11948: 
11949: If defined, the last cache time is set to _now_
11950: 
11951: =item user
11952: 
11953: If defined, the supplied username is used instead of the current user.
11954: 
11955: 
11956: =back
11957: 
11958: =item *
11959: 
11960: resdata($name,$domain,$type,@which) : request for current parameter
11961: setting for a specific $type, where $type is either 'course' or 'user',
11962: @what should be a list of parameters to ask about. This routine caches
11963: answers for 5 minutes.
11964: 
11965: =item *
11966: 
11967: get_courseresdata($courseid, $domain) : dump the entire course resource
11968: data base, returning a hash that is keyed by the resource name and has
11969: values that are the resource value.  I believe that the timestamps and
11970: versions are also returned.
11971: 
11972: 
11973: =back
11974: 
11975: =head2 Course Modification
11976: 
11977: =over 4
11978: 
11979: =item *
11980: 
11981: writecoursepref($courseid,%prefs) : write preferences (environment
11982: database) for a course
11983: 
11984: =item *
11985: 
11986: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11987: 
11988: =item *
11989: 
11990: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11991: 
11992: =item *
11993: 
11994: is_course($courseid), is_course($cdom, $cnum)
11995: 
11996: Accepts either a combined $courseid (in the form of domain_courseid) or the
11997: two component version $cdom, $cnum. It checks if the specified course exists.
11998: 
11999: Returns:
12000:     undef if the course doesn't exist, otherwise
12001:     in scalar context the combined courseid.
12002:     in list context the two components of the course identifier, domain and 
12003:     courseid.    
12004: 
12005: =back
12006: 
12007: =head2 Resource Subroutines
12008: 
12009: =over 4
12010: 
12011: =item *
12012: 
12013: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12014: 
12015: =item *
12016: 
12017: repcopy($filename) : subscribes to the requested file, and attempts to
12018: replicate from the owning library server, Might return
12019: 'unavailable', 'not_found', 'forbidden', 'ok', or
12020: 'bad_request', also attempts to grab the metadata for the
12021: resource. Expects the local filesystem pathname
12022: (/home/httpd/html/res/....)
12023: 
12024: =back
12025: 
12026: =head2 Resource Information
12027: 
12028: =over 4
12029: 
12030: =item *
12031: 
12032: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12033: a vairety of different possible values, $varname should be a request
12034: string, and the other parameters can be used to specify who and what
12035: one is asking about.
12036: 
12037: Possible values for $varname are environment.lastname (or other item
12038: from the envirnment hash), user.name (or someother aspect about the
12039: user), resource.0.maxtries (or some other part and parameter of a
12040: resource)
12041: 
12042: =item *
12043: 
12044: directcondval($number) : get current value of a condition; reads from a state
12045: string
12046: 
12047: =item *
12048: 
12049: condval($condidx) : value of condition index based on state
12050: 
12051: =item *
12052: 
12053: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12054: resource's metadata, $what should be either a specific key, or either
12055: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12056: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12057: 
12058: this function automatically caches all requests
12059: 
12060: =item *
12061: 
12062: metadata_query($query,$custom,$customshow) : make a metadata query against the
12063: network of library servers; returns file handle of where SQL and regex results
12064: will be stored for query
12065: 
12066: =item *
12067: 
12068: symbread($filename) : return symbolic list entry (filename argument optional);
12069: returns the data handle
12070: 
12071: =item *
12072: 
12073: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12074: a possible symb for the URL in $thisfn, and if is an encryypted
12075: resource that the user accessed using /enc/ returns a 1 on success, 0
12076: on failure, user must be in a course, as it assumes the existance of
12077: the course initial hash, and uses $env('request.course.id'}
12078: 
12079: 
12080: =item *
12081: 
12082: symbclean($symb) : removes versions numbers from a symb, returns the
12083: cleaned symb
12084: 
12085: =item *
12086: 
12087: is_on_map($uri) : checks if the $uri is somewhere on the current
12088: course map, user must be in a course for it to work.
12089: 
12090: =item *
12091: 
12092: numval($salt) : return random seed value (addend for rndseed)
12093: 
12094: =item *
12095: 
12096: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12097: a random seed, all arguments are optional, if they aren't sent it uses the
12098: environment to derive them. Note: if symb isn't sent and it can't get one
12099: from &symbread it will use the current time as its return value
12100: 
12101: =item *
12102: 
12103: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12104: unfakeable, receipt
12105: 
12106: =item *
12107: 
12108: receipt() : API to ireceipt working off of env values; given out to users
12109: 
12110: =item *
12111: 
12112: countacc($url) : count the number of accesses to a given URL
12113: 
12114: =item *
12115: 
12116: 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
12117: 
12118: =item *
12119: 
12120: 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)
12121: 
12122: =item *
12123: 
12124: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12125: 
12126: =item *
12127: 
12128: devalidate($symb) : devalidate temporary spreadsheet calculations,
12129: forcing spreadsheet to reevaluate the resource scores next time.
12130: 
12131: =back
12132: 
12133: =head2 Storing/Retreiving Data
12134: 
12135: =over 4
12136: 
12137: =item *
12138: 
12139: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12140: for this url; hashref needs to be given and should be a \%hashname; the
12141: remaining args aren't required and if they aren't passed or are '' they will
12142: be derived from the env
12143: 
12144: =item *
12145: 
12146: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12147: uses critical subroutine
12148: 
12149: =item *
12150: 
12151: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12152: all args are optional
12153: 
12154: =item *
12155: 
12156: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12157: dumps the complete (or key matching regexp) namespace into a hash
12158: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12159: normally &store()ed into
12160: 
12161: $range should be either an integer '100' (give me the first 100
12162:                                            matching records)
12163:               or be  two integers sperated by a - with no spaces
12164:                  '30-50' (give me the 30th through the 50th matching
12165:                           records)
12166: 
12167: 
12168: =item *
12169: 
12170: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12171: replaces a &store() version of data with a replacement set of data
12172: for a particular resource in a namespace passed in the $storehash hash 
12173: reference
12174: 
12175: =item *
12176: 
12177: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12178: works very similar to store/cstore, but all data is stored in a
12179: temporary location and can be reset using tmpreset, $storehash should
12180: be a hash reference, returns nothing on success
12181: 
12182: =item *
12183: 
12184: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12185: similar to restore, but all data is stored in a temporary location and
12186: can be reset using tmpreset. Returns a hash of values on success,
12187: error string otherwise.
12188: 
12189: =item *
12190: 
12191: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12192: deltes all keys for $symb form the temporary storage hash.
12193: 
12194: =item *
12195: 
12196: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12197: reference filled in from namesp ($udom and $uname are optional)
12198: 
12199: =item *
12200: 
12201: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12202: namesp ($udom and $uname are optional)
12203: 
12204: =item *
12205: 
12206: dump($namespace,$udom,$uname,$regexp,$range) : 
12207: dumps the complete (or key matching regexp) namespace into a hash
12208: ($udom, $uname, $regexp, $range are optional)
12209: 
12210: $range should be either an integer '100' (give me the first 100
12211:                                            matching records)
12212:               or be  two integers sperated by a - with no spaces
12213:                  '30-50' (give me the 30th through the 50th matching
12214:                           records)
12215: =item *
12216: 
12217: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12218: $store can be a scalar, an array reference, or if the amount to be 
12219: incremented is > 1, a hash reference.
12220: 
12221: ($udom and $uname are optional)
12222: 
12223: =item *
12224: 
12225: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12226: ($udom and $uname are optional)
12227: 
12228: =item *
12229: 
12230: cput($namespace,$storehash,$udom,$uname) : critical put
12231: ($udom and $uname are optional)
12232: 
12233: =item *
12234: 
12235: newput($namespace,$storehash,$udom,$uname) :
12236: 
12237: Attempts to store the items in the $storehash, but only if they don't
12238: currently exist, if this succeeds you can be certain that you have 
12239: successfully created a new key value pair in the $namespace db.
12240: 
12241: 
12242: Args:
12243:  $namespace: name of database to store values to
12244:  $storehash: hashref to store to the db
12245:  $udom: (optional) domain of user containing the db
12246:  $uname: (optional) name of user caontaining the db
12247: 
12248: Returns:
12249:  'ok' -> succeeded in storing all keys of $storehash
12250:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12251:                         least <key> already existed in the db (other
12252:                         requested keys may also already exist)
12253:  'error: <msg>' -> unable to tie the DB or other error occurred
12254:  'con_lost' -> unable to contact request server
12255:  'refused' -> action was not allowed by remote machine
12256: 
12257: 
12258: =item *
12259: 
12260: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12261: reference filled in from namesp (encrypts the return communication)
12262: ($udom and $uname are optional)
12263: 
12264: =item *
12265: 
12266: log($udom,$name,$home,$message) : write to permanent log for user; use
12267: critical subroutine
12268: 
12269: =item *
12270: 
12271: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12272: array reference filled in from namespace found in domain level on either
12273: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12274: 
12275: =item *
12276: 
12277: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12278: domain level either on specified domain server ($uhome) or primary domain 
12279: server ($udom and $uhome are optional)
12280: 
12281: =item * 
12282: 
12283: get_domain_defaults($target_domain) : returns hash with defaults for
12284: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12285: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12286: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12287: Values are retrieved from cache (if current), or from domain's configuration.db
12288: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12289: or lonTabs/domain.tab. 
12290: 
12291: %domdefaults = &get_auth_defaults($target_domain);
12292: 
12293: =back
12294: 
12295: =head2 Network Status Functions
12296: 
12297: =over 4
12298: 
12299: =item *
12300: 
12301: dirlist() : return directory list based on URI (first arg).
12302: 
12303: Inputs: 1 required, 5 optional.
12304: 
12305: =over
12306: 
12307: =item 
12308: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12309: 
12310: =item
12311: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12312: 
12313: =item
12314: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12315: 
12316: =item
12317: $getpropath - boolean: 1 if prepend path using &propath(). 
12318: 
12319: =item
12320: $getuserdir - boolean: 1 if prepend path for "userfiles".
12321: 
12322: =item 
12323: $alternateRoot - path to prepend in place of path from $uri.
12324: 
12325: =back
12326: 
12327: Returns: Array of up to two items.
12328: 
12329: =over
12330: 
12331: a reference to an array of files/subdirectories
12332: 
12333: =over
12334: 
12335: Each element in the array of files/subdirectories is a & separated list of
12336: item name and the result of running stat on the item.  If dirlist was requested
12337: for a file instead of a directory, the item name will be ''. For a directory 
12338: listing, if the item is a metadata file, the element will end &N&M 
12339: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12340: default copyright set (1).  
12341: 
12342: =back
12343: 
12344: a scalar containing error condition (if encountered).
12345: 
12346: =over
12347: 
12348: =item 
12349: no_host (no homeserver identified for $username:$domain).
12350: 
12351: =item 
12352: no_such_host (server contacted for listing not identified as valid host).
12353: 
12354: =item 
12355: con_lost (connection to remote server failed).
12356: 
12357: =item 
12358: refused (invalid $username:$domain received on lond side).
12359: 
12360: =item 
12361: no_such_dir (directory at specified path on lond side does not exist). 
12362: 
12363: =item 
12364: empty (directory at specified path on lond side is empty).
12365: 
12366: =over
12367: 
12368: This is currently not encountered because the &ls3, &ls2, 
12369: &ls (_handler) routines on the lond side do not filter out
12370: . and .. from a directory listing. 
12371: 
12372: =back
12373: 
12374: =back
12375: 
12376: =back
12377: 
12378: =item *
12379: 
12380: spareserver() : find server with least workload from spare.tab
12381: 
12382: 
12383: =item *
12384: 
12385: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12386: if there is no corresponding loncapa host.
12387: 
12388: =back
12389: 
12390: 
12391: =head2 Apache Request
12392: 
12393: =over 4
12394: 
12395: =item *
12396: 
12397: ssi($url,%hash) : server side include, does a complete request cycle on url to
12398: localhost, posts hash
12399: 
12400: =back
12401: 
12402: =head2 Data to String to Data
12403: 
12404: =over 4
12405: 
12406: =item *
12407: 
12408: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12409: and '&' separators, supports elements that are arrayrefs and hashrefs
12410: 
12411: =item *
12412: 
12413: hashref2str($hashref) : convert a hashref into a string complete with
12414: escaping and '=' and '&' separators, supports elements that are
12415: arrayrefs and hashrefs
12416: 
12417: =item *
12418: 
12419: arrayref2str($arrayref) : convert an arrayref into a string complete
12420: with escaping and '&' separators, supports elements that are arrayrefs
12421: and hashrefs
12422: 
12423: =item *
12424: 
12425: str2hash($string) : convert string to hash using unescaping and
12426: splitting on '=' and '&', supports elements that are arrayrefs and
12427: hashrefs
12428: 
12429: =item *
12430: 
12431: str2array($string) : convert string to hash using unescaping and
12432: splitting on '&', supports elements that are arrayrefs and hashrefs
12433: 
12434: =back
12435: 
12436: =head2 Logging Routines
12437: 
12438: 
12439: These routines allow one to make log messages in the lonnet.log and
12440: lonnet.perm logfiles.
12441: 
12442: =over 4
12443: 
12444: =item *
12445: 
12446: logtouch() : make sure the logfile, lonnet.log, exists
12447: 
12448: =item *
12449: 
12450: logthis() : append message to the normal lonnet.log file, it gets
12451: preiodically rolled over and deleted.
12452: 
12453: =item *
12454: 
12455: logperm() : append a permanent message to lonnet.perm.log, this log
12456: file never gets deleted by any automated portion of the system, only
12457: messages of critical importance should go in here.
12458: 
12459: 
12460: =back
12461: 
12462: =head2 General File Helper Routines
12463: 
12464: =over 4
12465: 
12466: =item *
12467: 
12468: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12469: (a) files in /uploaded
12470:   (i) If a local copy of the file exists - 
12471:       compares modification date of local copy with last-modified date for 
12472:       definitive version stored on home server for course. If local copy is 
12473:       stale, requests a new version from the home server and stores it. 
12474:       If the original has been removed from the home server, then local copy 
12475:       is unlinked.
12476:   (ii) If local copy does not exist -
12477:       requests the file from the home server and stores it. 
12478:   
12479:   If $caller is 'uploadrep':  
12480:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12481:     for request for files originally uploaded via DOCS. 
12482:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12483:   
12484:   Otherwise:
12485:      This indicates a call from the content generation phase of the request.
12486:      -  returns the entire contents of the file or -1.
12487:      
12488: (b) files in /res
12489:    - returns the entire contents of a file or -1; 
12490:    it properly subscribes to and replicates the file if neccessary.
12491: 
12492: 
12493: =item *
12494: 
12495: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12496:                   reference
12497: 
12498: returns either a stat() list of data about the file or an empty list
12499: if the file doesn't exist or couldn't find out about it (connection
12500: problems or user unknown)
12501: 
12502: =item *
12503: 
12504: filelocation($dir,$file) : returns file system location of a file
12505: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12506: directory that relative $file lookups are to looked in ($dir of /a/dir
12507: and a file of ../bob will become /a/bob)
12508: 
12509: =item *
12510: 
12511: hreflocation($dir,$file) : returns file system location or a URL; same as
12512: filelocation except for hrefs
12513: 
12514: =item *
12515: 
12516: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12517: 
12518: =back
12519: 
12520: =head2 Usererfile file routines (/uploaded*)
12521: 
12522: =over 4
12523: 
12524: =item *
12525: 
12526: userfileupload(): main rotine for putting a file in a user or course's
12527:                   filespace, arguments are,
12528: 
12529:  formname - required - this is the name of the element in $env where the
12530:            filename, and the contents of the file to create/modifed exist
12531:            the filename is in $env{'form.'.$formname.'.filename'} and the
12532:            contents of the file is located in $env{'form.'.$formname}
12533:  context - if coursedoc, store the file in the course of the active role
12534:              of the current user; 
12535:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12536:            if 'canceloverwrite': delete file in tmp/overwrites directory
12537:  subdir - required - subdirectory to put the file in under ../userfiles/
12538:          if undefined, it will be placed in "unknown"
12539: 
12540:  (This routine calls clean_filename() to remove any dangerous
12541:  characters from the filename, and then calls finuserfileupload() to
12542:  complete the transaction)
12543: 
12544:  returns either the url of the uploaded file (/uploaded/....) if successful
12545:  and /adm/notfound.html if unsuccessful
12546: 
12547: =item *
12548: 
12549: clean_filename(): routine for cleaing a filename up for storage in
12550:                  userfile space, argument is:
12551: 
12552:  filename - proposed filename
12553: 
12554: returns: the new clean filename
12555: 
12556: =item *
12557: 
12558: finishuserfileupload(): routine that creates and sends the file to
12559: userspace, probably shouldn't be called directly
12560: 
12561:   docuname: username or courseid of destination for the file
12562:   docudom: domain of user/course of destination for the file
12563:   formname: same as for userfileupload()
12564:   fname: filename (including subdirectories) for the file
12565:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12566:   allfiles: reference to hash used to store objects found by parser
12567:   codebase: reference to hash used for codebases of java objects found by parser
12568:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12569:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12570:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12571:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12572:   context: if 'overwrite', will move the uploaded file from its temporary location to
12573:             userfiles to facilitate overwriting a previously uploaded file with same name.
12574:   mimetype: reference to scalar to accommodate mime type determined
12575:             from File::MMagic if $parser = parse.
12576: 
12577:  returns either the url of the uploaded file (/uploaded/....) if successful
12578:  and /adm/notfound.html if unsuccessful (or an error message if context 
12579:  was 'overwrite').
12580:  
12581: 
12582: =item *
12583: 
12584: renameuserfile(): renames an existing userfile to a new name
12585: 
12586:   Args:
12587:    docuname: username or courseid of destination for the file
12588:    docudom: domain of user/course of destination for the file
12589:    old: current file name (including any subdirs under userfiles)
12590:    new: desired file name (including any subdirs under userfiles)
12591: 
12592: =item *
12593: 
12594: mkdiruserfile(): creates a directory is a userfiles dir
12595: 
12596:   Args:
12597:    docuname: username or courseid of destination for the file
12598:    docudom: domain of user/course of destination for the file
12599:    dir: dir to create (including any subdirs under userfiles)
12600: 
12601: =item *
12602: 
12603: removeuserfile(): removes a file that exists in userfiles
12604: 
12605:   Args:
12606:    docuname: username or courseid of destination for the file
12607:    docudom: domain of user/course of destination for the file
12608:    fname: filname to delete (including any subdirs under userfiles)
12609: 
12610: =item *
12611: 
12612: removeuploadedurl(): convience function for removeuserfile()
12613: 
12614:   Args:
12615:    url:  a full /uploaded/... url to delete
12616: 
12617: =item * 
12618: 
12619: get_portfile_permissions():
12620:   Args:
12621:     domain: domain of user or course contain the portfolio files
12622:     user: name of user or num of course contain the portfolio files
12623:   Returns:
12624:     hashref of a dump of the proper file_permissions.db
12625:    
12626: 
12627: =item * 
12628: 
12629: get_access_controls():
12630: 
12631: Args:
12632:   current_permissions: the hash ref returned from get_portfile_permissions()
12633:   group: (optional) the group you want the files associated with
12634:   file: (optional) the file you want access info on
12635: 
12636: Returns:
12637:     a hash (keys are file names) of hashes containing
12638:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12639:         values are XML containing access control settings (see below) 
12640: 
12641: Internal notes:
12642: 
12643:  access controls are stored in file_permissions.db as key=value pairs.
12644:     key -> path to file/file_name\0uniqueID:scope_end_start
12645:         where scope -> public,guest,course,group,domains or users.
12646:               end -> UNIX time for end of access (0 -> no end date)
12647:               start -> UNIX time for start of access
12648: 
12649:     value -> XML description of access control
12650:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12651:             <start></start>
12652:             <end></end>
12653: 
12654:             <password></password>  for scope type = guest
12655: 
12656:             <domain></domain>     for scope type = course or group
12657:             <number></number>
12658:             <roles id="">
12659:              <role></role>
12660:              <access></access>
12661:              <section></section>
12662:              <group></group>
12663:             </roles>
12664: 
12665:             <dom></dom>         for scope type = domains
12666: 
12667:             <users>             for scope type = users
12668:              <user>
12669:               <uname></uname>
12670:               <udom></udom>
12671:              </user>
12672:             </users>
12673:            </scope> 
12674:               
12675:  Access data is also aggregated for each file in an additional key=value pair:
12676:  key -> path to file/file_name\0accesscontrol 
12677:  value -> reference to hash
12678:           hash contains key = value pairs
12679:           where key = uniqueID:scope_end_start
12680:                 value = UNIX time record was last updated
12681: 
12682:           Used to improve speed of look-ups of access controls for each file.  
12683:  
12684:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12685: 
12686: modify_access_controls():
12687: 
12688: Modifies access controls for a portfolio file
12689: Args
12690: 1. file name
12691: 2. reference to hash of required changes,
12692: 3. domain
12693: 4. username
12694:   where domain,username are the domain of the portfolio owner 
12695:   (either a user or a course) 
12696: 
12697: Returns:
12698: 1. result of additions or updates ('ok' or 'error', with error message). 
12699: 2. result of deletions ('ok' or 'error', with error message).
12700: 3. reference to hash of any new or updated access controls.
12701: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12702:    key = integer (inbound ID)
12703:    value = uniqueID  
12704: 
12705: =back
12706: 
12707: =head2 HTTP Helper Routines
12708: 
12709: =over 4
12710: 
12711: =item *
12712: 
12713: escape() : unpack non-word characters into CGI-compatible hex codes
12714: 
12715: =item *
12716: 
12717: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12718: 
12719: =back
12720: 
12721: =head1 PRIVATE SUBROUTINES
12722: 
12723: =head2 Underlying communication routines (Shouldn't call)
12724: 
12725: =over 4
12726: 
12727: =item *
12728: 
12729: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12730: 
12731: =item *
12732: 
12733: reply() : uses subreply to send a message to remote machine, logs all failures
12734: 
12735: =item *
12736: 
12737: critical() : passes a critical message to another server; if cannot
12738: get through then place message in connection buffer directory and
12739: returns con_delayed, if incapable of saving message, returns
12740: con_failed
12741: 
12742: =item *
12743: 
12744: reconlonc() : tries to reconnect lonc client processes.
12745: 
12746: =back
12747: 
12748: =head2 Resource Access Logging
12749: 
12750: =over 4
12751: 
12752: =item *
12753: 
12754: flushcourselogs() : flush (save) buffer logs and access logs
12755: 
12756: =item *
12757: 
12758: courselog($what) : save message for course in hash
12759: 
12760: =item *
12761: 
12762: courseacclog($what) : save message for course using &courselog().  Perform
12763: special processing for specific resource types (problems, exams, quizzes, etc).
12764: 
12765: =item *
12766: 
12767: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12768: as a PerlChildExitHandler
12769: 
12770: =back
12771: 
12772: =head2 Other
12773: 
12774: =over 4
12775: 
12776: =item *
12777: 
12778: symblist($mapname,%newhash) : update symbolic storage links
12779: 
12780: =back
12781: 
12782: =cut
12783: 

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