File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1173: download - view: text, annotated - select for diffs
Mon May 28 12:23:03 2012 UTC (12 years, 2 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
BZ 5945 - Need to explicitly define the return from ssi HTTP::Request to be
utf8 via Encode::decode_utf8  ...many thanks to  gooogle:
http://ahinea.com/en/tech/perl-unicode-struggle.html specifically.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1173 2012/05/28 12:23:03 foxr 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 Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: 
  104: use File::Copy;
  105: 
  106: my $readit;
  107: my $max_connection_retries = 10;     # Or some such value.
  108: 
  109: require Exporter;
  110: 
  111: our @ISA = qw (Exporter);
  112: our @EXPORT = qw(%env);
  113: 
  114: 
  115: # --------------------------------------------------------------------- Logging
  116: {
  117:     my $logid;
  118:     sub instructor_log {
  119: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  120:         if (($cnum eq '') || ($cdom eq '')) {
  121:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  122:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  123:         }
  124: 	$logid++;
  125:         my $now = time();
  126: 	my $id=$now.'00000'.$$.'00000'.$logid;
  127: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  128: 				    { $id => {
  129: 					'exe_uname' => $env{'user.name'},
  130: 					'exe_udom'  => $env{'user.domain'},
  131: 					'exe_time'  => $now,
  132: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  133: 					'delflag'   => $delflag,
  134: 					'logentry'  => $storehash,
  135: 					'uname'     => $uname,
  136: 					'udom'      => $udom,
  137: 				    }
  138: 				  },$cdom,$cnum);
  139:     }
  140: }
  141: 
  142: sub logtouch {
  143:     my $execdir=$perlvar{'lonDaemons'};
  144:     unless (-e "$execdir/logs/lonnet.log") {	
  145: 	open(my $fh,">>$execdir/logs/lonnet.log");
  146: 	close $fh;
  147:     }
  148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  150: }
  151: 
  152: sub logthis {
  153:     my $message=shift;
  154:     my $execdir=$perlvar{'lonDaemons'};
  155:     my $now=time;
  156:     my $local=localtime($now);
  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  159: 	print $fh $logstring;
  160: 	close($fh);
  161:     }
  162:     return 1;
  163: }
  164: 
  165: sub logperm {
  166:     my $message=shift;
  167:     my $execdir=$perlvar{'lonDaemons'};
  168:     my $now=time;
  169:     my $local=localtime($now);
  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  171: 	print $fh "$now:$message:$local\n";
  172: 	close($fh);
  173:     }
  174:     return 1;
  175: }
  176: 
  177: sub create_connection {
  178:     my ($hostname,$lonid) = @_;
  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  180: 				     Type    => SOCK_STREAM,
  181: 				     Timeout => 10);
  182:     return 0 if (!$client);
  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  184:     my $result = <$client>;
  185:     chomp($result);
  186:     return 1 if ($result eq 'done');
  187:     return 0;
  188: }
  189: 
  190: sub get_server_timezone {
  191:     my ($cnum,$cdom) = @_;
  192:     my $home=&homeserver($cnum,$cdom);
  193:     if ($home ne 'no_host') {
  194:         my $cachetime = 24*3600;
  195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  196:         if (defined($cached)) {
  197:             return $timezone;
  198:         } else {
  199:             my $timezone = &reply('servertimezone',$home);
  200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  201:         }
  202:     }
  203: }
  204: 
  205: sub get_server_distarch {
  206:     my ($lonhost,$ignore_cache) = @_;
  207:     if (defined($lonhost)) {
  208:         if (!defined(&hostname($lonhost))) {
  209:             return;
  210:         }
  211:         my $cachetime = 12*3600;
  212:         if (!$ignore_cache) {
  213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  214:             if (defined($cached)) {
  215:                 return $distarch;
  216:             }
  217:         }
  218:         my $rep = &reply('serverdistarch',$lonhost);
  219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  221:                 $rep eq '') {
  222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  223:         }
  224:     }
  225:     return;
  226: }
  227: 
  228: sub get_server_loncaparev {
  229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  230:     if (defined($lonhost)) {
  231:         if (!defined(&hostname($lonhost))) {
  232:             undef($lonhost);
  233:         }
  234:     }
  235:     if (!defined($lonhost)) {
  236:         if (defined(&domain($dom,'primary'))) {
  237:             $lonhost=&domain($dom,'primary');
  238:             if ($lonhost eq 'no_host') {
  239:                 undef($lonhost);
  240:             }
  241:         }
  242:     }
  243:     if (defined($lonhost)) {
  244:         my $cachetime = 12*3600;
  245:         if (!$ignore_cache) {
  246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  247:             if (defined($cached)) {
  248:                 return $loncaparev;
  249:             }
  250:         }
  251:         my ($answer,$loncaparev);
  252:         my @ids=&current_machine_ids();
  253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  254:             $answer = $perlvar{'lonVersion'};
  255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  256:                 $loncaparev = $1;
  257:             }
  258:         } else {
  259:             $answer = &reply('serverloncaparev',$lonhost);
  260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  261:                 if ($caller eq 'loncron') {
  262:                     my $ua=new LWP::UserAgent;
  263:                     $ua->timeout(4);
  264:                     my $protocol = $protocol{$lonhost};
  265:                     $protocol = 'http' if ($protocol ne 'https');
  266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  267:                     my $request=new HTTP::Request('GET',$url);
  268:                     my $response=$ua->request($request);
  269:                     unless ($response->is_error()) {
  270:                         my $content = $response->content;
  271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  272:                             $loncaparev = $1;
  273:                         }
  274:                     }
  275:                 } else {
  276:                     $loncaparev = $loncaparevs{$lonhost};
  277:                 }
  278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  279:                 $loncaparev = $1;
  280:             }
  281:         }
  282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  283:     }
  284: }
  285: 
  286: sub get_server_homeID {
  287:     my ($hostname,$ignore_cache,$caller) = @_;
  288:     unless ($ignore_cache) {
  289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  290:         if (defined($cached)) {
  291:             return $serverhomeID;
  292:         }
  293:     }
  294:     my $cachetime = 12*3600;
  295:     my $serverhomeID;
  296:     if ($caller eq 'loncron') { 
  297:         my @machine_ids = &machine_ids($hostname);
  298:         foreach my $id (@machine_ids) {
  299:             my $response = &reply('serverhomeID',$id);
  300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  301:                 $serverhomeID = $response;
  302:                 last;
  303:             }
  304:         }
  305:         if ($serverhomeID eq '') {
  306:             $serverhomeID = $machine_ids[-1];
  307:         }
  308:     } else {
  309:         $serverhomeID = $serverhomeIDs{$hostname};
  310:     }
  311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  312: }
  313: 
  314: sub get_remote_globals {
  315:     my ($lonhost,$whathash,$ignore_cache) = @_;
  316:     my ($result,%returnhash,%whatneeded);
  317:     if (ref($whathash) eq 'HASH') {
  318:         foreach my $what (sort(keys(%{$whathash}))) {
  319:             my $hashid = $lonhost.'-'.$what;
  320:             my ($response,$cached);
  321:             unless ($ignore_cache) {
  322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  323:             }
  324:             if (defined($cached)) {
  325:                 $returnhash{$what} = $response;
  326:             } else {
  327:                 $whatneeded{$what} = 1;
  328:             }
  329:         }
  330:         if (keys(%whatneeded) == 0) {
  331:             $result = 'ok';
  332:         } else {
  333:             my $requested = &freeze_escape(\%whatneeded);
  334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  336:                 ($rep eq 'unknown_cmd')) {
  337:                 $result = $rep;
  338:             } else {
  339:                 $result = 'ok';
  340:                 my @pairs=split(/\&/,$rep);
  341:                 foreach my $item (@pairs) {
  342:                     my ($key,$value)=split(/=/,$item,2);
  343:                     my $what = &unescape($key);
  344:                     my $hashid = $lonhost.'-'.$what;
  345:                     $returnhash{$what}=&thaw_unescape($value);
  346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  347:                 }
  348:             }
  349:         }
  350:     }
  351:     return ($result,\%returnhash);
  352: }
  353: 
  354: sub remote_devalidate_cache {
  355:     my ($lonhost,$name,$id) = @_;
  356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  357:     return $response;
  358: }
  359: 
  360: # -------------------------------------------------- Non-critical communication
  361: sub subreply {
  362:     my ($cmd,$server)=@_;
  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  364:     #
  365:     #  With loncnew process trimming, there's a timing hole between lonc server
  366:     #  process exit and the master server picking up the listen on the AF_UNIX
  367:     #  socket.  In that time interval, a lock file will exist:
  368: 
  369:     my $lockfile=$peerfile.".lock";
  370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  371: 	sleep(1);
  372:     }
  373:     # At this point, either a loncnew parent is listening or an old lonc
  374:     # or loncnew child is listening so we can connect or everything's dead.
  375:     #
  376:     #   We'll give the connection a few tries before abandoning it.  If
  377:     #   connection is not possible, we'll con_lost back to the client.
  378:     #   
  379:     my $client;
  380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  382: 				      Type    => SOCK_STREAM,
  383: 				      Timeout => 10);
  384: 	if ($client) {
  385: 	    last;		# Connected!
  386: 	} else {
  387: 	    &create_connection(&hostname($server),$server);
  388: 	}
  389:         sleep(1);		# Try again later if failed connection.
  390:     }
  391:     my $answer;
  392:     if ($client) {
  393: 	print $client "sethost:$server:$cmd\n";
  394: 	$answer=<$client>;
  395: 	if (!$answer) { $answer="con_lost"; }
  396: 	chomp($answer);
  397:     } else {
  398: 	$answer = 'con_lost';	# Failed connection.
  399:     }
  400:     return $answer;
  401: }
  402: 
  403: sub reply {
  404:     my ($cmd,$server)=@_;
  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  406:     my $answer=subreply($cmd,$server);
  407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  408:        &logthis("<font color=\"blue\">WARNING:".
  409:                 " $cmd to $server returned $answer</font>");
  410:     }
  411:     return $answer;
  412: }
  413: 
  414: # ----------------------------------------------------------- Send USR1 to lonc
  415: 
  416: sub reconlonc {
  417:     my ($lonid) = @_;
  418:     my $hostname = &hostname($lonid);
  419:     if ($lonid) {
  420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  421: 	if ($hostname && -e $peerfile) {
  422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  424: 					     Type    => SOCK_STREAM,
  425: 					     Timeout => 10);
  426: 	    if ($client) {
  427: 		print $client ("reset_retries\n");
  428: 		my $answer=<$client>;
  429: 		#reset just this one.
  430: 	    }
  431: 	}
  432: 	return;
  433:     }
  434: 
  435:     &logthis("Trying to reconnect lonc");
  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  437:     if (open(my $fh,"<$loncfile")) {
  438: 	my $loncpid=<$fh>;
  439:         chomp($loncpid);
  440:         if (kill 0 => $loncpid) {
  441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  442:             kill USR1 => $loncpid;
  443:             sleep 1;
  444:          } else {
  445: 	    &logthis(
  446:                "<font color=\"blue\">WARNING:".
  447:                " lonc at pid $loncpid not responding, giving up</font>");
  448:         }
  449:     } else {
  450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  451:     }
  452: }
  453: 
  454: # ------------------------------------------------------ Critical communication
  455: 
  456: sub critical {
  457:     my ($cmd,$server)=@_;
  458:     unless (&hostname($server)) {
  459:         &logthis("<font color=\"blue\">WARNING:".
  460:                " Critical message to unknown server ($server)</font>");
  461:         return 'no_such_host';
  462:     }
  463:     my $answer=reply($cmd,$server);
  464:     if ($answer eq 'con_lost') {
  465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  466: 	my $answer=reply($cmd,$server);
  467:         if ($answer eq 'con_lost') {
  468:             my $now=time;
  469:             my $middlename=$cmd;
  470:             $middlename=substr($middlename,0,16);
  471:             $middlename=~s/\W//g;
  472:             my $dfilename=
  473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  474:             $dumpcount++;
  475:             {
  476: 		my $dfh;
  477: 		if (open($dfh,">$dfilename")) {
  478: 		    print $dfh "$cmd\n"; 
  479: 		    close($dfh);
  480: 		}
  481:             }
  482:             sleep 2;
  483:             my $wcmd='';
  484:             {
  485: 		my $dfh;
  486: 		if (open($dfh,"<$dfilename")) {
  487: 		    $wcmd=<$dfh>; 
  488: 		    close($dfh);
  489: 		}
  490:             }
  491:             chomp($wcmd);
  492:             if ($wcmd eq $cmd) {
  493: 		&logthis("<font color=\"blue\">WARNING: ".
  494:                          "Connection buffer $dfilename: $cmd</font>");
  495:                 &logperm("D:$server:$cmd");
  496: 	        return 'con_delayed';
  497:             } else {
  498:                 &logthis("<font color=\"red\">CRITICAL:"
  499:                         ." Critical connection failed: $server $cmd</font>");
  500:                 &logperm("F:$server:$cmd");
  501:                 return 'con_failed';
  502:             }
  503:         }
  504:     }
  505:     return $answer;
  506: }
  507: 
  508: # ------------------------------------------- check if return value is an error
  509: 
  510: sub error {
  511:     my ($result) = @_;
  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  513: 	if ($2 == 2) { return undef; }
  514: 	return $1;
  515:     }
  516:     return undef;
  517: }
  518: 
  519: sub convert_and_load_session_env {
  520:     my ($lonidsdir,$handle)=@_;
  521:     my @profile;
  522:     {
  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  524: 	if (!$opened) {
  525: 	    return 0;
  526: 	}
  527: 	flock($idf,LOCK_SH);
  528: 	@profile=<$idf>;
  529: 	close($idf);
  530:     }
  531:     my %temp_env;
  532:     foreach my $line (@profile) {
  533: 	if ($line !~ m/=/) {
  534: 	    return 0;
  535: 	}
  536: 	chomp($line);
  537: 	my ($envname,$envvalue)=split(/=/,$line,2);
  538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  539:     }
  540:     unlink("$lonidsdir/$handle.id");
  541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  542: 	    0640)) {
  543: 	%disk_env = %temp_env;
  544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  545: 	untie(%disk_env);
  546:     }
  547:     return 1;
  548: }
  549: 
  550: # ------------------------------------------- Transfer profile into environment
  551: my $env_loaded;
  552: sub transfer_profile_to_env {
  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
  554:     if (!$force_transfer && $env_loaded) { return; } 
  555: 
  556:     if (!defined($lonidsdir)) {
  557: 	$lonidsdir = $perlvar{'lonIDsDir'};
  558:     }
  559:     if (!defined($handle)) {
  560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  561:     }
  562: 
  563:     my $convert;
  564:     {
  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  566: 	if (!$opened) {
  567: 	    return;
  568: 	}
  569: 	flock($idf,LOCK_SH);
  570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  571: 		&GDBM_READER(),0640)) {
  572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  573: 	    untie(%disk_env);
  574: 	} else {
  575: 	    $convert = 1;
  576: 	}
  577:     }
  578:     if ($convert) {
  579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  580: 	    &logthis("Failed to load session, or convert session.");
  581: 	}
  582:     }
  583: 
  584:     my %remove;
  585:     while ( my $envname = each(%env) ) {
  586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  587:             if ($time < time-300) {
  588:                 $remove{$key}++;
  589:             }
  590:         }
  591:     }
  592: 
  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  594:     $env_loaded=1;
  595:     foreach my $expired_key (keys(%remove)) {
  596:         &delenv($expired_key);
  597:     }
  598: }
  599: 
  600: # ---------------------------------------------------- Check for valid session 
  601: sub check_for_valid_session {
  602:     my ($r,$name) = @_;
  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  604:     if ($name eq '') {
  605:         $name = 'lonID';
  606:     }
  607:     my $lonid=$cookies{$name};
  608:     return undef if (!$lonid);
  609: 
  610:     my $handle=&LONCAPA::clean_handle($lonid->value);
  611:     my $lonidsdir;
  612:     if ($name eq 'lonDAV') {
  613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  614:     } else {
  615:         $lonidsdir=$r->dir_config('lonIDsDir');
  616:     }
  617:     return undef if (!-e "$lonidsdir/$handle.id");
  618: 
  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  620:     return undef if (!$opened);
  621: 
  622:     flock($idf,LOCK_SH);
  623:     my %disk_env;
  624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  625: 	    &GDBM_READER(),0640)) {
  626: 	return undef;	
  627:     }
  628: 
  629:     if (!defined($disk_env{'user.name'})
  630: 	|| !defined($disk_env{'user.domain'})) {
  631: 	return undef;
  632:     }
  633:     return $handle;
  634: }
  635: 
  636: sub timed_flock {
  637:     my ($file,$lock_type) = @_;
  638:     my $failed=0;
  639:     eval {
  640: 	local $SIG{__DIE__}='DEFAULT';
  641: 	local $SIG{ALRM}=sub {
  642: 	    $failed=1;
  643: 	    die("failed lock");
  644: 	};
  645: 	alarm(13);
  646: 	flock($file,$lock_type);
  647: 	alarm(0);
  648:     };
  649:     if ($failed) {
  650: 	return undef;
  651:     } else {
  652: 	return 1;
  653:     }
  654: }
  655: 
  656: # ---------------------------------------------------------- Append Environment
  657: 
  658: sub appenv {
  659:     my ($newenv,$roles) = @_;
  660:     if (ref($newenv) eq 'HASH') {
  661:         foreach my $key (keys(%{$newenv})) {
  662:             my $refused = 0;
  663: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  664:                 $refused = 1;
  665:                 if (ref($roles) eq 'ARRAY') {
  666:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  667:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  668:                         $refused = 0;
  669:                     }
  670:                 }
  671:             }
  672:             if ($refused) {
  673:                 &logthis("<font color=\"blue\">WARNING: ".
  674:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  675:                          .'</font>');
  676: 	        delete($newenv->{$key});
  677:             } else {
  678:                 $env{$key}=$newenv->{$key};
  679:             }
  680:         }
  681:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  682:         if ($opened
  683: 	    && &timed_flock($env_file,LOCK_EX)
  684: 	    &&
  685: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  686: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  687: 	    while (my ($key,$value) = each(%{$newenv})) {
  688: 	        $disk_env{$key} = $value;
  689: 	    }
  690: 	    untie(%disk_env);
  691:         }
  692:     }
  693:     return 'ok';
  694: }
  695: # ----------------------------------------------------- Delete from Environment
  696: 
  697: sub delenv {
  698:     my ($delthis,$regexp,$roles) = @_;
  699:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  700:         my $refused = 1;
  701:         if (ref($roles) eq 'ARRAY') {
  702:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  703:             if (grep(/^\Q$role\E$/,@{$roles})) {
  704:                 $refused = 0;
  705:             }
  706:         }
  707:         if ($refused) {
  708:             &logthis("<font color=\"blue\">WARNING: ".
  709:                      "Attempt to delete from environment ".$delthis);
  710:             return 'error';
  711:         }
  712:     }
  713:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  714:     if ($opened
  715: 	&& &timed_flock($env_file,LOCK_EX)
  716: 	&&
  717: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  718: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  719: 	foreach my $key (keys(%disk_env)) {
  720: 	    if ($regexp) {
  721:                 if ($key=~/^$delthis/) {
  722:                     delete($env{$key});
  723:                     delete($disk_env{$key});
  724:                 } 
  725:             } else {
  726:                 if ($key=~/^\Q$delthis\E/) {
  727: 		    delete($env{$key});
  728: 		    delete($disk_env{$key});
  729: 	        }
  730:             }
  731: 	}
  732: 	untie(%disk_env);
  733:     }
  734:     return 'ok';
  735: }
  736: 
  737: sub get_env_multiple {
  738:     my ($name) = @_;
  739:     my @values;
  740:     if (defined($env{$name})) {
  741:         # exists is it an array
  742:         if (ref($env{$name})) {
  743:             @values=@{ $env{$name} };
  744:         } else {
  745:             $values[0]=$env{$name};
  746:         }
  747:     }
  748:     return(@values);
  749: }
  750: 
  751: # ------------------------------------------------------------------- Locking
  752: 
  753: sub set_lock {
  754:     my ($text)=@_;
  755:     $locknum++;
  756:     my $id=$$.'-'.$locknum;
  757:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  758:              'session.lock.'.$id => $text});
  759:     return $id;
  760: }
  761: 
  762: sub get_locks {
  763:     my $num=0;
  764:     my %texts=();
  765:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  766:        if ($lock=~/\w/) {
  767:           $num++;
  768:           $texts{$lock}=$env{'session.lock.'.$lock};
  769:        }
  770:    }
  771:    return ($num,%texts);
  772: }
  773: 
  774: sub remove_lock {
  775:     my ($id)=@_;
  776:     my $newlocks='';
  777:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  778:        if (($lock=~/\w/) && ($lock ne $id)) {
  779:           $newlocks.=','.$lock;
  780:        }
  781:     }
  782:     &appenv({'session.locks' => $newlocks});
  783:     &delenv('session.lock.'.$id);
  784: }
  785: 
  786: sub remove_all_locks {
  787:     my $activelocks=$env{'session.locks'};
  788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  789:        if ($lock=~/\w/) {
  790:           &remove_lock($lock);
  791:        }
  792:     }
  793: }
  794: 
  795: 
  796: # ------------------------------------------ Find out current server userload
  797: sub userload {
  798:     my $numusers=0;
  799:     {
  800: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  801: 	my $filename;
  802: 	my $curtime=time;
  803: 	while ($filename=readdir(LONIDS)) {
  804: 	    next if ($filename eq '.' || $filename eq '..');
  805: 	    next if ($filename =~ /publicuser_\d+\.id/);
  806: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  807: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  808: 	}
  809: 	closedir(LONIDS);
  810:     }
  811:     my $userloadpercent=0;
  812:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  813:     if ($maxuserload) {
  814: 	$userloadpercent=100*$numusers/$maxuserload;
  815:     }
  816:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  817:     return $userloadpercent;
  818: }
  819: 
  820: # ------------------------------ Find server with least workload from spare.tab
  821: 
  822: sub spareserver {
  823:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  824:     my $spare_server;
  825:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  826:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  827:                                                      :  $userloadpercent;
  828:     my ($uint_dom,$remotesessions);
  829:     if (($udom ne '') && (&domain($udom) ne '')) {
  830:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  831:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  832:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  833:         $remotesessions = $udomdefaults{'remotesessions'};
  834:     }
  835:     my $spareshash = &this_host_spares($udom);
  836:     if (ref($spareshash) eq 'HASH') {
  837:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  838:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  839:                 if ($uint_dom) {
  840:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  841:                                                  $try_server));
  842:                 }
  843: 	        ($spare_server, $lowest_load) =
  844: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  845:             }
  846:         }
  847: 
  848:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  849: 
  850:         if (!$found_server) {
  851:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  852: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  853:                     if ($uint_dom) {
  854:                         next unless (&spare_can_host($udom,$uint_dom,
  855:                                                      $remotesessions,$try_server));
  856:                     }
  857: 	            ($spare_server, $lowest_load) =
  858: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  859:                 }
  860: 	    }
  861:         }
  862:     }
  863: 
  864:     if (!$want_server_name) {
  865:         my $protocol = 'http';
  866:         if ($protocol{$spare_server} eq 'https') {
  867:             $protocol = $protocol{$spare_server};
  868:         }
  869:         if (defined($spare_server)) {
  870:             my $hostname = &hostname($spare_server);
  871:             if (defined($hostname)) {
  872: 	        $spare_server = $protocol.'://'.$hostname;
  873:             }
  874:         }
  875:     }
  876:     return $spare_server;
  877: }
  878: 
  879: sub compare_server_load {
  880:     my ($try_server, $spare_server, $lowest_load) = @_;
  881: 
  882:     my $loadans     = &reply('load',    $try_server);
  883:     my $userloadans = &reply('userload',$try_server);
  884: 
  885:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  886: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  887:     }
  888: 
  889:     my $load;
  890:     if ($loadans =~ /\d/) {
  891: 	if ($userloadans =~ /\d/) {
  892: 	    #both are numbers, pick the bigger one
  893: 	    $load = ($loadans > $userloadans) ? $loadans 
  894: 		                              : $userloadans;
  895: 	} else {
  896: 	    $load = $loadans;
  897: 	}
  898:     } else {
  899: 	$load = $userloadans;
  900:     }
  901: 
  902:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  903: 	$spare_server = $try_server;
  904: 	$lowest_load  = $load;
  905:     }
  906:     return ($spare_server,$lowest_load);
  907: }
  908: 
  909: # --------------------------- ask offload servers if user already has a session
  910: sub find_existing_session {
  911:     my ($udom,$uname) = @_;
  912:     my $spareshash = &this_host_spares($udom);
  913:     if (ref($spareshash) eq 'HASH') {
  914:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  915:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  916:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  917:             }
  918:         }
  919:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  920:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  921:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  922:             }
  923:         }
  924:     }
  925:     return;
  926: }
  927: 
  928: # -------------------------------- ask if server already has a session for user
  929: sub has_user_session {
  930:     my ($lonid,$udom,$uname) = @_;
  931:     my $result = &reply(join(':','userhassession',
  932: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  933:     return 1 if ($result eq 'ok');
  934: 
  935:     return 0;
  936: }
  937: 
  938: # --------- determine least loaded server in a user's domain which allows login
  939: 
  940: sub choose_server {
  941:     my ($udom,$checkloginvia) = @_;
  942:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  943:     my %servers = &get_servers($udom);
  944:     my $lowest_load = 30000;
  945:     my ($login_host,$hostname,$portal_path,$isredirect);
  946:     foreach my $lonhost (keys(%servers)) {
  947:         my $loginvia;
  948:         if ($checkloginvia) {
  949:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  950:             if ($loginvia) {
  951:                 my ($server,$path) = split(/:/,$loginvia);
  952:                 ($login_host, $lowest_load) =
  953:                     &compare_server_load($server, $login_host, $lowest_load);
  954:                 if ($login_host eq $server) {
  955:                     $portal_path = $path;
  956:                     $isredirect = 1;
  957:                 }
  958:             } else {
  959:                 ($login_host, $lowest_load) =
  960:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  961:                 if ($login_host eq $lonhost) {
  962:                     $portal_path = '';
  963:                     $isredirect = ''; 
  964:                 }
  965:             }
  966:         } else {
  967:             ($login_host, $lowest_load) =
  968:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  969:         }
  970:     }
  971:     if ($login_host ne '') {
  972:         $hostname = &hostname($login_host);
  973:     }
  974:     return ($login_host,$hostname,$portal_path,$isredirect);
  975: }
  976: 
  977: # --------------------------------------------- Try to change a user's password
  978: 
  979: sub changepass {
  980:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  981:     $currentpass = &escape($currentpass);
  982:     $newpass     = &escape($newpass);
  983:     my $lonhost = $perlvar{'lonHostID'};
  984:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  985: 		       $server);
  986:     if (! $answer) {
  987: 	&logthis("No reply on password change request to $server ".
  988: 		 "by $uname in domain $udom.");
  989:     } elsif ($answer =~ "^ok") {
  990:         &logthis("$uname in $udom successfully changed their password ".
  991: 		 "on $server.");
  992:     } elsif ($answer =~ "^pwchange_failure") {
  993: 	&logthis("$uname in $udom was unable to change their password ".
  994: 		 "on $server.  The action was blocked by either lcpasswd ".
  995: 		 "or pwchange");
  996:     } elsif ($answer =~ "^non_authorized") {
  997:         &logthis("$uname in $udom did not get their password correct when ".
  998: 		 "attempting to change it on $server.");
  999:     } elsif ($answer =~ "^auth_mode_error") {
 1000:         &logthis("$uname in $udom attempted to change their password despite ".
 1001: 		 "not being locally or internally authenticated on $server.");
 1002:     } elsif ($answer =~ "^unknown_user") {
 1003:         &logthis("$uname in $udom attempted to change their password ".
 1004: 		 "on $server but were unable to because $server is not ".
 1005: 		 "their home server.");
 1006:     } elsif ($answer =~ "^refused") {
 1007: 	&logthis("$server refused to change $uname in $udom password because ".
 1008: 		 "it was sent an unencrypted request to change the password.");
 1009:     } elsif ($answer =~ "invalid_client") {
 1010:         &logthis("$server refused to change $uname in $udom password because ".
 1011:                  "it was a reset by e-mail originating from an invalid server.");
 1012:     }
 1013:     return $answer;
 1014: }
 1015: 
 1016: # ----------------------- Try to determine user's current authentication scheme
 1017: 
 1018: sub queryauthenticate {
 1019:     my ($uname,$udom)=@_;
 1020:     my $uhome=&homeserver($uname,$udom);
 1021:     if (!$uhome) {
 1022: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1023: 	return 'no_host';
 1024:     }
 1025:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1026:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1027: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1028:     }
 1029:     return $answer;
 1030: }
 1031: 
 1032: # --------- Try to authenticate user from domain's lib servers (first this one)
 1033: 
 1034: sub authenticate {
 1035:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1036:     $upass=&escape($upass);
 1037:     $uname= &LONCAPA::clean_username($uname);
 1038:     my $uhome=&homeserver($uname,$udom,1);
 1039:     my $newhome;
 1040:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1041: # Maybe the machine was offline and only re-appeared again recently?
 1042:         &reconlonc();
 1043: # One more
 1044: 	$uhome=&homeserver($uname,$udom,1);
 1045:         if (($uhome eq 'no_host') && $checkdefauth) {
 1046:             if (defined(&domain($udom,'primary'))) {
 1047:                 $newhome=&domain($udom,'primary');
 1048:             }
 1049:             if ($newhome ne '') {
 1050:                 $uhome = $newhome;
 1051:             }
 1052:         }
 1053: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1054: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1055: 	    return 'no_host';
 1056:         }
 1057:     }
 1058:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1059:     if ($answer eq 'authorized') {
 1060:         if ($newhome) {
 1061:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1062:             return 'no_account_on_host'; 
 1063:         } else {
 1064:             &logthis("User $uname at $udom authorized by $uhome");
 1065:             return $uhome;
 1066:         }
 1067:     }
 1068:     if ($answer eq 'non_authorized') {
 1069: 	&logthis("User $uname at $udom rejected by $uhome");
 1070: 	return 'no_host'; 
 1071:     }
 1072:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1073:     return 'no_host';
 1074: }
 1075: 
 1076: sub can_host_session {
 1077:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1078:     my $canhost = 1;
 1079:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1080:     if (ref($remotesessions) eq 'HASH') {
 1081:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1082:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1083:                 $canhost = 0;
 1084:             } else {
 1085:                 $canhost = 1;
 1086:             }
 1087:         }
 1088:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1089:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1090:                 $canhost = 1;
 1091:             } else {
 1092:                 $canhost = 0;
 1093:             }
 1094:         }
 1095:         if ($canhost) {
 1096:             if ($remotesessions->{'version'} ne '') {
 1097:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1098:                 if ($reqmajor ne '' && $reqminor ne '') {
 1099:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1100:                         my $major = $1;
 1101:                         my $minor = $2;
 1102:                         if (($major < $reqmajor ) ||
 1103:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1104:                             $canhost = 0;
 1105:                         }
 1106:                     } else {
 1107:                         $canhost = 0;
 1108:                     }
 1109:                 }
 1110:             }
 1111:         }
 1112:     }
 1113:     if ($canhost) {
 1114:         if (ref($hostedsessions) eq 'HASH') {
 1115:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1116:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1117:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1118:                 if (($uint_dom ne '') && 
 1119:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1120:                     $canhost = 0;
 1121:                 } else {
 1122:                     $canhost = 1;
 1123:                 }
 1124:             }
 1125:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1126:                 if (($uint_dom ne '') && 
 1127:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1128:                     $canhost = 1;
 1129:                 } else {
 1130:                     $canhost = 0;
 1131:                 }
 1132:             }
 1133:         }
 1134:     }
 1135:     return $canhost;
 1136: }
 1137: 
 1138: sub spare_can_host {
 1139:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1140:     my $canhost=1;
 1141:     my @intdoms;
 1142:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1143:     if (ref($internet_names) eq 'ARRAY') {
 1144:         @intdoms = @{$internet_names};
 1145:     }
 1146:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1147:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1148:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1149:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1150:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1151:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1152:                                      $remotesessions,
 1153:                                      $defdomdefaults{'hostedsessions'});
 1154:     }
 1155:     return $canhost;
 1156: }
 1157: 
 1158: sub this_host_spares {
 1159:     my ($dom) = @_;
 1160:     my ($dom_in_use,$lonhost_in_use,$result);
 1161:     my @hosts = &current_machine_ids();
 1162:     foreach my $lonhost (@hosts) {
 1163:         if (&host_domain($lonhost) eq $dom) {
 1164:             $dom_in_use = $dom;
 1165:             $lonhost_in_use = $lonhost;
 1166:             last;
 1167:         }
 1168:     }
 1169:     if ($dom_in_use ne '') {
 1170:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1171:     }
 1172:     if (ref($result) ne 'HASH') {
 1173:         $lonhost_in_use = $perlvar{'lonHostID'};
 1174:         $dom_in_use = &host_domain($lonhost_in_use);
 1175:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1176:         if (ref($result) ne 'HASH') {
 1177:             $result = \%spareid;
 1178:         }
 1179:     }
 1180:     return $result;
 1181: }
 1182: 
 1183: sub spares_for_offload  {
 1184:     my ($dom_in_use,$lonhost_in_use) = @_;
 1185:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1186:     if (defined($cached)) {
 1187:         return $result;
 1188:     } else {
 1189:         my $cachetime = 60*60*24;
 1190:         my %domconfig =
 1191:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1192:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1193:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1194:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1195:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1196:                 }
 1197:             }
 1198:         }
 1199:     }
 1200:     return;
 1201: }
 1202: 
 1203: sub get_lonbalancer_config {
 1204:     my ($servers) = @_;
 1205:     my ($currbalancer,$currtargets);
 1206:     if (ref($servers) eq 'HASH') {
 1207:         foreach my $server (keys(%{$servers})) {
 1208:             my %what = (
 1209:                          spareid => 1,
 1210:                          perlvar => 1,
 1211:                        );
 1212:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1213:             if ($result eq 'ok') {
 1214:                 if (ref($returnhash) eq 'HASH') {
 1215:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1216:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1217:                             $currbalancer = $server;
 1218:                             $currtargets = {};
 1219:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1220:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1221:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1222:                                 }
 1223:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1224:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1225:                                 }
 1226:                             }
 1227:                             last;
 1228:                         }
 1229:                     }
 1230:                 }
 1231:             }
 1232:         }
 1233:     }
 1234:     return ($currbalancer,$currtargets);
 1235: }
 1236: 
 1237: sub check_loadbalancing {
 1238:     my ($uname,$udom) = @_;
 1239:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1240:         $offloadto,$otherserver);
 1241:     my $lonhost = $perlvar{'lonHostID'};
 1242:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1243:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1244:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1245:     my $serverhomedom = &host_domain($lonhost);
 1246: 
 1247:     my $cachetime = 60*60*24;
 1248: 
 1249:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1250:         $dom_in_use = $udom;
 1251:         $homeintdom = 1;
 1252:     } else {
 1253:         $dom_in_use = $serverhomedom;
 1254:     }
 1255:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1256:     unless (defined($cached)) {
 1257:         my %domconfig =
 1258:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1259:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1260:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1261:         }
 1262:     }
 1263:     if (ref($result) eq 'HASH') {
 1264:         my $currbalancer = $result->{'lonhost'};
 1265:         my $currtargets = $result->{'targets'};
 1266:         my $currrules = $result->{'rules'};
 1267:         if ($currbalancer ne '') {
 1268:             my @hosts = &current_machine_ids();
 1269:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1270:                 $is_balancer = 1;
 1271:             }
 1272:         }
 1273:         if ($is_balancer) {
 1274:             if (ref($currrules) eq 'HASH') {
 1275:                 if ($homeintdom) {
 1276:                     if ($uname ne '') {
 1277:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1278:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1279:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1281:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1282:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1283:                             }
 1284:                         }
 1285:                         if ($rule_in_effect eq '') {
 1286:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1287:                             if ($userenv{'inststatus'} ne '') {
 1288:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1289:                                 my ($othertitle,$usertypes,$types) =
 1290:                                     &Apache::loncommon::sorted_inst_types($udom);
 1291:                                 if (ref($types) eq 'ARRAY') {
 1292:                                     foreach my $type (@{$types}) {
 1293:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1294:                                             if (exists($currrules->{$type})) {
 1295:                                                 $rule_in_effect = $currrules->{$type};
 1296:                                             }
 1297:                                         }
 1298:                                     }
 1299:                                 }
 1300:                             } else {
 1301:                                 if (exists($currrules->{'default'})) {
 1302:                                     $rule_in_effect = $currrules->{'default'};
 1303:                                 }
 1304:                             }
 1305:                         }
 1306:                     } else {
 1307:                         if (exists($currrules->{'default'})) {
 1308:                             $rule_in_effect = $currrules->{'default'};
 1309:                         }
 1310:                     }
 1311:                 } else {
 1312:                     if ($currrules->{'_LC_external'} ne '') {
 1313:                         $rule_in_effect = $currrules->{'_LC_external'};
 1314:                     }
 1315:                 }
 1316:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1317:                                                        $uname,$udom);
 1318:             }
 1319:         }
 1320:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1321:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1322:         unless (defined($cached)) {
 1323:             my %domconfig =
 1324:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1325:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1326:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1327:             }
 1328:         }
 1329:         if (ref($result) eq 'HASH') {
 1330:             my $currbalancer = $result->{'lonhost'};
 1331:             my $currtargets = $result->{'targets'};
 1332:             my $currrules = $result->{'rules'};
 1333: 
 1334:             if ($currbalancer eq $lonhost) {
 1335:                 $is_balancer = 1;
 1336:                 if (ref($currrules) eq 'HASH') {
 1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1339:                     }
 1340:                 }
 1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1342:                                                        $uname,$udom);
 1343:             }
 1344:         } else {
 1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1346:                 $is_balancer = 1;
 1347:                 $offloadto = &this_host_spares($dom_in_use);
 1348:             }
 1349:         }
 1350:     } else {
 1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1352:             $is_balancer = 1;
 1353:             $offloadto = &this_host_spares($dom_in_use);
 1354:         }
 1355:     }
 1356:     my $lowest_load = 30000;
 1357:     if (ref($offloadto) eq 'HASH') {
 1358:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1359:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1360:                 ($otherserver,$lowest_load) =
 1361:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1362:             }
 1363:         }
 1364:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1365: 
 1366:         if (!$found_server) {
 1367:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1368:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1369:                     ($otherserver,$lowest_load) =
 1370:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1371:                 }
 1372:             }
 1373:         }
 1374:     } elsif (ref($offloadto) eq 'ARRAY') {
 1375:         if (@{$offloadto} == 1) {
 1376:             $otherserver = $offloadto->[0];
 1377:         } elsif (@{$offloadto} > 1) {
 1378:             foreach my $try_server (@{$offloadto}) {
 1379:                 ($otherserver,$lowest_load) =
 1380:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1381:             }
 1382:         }
 1383:     }
 1384:     return ($is_balancer,$otherserver);
 1385: }
 1386: 
 1387: sub get_loadbalancer_targets {
 1388:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1389:     my $offloadto;
 1390:     if ($rule_in_effect eq '') {
 1391:         $offloadto = $currtargets;
 1392:     } else {
 1393:         if ($rule_in_effect eq 'homeserver') {
 1394:             my $homeserver = &homeserver($uname,$udom);
 1395:             if ($homeserver ne 'no_host') {
 1396:                 $offloadto = [$homeserver];
 1397:             }
 1398:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1399:             my %domconfig =
 1400:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1401:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1402:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1403:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1404:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1405:                     }
 1406:                 }
 1407:             } else {
 1408:                 my %servers = &dom_servers($udom);
 1409:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1410:                 if (&hostname($remotebalancer) ne '') {
 1411:                     $offloadto = [$remotebalancer];
 1412:                 }
 1413:             }
 1414:         } elsif (&hostname($rule_in_effect) ne '') {
 1415:             $offloadto = [$rule_in_effect];
 1416:         }
 1417:     }
 1418:     return $offloadto;
 1419: }
 1420: 
 1421: sub internet_dom_servers {
 1422:     my ($dom) = @_;
 1423:     my (%uniqservers,%servers);
 1424:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1425:     my @machinedoms = &machine_domains($primaryserver);
 1426:     foreach my $mdom (@machinedoms) {
 1427:         my %currservers = %servers;
 1428:         my %server = &get_servers($mdom);
 1429:         %servers = (%currservers,%server);
 1430:     }
 1431:     my %by_hostname;
 1432:     foreach my $id (keys(%servers)) {
 1433:         push(@{$by_hostname{$servers{$id}}},$id);
 1434:     }
 1435:     foreach my $hostname (sort(keys(%by_hostname))) {
 1436:         if (@{$by_hostname{$hostname}} > 1) {
 1437:             my $match = 0;
 1438:             foreach my $id (@{$by_hostname{$hostname}}) {
 1439:                 if (&host_domain($id) eq $dom) {
 1440:                     $uniqservers{$id} = $hostname;
 1441:                     $match = 1;
 1442:                 }
 1443:             }
 1444:             unless ($match) {
 1445:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1446:             }
 1447:         } else {
 1448:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1449:         }
 1450:     }
 1451:     return %uniqservers;
 1452: }
 1453: 
 1454: # ---------------------- Find the homebase for a user from domain's lib servers
 1455: 
 1456: my %homecache;
 1457: sub homeserver {
 1458:     my ($uname,$udom,$ignoreBadCache)=@_;
 1459:     my $index="$uname:$udom";
 1460: 
 1461:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1462: 
 1463:     my %servers = &get_servers($udom,'library');
 1464:     foreach my $tryserver (keys(%servers)) {
 1465:         next if ($ignoreBadCache ne 'true' && 
 1466: 		 exists($badServerCache{$tryserver}));
 1467: 
 1468: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1469: 	if ($answer eq 'found') {
 1470: 	    delete($badServerCache{$tryserver}); 
 1471: 	    return $homecache{$index}=$tryserver;
 1472: 	} elsif ($answer eq 'no_host') {
 1473: 	    $badServerCache{$tryserver}=1;
 1474: 	}
 1475:     }    
 1476:     return 'no_host';
 1477: }
 1478: 
 1479: # ------------------------------------- Find the usernames behind a list of IDs
 1480: 
 1481: sub idget {
 1482:     my ($udom,@ids)=@_;
 1483:     my %returnhash=();
 1484:     
 1485:     my %servers = &get_servers($udom,'library');
 1486:     foreach my $tryserver (keys(%servers)) {
 1487: 	my $idlist=join('&',@ids);
 1488: 	$idlist=~tr/A-Z/a-z/; 
 1489: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1490: 	my @answer=();
 1491: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1492: 	    @answer=split(/\&/,$reply);
 1493: 	}                    ;
 1494: 	my $i;
 1495: 	for ($i=0;$i<=$#ids;$i++) {
 1496: 	    if ($answer[$i]) {
 1497: 		$returnhash{$ids[$i]}=$answer[$i];
 1498: 	    } 
 1499: 	}
 1500:     } 
 1501:     return %returnhash;
 1502: }
 1503: 
 1504: # ------------------------------------- Find the IDs behind a list of usernames
 1505: 
 1506: sub idrget {
 1507:     my ($udom,@unames)=@_;
 1508:     my %returnhash=();
 1509:     foreach my $uname (@unames) {
 1510:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1511:     }
 1512:     return %returnhash;
 1513: }
 1514: 
 1515: # ------------------------------- Store away a list of names and associated IDs
 1516: 
 1517: sub idput {
 1518:     my ($udom,%ids)=@_;
 1519:     my %servers=();
 1520:     foreach my $uname (keys(%ids)) {
 1521: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1522:         my $uhom=&homeserver($uname,$udom);
 1523:         if ($uhom ne 'no_host') {
 1524:             my $id=&escape($ids{$uname});
 1525:             $id=~tr/A-Z/a-z/;
 1526:             my $esc_unam=&escape($uname);
 1527: 	    if ($servers{$uhom}) {
 1528: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1529:             } else {
 1530:                 $servers{$uhom}=$id.'='.$esc_unam;
 1531:             }
 1532:         }
 1533:     }
 1534:     foreach my $server (keys(%servers)) {
 1535:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1536:     }
 1537: }
 1538: 
 1539: # ------------------------------dump from db file owned by domainconfig user
 1540: sub dump_dom {
 1541:     my ($namespace, $udom, $regexp) = @_;
 1542: 
 1543:     $udom ||= $env{'user.domain'};
 1544: 
 1545:     return () unless $udom;
 1546: 
 1547:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1548: }
 1549: 
 1550: # ------------------------------------------ get items from domain db files   
 1551: 
 1552: sub get_dom {
 1553:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1554:     my $items='';
 1555:     foreach my $item (@$storearr) {
 1556:         $items.=&escape($item).'&';
 1557:     }
 1558:     $items=~s/\&$//;
 1559:     if (!$udom) {
 1560:         $udom=$env{'user.domain'};
 1561:         if (defined(&domain($udom,'primary'))) {
 1562:             $uhome=&domain($udom,'primary');
 1563:         } else {
 1564:             undef($uhome);
 1565:         }
 1566:     } else {
 1567:         if (!$uhome) {
 1568:             if (defined(&domain($udom,'primary'))) {
 1569:                 $uhome=&domain($udom,'primary');
 1570:             }
 1571:         }
 1572:     }
 1573:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1574:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1575:         my %returnhash;
 1576:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1577:             return %returnhash;
 1578:         }
 1579:         my @pairs=split(/\&/,$rep);
 1580:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1581:             return @pairs;
 1582:         }
 1583:         my $i=0;
 1584:         foreach my $item (@$storearr) {
 1585:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1586:             $i++;
 1587:         }
 1588:         return %returnhash;
 1589:     } else {
 1590:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1591:     }
 1592: }
 1593: 
 1594: # -------------------------------------------- put items in domain db files 
 1595: 
 1596: sub put_dom {
 1597:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1598:     if (!$udom) {
 1599:         $udom=$env{'user.domain'};
 1600:         if (defined(&domain($udom,'primary'))) {
 1601:             $uhome=&domain($udom,'primary');
 1602:         } else {
 1603:             undef($uhome);
 1604:         }
 1605:     } else {
 1606:         if (!$uhome) {
 1607:             if (defined(&domain($udom,'primary'))) {
 1608:                 $uhome=&domain($udom,'primary');
 1609:             }
 1610:         }
 1611:     } 
 1612:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1613:         my $items='';
 1614:         foreach my $item (keys(%$storehash)) {
 1615:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1616:         }
 1617:         $items=~s/\&$//;
 1618:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1619:     } else {
 1620:         &logthis("put_dom failed - no homeserver and/or domain");
 1621:     }
 1622: }
 1623: 
 1624: # --------------------- newput for items in db file owned by domainconfig user
 1625: sub newput_dom {
 1626:     my ($namespace,$storehash,$udom) = @_;
 1627:     my $result;
 1628:     if (!$udom) {
 1629:         $udom=$env{'user.domain'};
 1630:     }
 1631:     if ($udom) {
 1632:         my $uname = &get_domainconfiguser($udom);
 1633:         $result = &newput($namespace,$storehash,$udom,$uname);
 1634:     }
 1635:     return $result;
 1636: }
 1637: 
 1638: # --------------------- delete for items in db file owned by domainconfig user
 1639: sub del_dom {
 1640:     my ($namespace,$storearr,$udom)=@_;
 1641:     if (ref($storearr) eq 'ARRAY') {
 1642:         if (!$udom) {
 1643:             $udom=$env{'user.domain'};
 1644:         }
 1645:         if ($udom) {
 1646:             my $uname = &get_domainconfiguser($udom); 
 1647:             return &del($namespace,$storearr,$udom,$uname);
 1648:         }
 1649:     }
 1650: }
 1651: 
 1652: # ----------------------------------construct domainconfig user for a domain 
 1653: sub get_domainconfiguser {
 1654:     my ($udom) = @_;
 1655:     return $udom.'-domainconfig';
 1656: }
 1657: 
 1658: sub retrieve_inst_usertypes {
 1659:     my ($udom) = @_;
 1660:     my (%returnhash,@order);
 1661:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1662:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1663:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1664:         %returnhash = %{$domdefs{'inststatustypes'}};
 1665:         @order = @{$domdefs{'inststatusorder'}};
 1666:     } else {
 1667:         if (defined(&domain($udom,'primary'))) {
 1668:             my $uhome=&domain($udom,'primary');
 1669:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1670:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1671:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1672:                 return (\%returnhash,\@order);
 1673:             }
 1674:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1675:             my @pairs=split(/\&/,$hashitems);
 1676:             foreach my $item (@pairs) {
 1677:                 my ($key,$value)=split(/=/,$item,2);
 1678:                 $key = &unescape($key);
 1679:                 next if ($key =~ /^error: 2 /);
 1680:                 $returnhash{$key}=&thaw_unescape($value);
 1681:             }
 1682:             my @esc_order = split(/\&/,$orderitems);
 1683:             foreach my $item (@esc_order) {
 1684:                 push(@order,&unescape($item));
 1685:             }
 1686:         } else {
 1687:             &logthis("get_dom failed - no primary domain server for $udom");
 1688:         }
 1689:     }
 1690:     return (\%returnhash,\@order);
 1691: }
 1692: 
 1693: sub is_domainimage {
 1694:     my ($url) = @_;
 1695:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1696:         if (&domain($1) ne '') {
 1697:             return '1';
 1698:         }
 1699:     }
 1700:     return;
 1701: }
 1702: 
 1703: sub inst_directory_query {
 1704:     my ($srch) = @_;
 1705:     my $udom = $srch->{'srchdomain'};
 1706:     my %results;
 1707:     my $homeserver = &domain($udom,'primary');
 1708:     my $outcome;
 1709:     if ($homeserver ne '') {
 1710: 	my $queryid=&reply("querysend:instdirsearch:".
 1711: 			   &escape($srch->{'srchby'}).':'.
 1712: 			   &escape($srch->{'srchterm'}).':'.
 1713: 			   &escape($srch->{'srchtype'}),$homeserver);
 1714: 	my $host=&hostname($homeserver);
 1715: 	if ($queryid !~/^\Q$host\E\_/) {
 1716: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1717: 	    return;
 1718: 	}
 1719: 	my $response = &get_query_reply($queryid);
 1720: 	my $maxtries = 5;
 1721: 	my $tries = 1;
 1722: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1723: 	    $response = &get_query_reply($queryid);
 1724: 	    $tries ++;
 1725: 	}
 1726: 
 1727:         if (!&error($response) && $response ne 'refused') {
 1728:             if ($response eq 'unavailable') {
 1729:                 $outcome = $response;
 1730:             } else {
 1731:                 $outcome = 'ok';
 1732:                 my @matches = split(/\n/,$response);
 1733:                 foreach my $match (@matches) {
 1734:                     my ($key,$value) = split(/=/,$match);
 1735:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1736:                 }
 1737:             }
 1738:         }
 1739:     }
 1740:     return ($outcome,%results);
 1741: }
 1742: 
 1743: sub usersearch {
 1744:     my ($srch) = @_;
 1745:     my $dom = $srch->{'srchdomain'};
 1746:     my %results;
 1747:     my %libserv = &all_library();
 1748:     my $query = 'usersearch';
 1749:     foreach my $tryserver (keys(%libserv)) {
 1750:         if (&host_domain($tryserver) eq $dom) {
 1751:             my $host=&hostname($tryserver);
 1752:             my $queryid=
 1753:                 &reply("querysend:".&escape($query).':'.
 1754:                        &escape($srch->{'srchby'}).':'.
 1755:                        &escape($srch->{'srchtype'}).':'.
 1756:                        &escape($srch->{'srchterm'}),$tryserver);
 1757:             if ($queryid !~/^\Q$host\E\_/) {
 1758:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1759:                 next;
 1760:             }
 1761:             my $reply = &get_query_reply($queryid);
 1762:             my $maxtries = 1;
 1763:             my $tries = 1;
 1764:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1765:                 $reply = &get_query_reply($queryid);
 1766:                 $tries ++;
 1767:             }
 1768:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1769:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1770:             } else {
 1771:                 my @matches;
 1772:                 if ($reply =~ /\n/) {
 1773:                     @matches = split(/\n/,$reply);
 1774:                 } else {
 1775:                     @matches = split(/\&/,$reply);
 1776:                 }
 1777:                 foreach my $match (@matches) {
 1778:                     my ($uname,$udom,%userhash);
 1779:                     foreach my $entry (split(/:/,$match)) {
 1780:                         my ($key,$value) =
 1781:                             map {&unescape($_);} split(/=/,$entry);
 1782:                         $userhash{$key} = $value;
 1783:                         if ($key eq 'username') {
 1784:                             $uname = $value;
 1785:                         } elsif ($key eq 'domain') {
 1786:                             $udom = $value;
 1787:                         }
 1788:                     }
 1789:                     $results{$uname.':'.$udom} = \%userhash;
 1790:                 }
 1791:             }
 1792:         }
 1793:     }
 1794:     return %results;
 1795: }
 1796: 
 1797: sub get_instuser {
 1798:     my ($udom,$uname,$id) = @_;
 1799:     my $homeserver = &domain($udom,'primary');
 1800:     my ($outcome,%results);
 1801:     if ($homeserver ne '') {
 1802:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1803:                            &escape($id).':'.&escape($udom),$homeserver);
 1804:         my $host=&hostname($homeserver);
 1805:         if ($queryid !~/^\Q$host\E\_/) {
 1806:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1807:             return;
 1808:         }
 1809:         my $response = &get_query_reply($queryid);
 1810:         my $maxtries = 5;
 1811:         my $tries = 1;
 1812:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1813:             $response = &get_query_reply($queryid);
 1814:             $tries ++;
 1815:         }
 1816:         if (!&error($response) && $response ne 'refused') {
 1817:             if ($response eq 'unavailable') {
 1818:                 $outcome = $response;
 1819:             } else {
 1820:                 $outcome = 'ok';
 1821:                 my @matches = split(/\n/,$response);
 1822:                 foreach my $match (@matches) {
 1823:                     my ($key,$value) = split(/=/,$match);
 1824:                     $results{&unescape($key)} = &thaw_unescape($value);
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     my %userinfo;
 1830:     if (ref($results{$uname}) eq 'HASH') {
 1831:         %userinfo = %{$results{$uname}};
 1832:     } 
 1833:     return ($outcome,%userinfo);
 1834: }
 1835: 
 1836: sub inst_rulecheck {
 1837:     my ($udom,$uname,$id,$item,$rules) = @_;
 1838:     my %returnhash;
 1839:     if ($udom ne '') {
 1840:         if (ref($rules) eq 'ARRAY') {
 1841:             @{$rules} = map {&escape($_);} (@{$rules});
 1842:             my $rulestr = join(':',@{$rules});
 1843:             my $homeserver=&domain($udom,'primary');
 1844:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1845:                 my $response;
 1846:                 if ($item eq 'username') {                
 1847:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1848:                                               ':'.&escape($uname).':'.$rulestr,
 1849:                                               $homeserver));
 1850:                 } elsif ($item eq 'id') {
 1851:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1852:                                               ':'.&escape($id).':'.$rulestr,
 1853:                                               $homeserver));
 1854:                 } elsif ($item eq 'selfcreate') {
 1855:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1856:                                                &escape($udom).':'.&escape($uname).
 1857:                                               ':'.$rulestr,$homeserver));
 1858:                 }
 1859:                 if ($response ne 'refused') {
 1860:                     my @pairs=split(/\&/,$response);
 1861:                     foreach my $item (@pairs) {
 1862:                         my ($key,$value)=split(/=/,$item,2);
 1863:                         $key = &unescape($key);
 1864:                         next if ($key =~ /^error: 2 /);
 1865:                         $returnhash{$key}=&thaw_unescape($value);
 1866:                     }
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     return %returnhash;
 1872: }
 1873: 
 1874: sub inst_userrules {
 1875:     my ($udom,$check) = @_;
 1876:     my (%ruleshash,@ruleorder);
 1877:     if ($udom ne '') {
 1878:         my $homeserver=&domain($udom,'primary');
 1879:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:             my $response;
 1881:             if ($check eq 'id') {
 1882:                 $response=&reply('instidrules:'.&escape($udom),
 1883:                                  $homeserver);
 1884:             } elsif ($check eq 'email') {
 1885:                 $response=&reply('instemailrules:'.&escape($udom),
 1886:                                  $homeserver);
 1887:             } else {
 1888:                 $response=&reply('instuserrules:'.&escape($udom),
 1889:                                  $homeserver);
 1890:             }
 1891:             if (($response ne 'refused') && ($response ne 'error') && 
 1892:                 ($response ne 'unknown_cmd') && 
 1893:                 ($response ne 'no_such_host')) {
 1894:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1895:                 my @pairs=split(/\&/,$hashitems);
 1896:                 foreach my $item (@pairs) {
 1897:                     my ($key,$value)=split(/=/,$item,2);
 1898:                     $key = &unescape($key);
 1899:                     next if ($key =~ /^error: 2 /);
 1900:                     $ruleshash{$key}=&thaw_unescape($value);
 1901:                 }
 1902:                 my @esc_order = split(/\&/,$orderitems);
 1903:                 foreach my $item (@esc_order) {
 1904:                     push(@ruleorder,&unescape($item));
 1905:                 }
 1906:             }
 1907:         }
 1908:     }
 1909:     return (\%ruleshash,\@ruleorder);
 1910: }
 1911: 
 1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1913: 
 1914: sub get_domain_defaults {
 1915:     my ($domain) = @_;
 1916:     my $cachetime = 60*60*24;
 1917:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1918:     if (defined($cached)) {
 1919:         if (ref($result) eq 'HASH') {
 1920:             return %{$result};
 1921:         }
 1922:     }
 1923:     my %domdefaults;
 1924:     my %domconfig =
 1925:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1926:                                   'requestcourses','inststatus',
 1927:                                   'coursedefaults','usersessions'],$domain);
 1928:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1929:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1930:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1931:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1932:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1933:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1934:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1935:     } else {
 1936:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1937:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1938:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1939:     }
 1940:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1941:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1943:         } else {
 1944:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1945:         } 
 1946:         my @usertools = ('aboutme','blog','portfolio');
 1947:         foreach my $item (@usertools) {
 1948:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1949:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1950:             }
 1951:         }
 1952:     }
 1953:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1954:         foreach my $item ('official','unofficial','community') {
 1955:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1956:         }
 1957:     }
 1958:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1959:         foreach my $item ('inststatustypes','inststatusorder') {
 1960:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1961:         }
 1962:     }
 1963:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1964:         foreach my $item ('canuse_pdfforms') {
 1965:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1966:         }
 1967:     }
 1968:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1969:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1970:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1971:         }
 1972:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1973:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1974:         }
 1975:     }
 1976:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1977:                                   $cachetime);
 1978:     return %domdefaults;
 1979: }
 1980: 
 1981: # --------------------------------------------------- Assign a key to a student
 1982: 
 1983: sub assign_access_key {
 1984: #
 1985: # a valid key looks like uname:udom#comments
 1986: # comments are being appended
 1987: #
 1988:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1989:     $kdom=
 1990:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1991:     $knum=
 1992:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1993:     $cdom=
 1994:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1995:     $cnum=
 1996:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1997:     $udom=$env{'user.name'} unless (defined($udom));
 1998:     $uname=$env{'user.domain'} unless (defined($uname));
 1999:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2000:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2001:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2002:                                                   # assigned to this person
 2003:                                                   # - this should not happen,
 2004:                                                   # unless something went wrong
 2005:                                                   # the first time around
 2006: # ready to assign
 2007:         $logentry=$1.'; '.$logentry;
 2008:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2009:                                                  $kdom,$knum) eq 'ok') {
 2010: # key now belongs to user
 2011: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2012:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2013:                 &appenv({'environment.'.$envkey => $ckey});
 2014:                 return 'ok';
 2015:             } else {
 2016:                 return 
 2017:   'error: Count not permanently assign key, will need to be re-entered later.';
 2018: 	    }
 2019:         } else {
 2020:             return 'error: Could not assign key, try again later.';
 2021:         }
 2022:     } elsif (!$existing{$ckey}) {
 2023: # the key does not exist
 2024: 	return 'error: The key does not exist';
 2025:     } else {
 2026: # the key is somebody else's
 2027: 	return 'error: The key is already in use';
 2028:     }
 2029: }
 2030: 
 2031: # ------------------------------------------ put an additional comment on a key
 2032: 
 2033: sub comment_access_key {
 2034: #
 2035: # a valid key looks like uname:udom#comments
 2036: # comments are being appended
 2037: #
 2038:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2039:     $cdom=
 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2041:     $cnum=
 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2043:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2044:     if ($existing{$ckey}) {
 2045:         $existing{$ckey}.='; '.$logentry;
 2046: # ready to assign
 2047:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2048:                                                  $cdom,$cnum) eq 'ok') {
 2049: 	    return 'ok';
 2050:         } else {
 2051: 	    return 'error: Count not store comment.';
 2052:         }
 2053:     } else {
 2054: # the key does not exist
 2055: 	return 'error: The key does not exist';
 2056:     }
 2057: }
 2058: 
 2059: # ------------------------------------------------------ Generate a set of keys
 2060: 
 2061: sub generate_access_keys {
 2062:     my ($number,$cdom,$cnum,$logentry)=@_;
 2063:     $cdom=
 2064:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2065:     $cnum=
 2066:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2067:     unless (&allowed('mky',$cdom)) { return 0; }
 2068:     unless (($cdom) && ($cnum)) { return 0; }
 2069:     if ($number>10000) { return 0; }
 2070:     sleep(2); # make sure don't get same seed twice
 2071:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2072:     my $total=0;
 2073:     for (my $i=1;$i<=$number;$i++) {
 2074:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2075:                   sprintf("%lx",int(100000*rand)).'-'.
 2076:                   sprintf("%lx",int(100000*rand));
 2077:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2078:        $newkey=~s/0/h/g; # and also 0 and O
 2079:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2080:        if ($existing{$newkey}) {
 2081:            $i--;
 2082:        } else {
 2083: 	  if (&put('accesskeys',
 2084:               { $newkey => '# generated '.localtime().
 2085:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2086:                            '; '.$logentry },
 2087: 		   $cdom,$cnum) eq 'ok') {
 2088:               $total++;
 2089: 	  }
 2090:        }
 2091:     }
 2092:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2093:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2094:     return $total;
 2095: }
 2096: 
 2097: # ------------------------------------------------------- Validate an accesskey
 2098: 
 2099: sub validate_access_key {
 2100:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2101:     $cdom=
 2102:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2103:     $cnum=
 2104:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2105:     $udom=$env{'user.domain'} unless (defined($udom));
 2106:     $uname=$env{'user.name'} unless (defined($uname));
 2107:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2108:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2109: }
 2110: 
 2111: # ------------------------------------- Find the section of student in a course
 2112: sub devalidate_getsection_cache {
 2113:     my ($udom,$unam,$courseid)=@_;
 2114:     my $hashid="$udom:$unam:$courseid";
 2115:     &devalidate_cache_new('getsection',$hashid);
 2116: }
 2117: 
 2118: sub courseid_to_courseurl {
 2119:     my ($courseid) = @_;
 2120:     #already url style courseid
 2121:     return $courseid if ($courseid =~ m{^/});
 2122: 
 2123:     if (exists($env{'course.'.$courseid.'.num'})) {
 2124: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2125: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2126: 	return "/$cdom/$cnum";
 2127:     }
 2128: 
 2129:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2130:     if (exists($courseinfo{'num'})) {
 2131: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2132:     }
 2133: 
 2134:     return undef;
 2135: }
 2136: 
 2137: sub getsection {
 2138:     my ($udom,$unam,$courseid)=@_;
 2139:     my $cachetime=1800;
 2140: 
 2141:     my $hashid="$udom:$unam:$courseid";
 2142:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2143:     if (defined($cached)) { return $result; }
 2144: 
 2145:     my %Pending; 
 2146:     my %Expired;
 2147:     #
 2148:     # Each role can either have not started yet (pending), be active, 
 2149:     #    or have expired.
 2150:     #
 2151:     # If there is an active role, we are done.
 2152:     #
 2153:     # If there is more than one role which has not started yet, 
 2154:     #     choose the one which will start sooner
 2155:     # If there is one role which has not started yet, return it.
 2156:     #
 2157:     # If there is more than one expired role, choose the one which ended last.
 2158:     # If there is a role which has expired, return it.
 2159:     #
 2160:     $courseid = &courseid_to_courseurl($courseid);
 2161:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2162:     foreach my $key (keys(%roleshash)) {
 2163:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2164:         my $section=$1;
 2165:         if ($key eq $courseid.'_st') { $section=''; }
 2166:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2167:         my $now=time;
 2168:         if (defined($end) && $end && ($now > $end)) {
 2169:             $Expired{$end}=$section;
 2170:             next;
 2171:         }
 2172:         if (defined($start) && $start && ($now < $start)) {
 2173:             $Pending{$start}=$section;
 2174:             next;
 2175:         }
 2176:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2177:     }
 2178:     #
 2179:     # Presumedly there will be few matching roles from the above
 2180:     # loop and the sorting time will be negligible.
 2181:     if (scalar(keys(%Pending))) {
 2182:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2183:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2184:     } 
 2185:     if (scalar(keys(%Expired))) {
 2186:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2187:         my $time = pop(@sorted);
 2188:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2189:     }
 2190:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2191: }
 2192: 
 2193: sub save_cache {
 2194:     &purge_remembered();
 2195:     #&Apache::loncommon::validate_page();
 2196:     undef(%env);
 2197:     undef($env_loaded);
 2198: }
 2199: 
 2200: my $to_remember=-1;
 2201: my %remembered;
 2202: my %accessed;
 2203: my $kicks=0;
 2204: my $hits=0;
 2205: sub make_key {
 2206:     my ($name,$id) = @_;
 2207:     if (length($id) > 65 
 2208: 	&& length(&escape($id)) > 200) {
 2209: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2210:     }
 2211:     return &escape($name.':'.$id);
 2212: }
 2213: 
 2214: sub devalidate_cache_new {
 2215:     my ($name,$id,$debug) = @_;
 2216:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2217:     $id=&make_key($name,$id);
 2218:     $memcache->delete($id);
 2219:     delete($remembered{$id});
 2220:     delete($accessed{$id});
 2221: }
 2222: 
 2223: sub is_cached_new {
 2224:     my ($name,$id,$debug) = @_;
 2225:     $id=&make_key($name,$id);
 2226:     if (exists($remembered{$id})) {
 2227: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2228: 	$accessed{$id}=[&gettimeofday()];
 2229: 	$hits++;
 2230: 	return ($remembered{$id},1);
 2231:     }
 2232:     my $value = $memcache->get($id);
 2233:     if (!(defined($value))) {
 2234: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2235: 	return (undef,undef);
 2236:     }
 2237:     if ($value eq '__undef__') {
 2238: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2239: 	$value=undef;
 2240:     }
 2241:     &make_room($id,$value,$debug);
 2242:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2243:     return ($value,1);
 2244: }
 2245: 
 2246: sub do_cache_new {
 2247:     my ($name,$id,$value,$time,$debug) = @_;
 2248:     $id=&make_key($name,$id);
 2249:     my $setvalue=$value;
 2250:     if (!defined($setvalue)) {
 2251: 	$setvalue='__undef__';
 2252:     }
 2253:     if (!defined($time) ) {
 2254: 	$time=600;
 2255:     }
 2256:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2257:     my $result = $memcache->set($id,$setvalue,$time);
 2258:     if (! $result) {
 2259: 	&logthis("caching of id -> $id  failed");
 2260: 	$memcache->disconnect_all();
 2261:     }
 2262:     # need to make a copy of $value
 2263:     &make_room($id,$value,$debug);
 2264:     return $value;
 2265: }
 2266: 
 2267: sub make_room {
 2268:     my ($id,$value,$debug)=@_;
 2269: 
 2270:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2271:                                     : $value;
 2272:     if ($to_remember<0) { return; }
 2273:     $accessed{$id}=[&gettimeofday()];
 2274:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2275:     my $to_kick;
 2276:     my $max_time=0;
 2277:     foreach my $other (keys(%accessed)) {
 2278: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2279: 	    $to_kick=$other;
 2280: 	    $max_time=&tv_interval($accessed{$other});
 2281: 	}
 2282:     }
 2283:     delete($remembered{$to_kick});
 2284:     delete($accessed{$to_kick});
 2285:     $kicks++;
 2286:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2287:     return;
 2288: }
 2289: 
 2290: sub purge_remembered {
 2291:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2292:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2293:     undef(%remembered);
 2294:     undef(%accessed);
 2295: }
 2296: # ------------------------------------- Read an entry from a user's environment
 2297: 
 2298: sub userenvironment {
 2299:     my ($udom,$unam,@what)=@_;
 2300:     my $items;
 2301:     foreach my $item (@what) {
 2302:         $items.=&escape($item).'&';
 2303:     }
 2304:     $items=~s/\&$//;
 2305:     my %returnhash=();
 2306:     my $uhome = &homeserver($unam,$udom);
 2307:     unless ($uhome eq 'no_host') {
 2308:         my @answer=split(/\&/, 
 2309:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2310:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2311:             return %returnhash;
 2312:         }
 2313:         my $i;
 2314:         for ($i=0;$i<=$#what;$i++) {
 2315: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2316:         }
 2317:     }
 2318:     return %returnhash;
 2319: }
 2320: 
 2321: # ---------------------------------------------------------- Get a studentphoto
 2322: sub studentphoto {
 2323:     my ($udom,$unam,$ext) = @_;
 2324:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2325:     if (defined($env{'request.course.id'})) {
 2326:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2327:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2328:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2329:             } else {
 2330:                 my ($result,$perm_reqd)=
 2331: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2332:                 if ($result eq 'ok') {
 2333:                     if (!($perm_reqd eq 'yes')) {
 2334:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2335:                     }
 2336:                 }
 2337:             }
 2338:         }
 2339:     } else {
 2340:         my ($result,$perm_reqd) = 
 2341: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2342:         if ($result eq 'ok') {
 2343:             if (!($perm_reqd eq 'yes')) {
 2344:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2345:             }
 2346:         }
 2347:     }
 2348:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2349: }
 2350: 
 2351: sub retrievestudentphoto {
 2352:     my ($udom,$unam,$ext,$type) = @_;
 2353:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2354:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2355:     if ($ret eq 'ok') {
 2356:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2357:         if ($type eq 'thumbnail') {
 2358:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2359:         }
 2360:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2361:         return $tokenurl;
 2362:     } else {
 2363:         if ($type eq 'thumbnail') {
 2364:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2365:         } else { 
 2366:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2367:         }
 2368:     }
 2369: }
 2370: 
 2371: # -------------------------------------------------------------------- New chat
 2372: 
 2373: sub chatsend {
 2374:     my ($newentry,$anon,$group)=@_;
 2375:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2376:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2377:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2378:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2379: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2380: 		   &escape($newentry)).':'.$group,$chome);
 2381: }
 2382: 
 2383: # ------------------------------------------ Find current version of a resource
 2384: 
 2385: sub getversion {
 2386:     my $fname=&clutter(shift);
 2387:     unless ($fname=~/^\/res\//) { return -1; }
 2388:     return &currentversion(&filelocation('',$fname));
 2389: }
 2390: 
 2391: sub currentversion {
 2392:     my $fname=shift;
 2393:     my $author=$fname;
 2394:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2395:     my ($udom,$uname)=split(/\//,$author);
 2396:     my $home=&homeserver($uname,$udom);
 2397:     if ($home eq 'no_host') { 
 2398:         return -1; 
 2399:     }
 2400:     my $answer=&reply("currentversion:$fname",$home);
 2401:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2402: 	return -1;
 2403:     }
 2404:     return $answer;
 2405: }
 2406: 
 2407: #
 2408: # Return special version number of resource if set by override, empty otherwise
 2409: #
 2410: sub usedversion {
 2411:     my $fname=shift;
 2412:     unless ($fname) { $fname=$env{'request.uri'}; }
 2413:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2414:     if ($urlversion) { return $urlversion; }
 2415:     return '';
 2416: }
 2417: 
 2418: # ----------------------------- Subscribe to a resource, return URL if possible
 2419: 
 2420: sub subscribe {
 2421:     my $fname=shift;
 2422:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2423:     $fname=~s/[\n\r]//g;
 2424:     my $author=$fname;
 2425:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2426:     my ($udom,$uname)=split(/\//,$author);
 2427:     my $home=homeserver($uname,$udom);
 2428:     if ($home eq 'no_host') {
 2429:         return 'not_found';
 2430:     }
 2431:     my $answer=reply("sub:$fname",$home);
 2432:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2433: 	$answer.=' by '.$home;
 2434:     }
 2435:     return $answer;
 2436: }
 2437:     
 2438: # -------------------------------------------------------------- Replicate file
 2439: 
 2440: sub repcopy {
 2441:     my $filename=shift;
 2442:     $filename=~s/\/+/\//g;
 2443:     my $londocroot = $perlvar{'lonDocRoot'};
 2444:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2445:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2446:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2447: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2448: 	return &repcopy_userfile($filename);
 2449:     }
 2450:     $filename=~s/[\n\r]//g;
 2451:     my $transname="$filename.in.transfer";
 2452: # FIXME: this should flock
 2453:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2454:     my $remoteurl=subscribe($filename);
 2455:     if ($remoteurl =~ /^con_lost by/) {
 2456: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2457:            return 'unavailable';
 2458:     } elsif ($remoteurl eq 'not_found') {
 2459: 	   #&logthis("Subscribe returned not_found: $filename");
 2460: 	   return 'not_found';
 2461:     } elsif ($remoteurl =~ /^rejected by/) {
 2462: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2463:            return 'forbidden';
 2464:     } elsif ($remoteurl eq 'directory') {
 2465:            return 'ok';
 2466:     } else {
 2467:         my $author=$filename;
 2468:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2469:         my ($udom,$uname)=split(/\//,$author);
 2470:         my $home=homeserver($uname,$udom);
 2471:         unless ($home eq $perlvar{'lonHostID'}) {
 2472:            my @parts=split(/\//,$filename);
 2473:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2474:            if ($path ne "$londocroot/res") {
 2475:                &logthis("Malconfiguration for replication: $filename");
 2476: 	       return 'bad_request';
 2477:            }
 2478:            my $count;
 2479:            for ($count=5;$count<$#parts;$count++) {
 2480:                $path.="/$parts[$count]";
 2481:                if ((-e $path)!=1) {
 2482: 		   mkdir($path,0777);
 2483:                }
 2484:            }
 2485:            my $ua=new LWP::UserAgent;
 2486:            my $request=new HTTP::Request('GET',"$remoteurl");
 2487:            my $response=$ua->request($request,$transname);
 2488:            if ($response->is_error()) {
 2489: 	       unlink($transname);
 2490:                my $message=$response->status_line;
 2491:                &logthis("<font color=\"blue\">WARNING:"
 2492:                        ." LWP get: $message: $filename</font>");
 2493:                return 'unavailable';
 2494:            } else {
 2495: 	       if ($remoteurl!~/\.meta$/) {
 2496:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2497:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2498:                   if ($mresponse->is_error()) {
 2499: 		      unlink($filename.'.meta');
 2500:                       &logthis(
 2501:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2502:                   }
 2503: 	       }
 2504:                rename($transname,$filename);
 2505:                return 'ok';
 2506:            }
 2507:        }
 2508:     }
 2509: }
 2510: 
 2511: # ------------------------------------------------ Get server side include body
 2512: sub ssi_body {
 2513:     my ($filelink,%form)=@_;
 2514:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2515:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2516:     }
 2517:     my $output='';
 2518:     my $response;
 2519:     if ($filelink=~/^https?\:/) {
 2520:        ($output,$response)=&externalssi($filelink);
 2521:     } else {
 2522:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2523:        $filelink .= 'inhibitmenu=yes';
 2524:        ($output,$response)=&ssi($filelink,%form);
 2525:     }
 2526:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2527:     $output=~s/^.*?\<body[^\>]*\>//si;
 2528:     $output=~s/\<\/body\s*\>.*?$//si;
 2529:     if (wantarray) {
 2530:         return ($output, $response);
 2531:     } else {
 2532:         return $output;
 2533:     }
 2534: }
 2535: 
 2536: # --------------------------------------------------------- Server Side Include
 2537: 
 2538: sub absolute_url {
 2539:     my ($host_name) = @_;
 2540:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2541:     if ($host_name eq '') {
 2542: 	$host_name = $ENV{'SERVER_NAME'};
 2543:     }
 2544:     return $protocol.$host_name;
 2545: }
 2546: 
 2547: #
 2548: #   Server side include.
 2549: # Parameters:
 2550: #  fn     Possibly encrypted resource name/id.
 2551: #  form   Hash that describes how the rendering should be done
 2552: #         and other things.
 2553: # Returns:
 2554: #   Scalar context: The content of the response.
 2555: #   Array context:  2 element list of the content and the full response object.
 2556: #     
 2557: sub ssi {
 2558: 
 2559:     my ($fn,%form)=@_;
 2560:     my $ua=new LWP::UserAgent;
 2561:     my $request;
 2562: 
 2563:     $form{'no_update_last_known'}=1;
 2564:     &Apache::lonenc::check_encrypt(\$fn);
 2565:     if (%form) {
 2566:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2567:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2568:     } else {
 2569:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2570:     }
 2571: 
 2572:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2573:     my $response= $ua->request($request);
 2574:     my $content = Encode::decode_utf8($response->content);
 2575:     if (wantarray) {
 2576: 	return ($content, $response);
 2577:     } else {
 2578: 	return $content;
 2579:     }
 2580: }
 2581: 
 2582: sub externalssi {
 2583:     my ($url)=@_;
 2584:     my $ua=new LWP::UserAgent;
 2585:     my $request=new HTTP::Request('GET',$url);
 2586:     my $response=$ua->request($request);
 2587:     if (wantarray) {
 2588:         return ($response->content, $response);
 2589:     } else {
 2590:         return $response->content;
 2591:     }
 2592: }
 2593: 
 2594: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2595: 
 2596: sub allowuploaded {
 2597:     my ($srcurl,$url)=@_;
 2598:     $url=&clutter(&declutter($url));
 2599:     my $dir=$url;
 2600:     $dir=~s/\/[^\/]+$//;
 2601:     my %httpref=();
 2602:     my $httpurl=&hreflocation('',$url);
 2603:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2604:     &Apache::lonnet::appenv(\%httpref);
 2605: }
 2606: 
 2607: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2608: # input: action, courseID, current domain, intended
 2609: #        path to file, source of file, instruction to parse file for objects,
 2610: #        ref to hash for embedded objects,
 2611: #        ref to hash for codebase of java objects.
 2612: #        reference to scalar to accommodate mime type determined
 2613: #          from File::MMagic if $parser = parse.
 2614: #
 2615: # output: url to file (if action was uploaddoc), 
 2616: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2617: #
 2618: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2619: # course.
 2620: #
 2621: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2622: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2623: #          course's home server.
 2624: #
 2625: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2626: #          be copied from $source (current location) to 
 2627: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2628: #         and will then be copied to
 2629: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2630: #         course's home server.
 2631: #
 2632: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2633: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2634: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2635: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2636: #         in course's home server.
 2637: #
 2638: 
 2639: sub process_coursefile {
 2640:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2641:         $mimetype)=@_;
 2642:     my $fetchresult;
 2643:     my $home=&homeserver($docuname,$docudom);
 2644:     if ($action eq 'propagate') {
 2645:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2646: 			     $home);
 2647:     } else {
 2648:         my $fpath = '';
 2649:         my $fname = $file;
 2650:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2651:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2652:         my $filepath = &build_filepath($fpath);
 2653:         if ($action eq 'copy') {
 2654:             if ($source eq '') {
 2655:                 $fetchresult = 'no source file';
 2656:                 return $fetchresult;
 2657:             } else {
 2658:                 my $destination = $filepath.'/'.$fname;
 2659:                 rename($source,$destination);
 2660:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2661:                                  $home);
 2662:             }
 2663:         } elsif ($action eq 'uploaddoc') {
 2664:             open(my $fh,'>'.$filepath.'/'.$fname);
 2665:             print $fh $env{'form.'.$source};
 2666:             close($fh);
 2667:             if ($parser eq 'parse') {
 2668:                 my $mm = new File::MMagic;
 2669:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2670:                 if ($type eq 'text/html') {
 2671:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2672:                     unless ($parse_result eq 'ok') {
 2673:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2674:                     }
 2675:                 }
 2676:                 if (ref($mimetype)) {
 2677:                     $$mimetype = $type;
 2678:                 } 
 2679:             }
 2680:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2681:                                  $home);
 2682:             if ($fetchresult eq 'ok') {
 2683:                 return '/uploaded/'.$fpath.'/'.$fname;
 2684:             } else {
 2685:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2686:                         ' to host '.$home.': '.$fetchresult);
 2687:                 return '/adm/notfound.html';
 2688:             }
 2689:         }
 2690:     }
 2691:     unless ( $fetchresult eq 'ok') {
 2692:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2693:              ' to host '.$home.': '.$fetchresult);
 2694:     }
 2695:     return $fetchresult;
 2696: }
 2697: 
 2698: sub build_filepath {
 2699:     my ($fpath) = @_;
 2700:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2701:     unless ($fpath eq '') {
 2702:         my @parts=split('/',$fpath);
 2703:         foreach my $part (@parts) {
 2704:             $filepath.= '/'.$part;
 2705:             if ((-e $filepath)!=1) {
 2706:                 mkdir($filepath,0777);
 2707:             }
 2708:         }
 2709:     }
 2710:     return $filepath;
 2711: }
 2712: 
 2713: sub store_edited_file {
 2714:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2715:     my $file = $primary_url;
 2716:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2717:     my $fpath = '';
 2718:     my $fname = $file;
 2719:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2720:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2721:     my $filepath = &build_filepath($fpath);
 2722:     open(my $fh,'>'.$filepath.'/'.$fname);
 2723:     print $fh $content;
 2724:     close($fh);
 2725:     my $home=&homeserver($docuname,$docudom);
 2726:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2727: 			  $home);
 2728:     if ($$fetchresult eq 'ok') {
 2729:         return '/uploaded/'.$fpath.'/'.$fname;
 2730:     } else {
 2731:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2732: 		 ' to host '.$home.': '.$$fetchresult);
 2733:         return '/adm/notfound.html';
 2734:     }
 2735: }
 2736: 
 2737: sub clean_filename {
 2738:     my ($fname,$args)=@_;
 2739: # Replace Windows backslashes by forward slashes
 2740:     $fname=~s/\\/\//g;
 2741:     if (!$args->{'keep_path'}) {
 2742:         # Get rid of everything but the actual filename
 2743: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2744:     }
 2745: # Replace spaces by underscores
 2746:     $fname=~s/\s+/\_/g;
 2747: # Replace all other weird characters by nothing
 2748:     $fname=~s{[^/\w\.\-]}{}g;
 2749: # Replace all .\d. sequences with _\d. so they no longer look like version
 2750: # numbers
 2751:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2752:     return $fname;
 2753: }
 2754: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2755: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2756: # image with the same aspect ratio as the original, but with dimensions which do 
 2757: # not exceed $resizewidth and $resizeheight.
 2758:  
 2759: sub resizeImage {
 2760:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2761:     my $ima = Image::Magick->new;
 2762:     my $resized;
 2763:     if (-e $img_path) {
 2764:         $ima->Read($img_path);
 2765:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2766:             my $width = $ima->Get('width');
 2767:             my $height = $ima->Get('height');
 2768:             if ($width > $resizewidth) {
 2769: 	        my $factor = $width/$resizewidth;
 2770:                 my $newheight = $height/$factor;
 2771:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2772:                 $resized = 1;
 2773:             }
 2774:         }
 2775:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2776:             my $width = $ima->Get('width');
 2777:             my $height = $ima->Get('height');
 2778:             if ($height > $resizeheight) {
 2779:                 my $factor = $height/$resizeheight;
 2780:                 my $newwidth = $width/$factor;
 2781:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2782:                 $resized = 1;
 2783:             }
 2784:         }
 2785:         if ($resized) {
 2786:             $ima->Write($img_path);
 2787:         }
 2788:     }
 2789:     return;
 2790: }
 2791: 
 2792: # --------------- Take an uploaded file and put it into the userfiles directory
 2793: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2794: #                    the desired filename is in $env{"form.$formname.filename"}
 2795: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2796: #                                    canceloverwrite, or ''. 
 2797: #                   if 'coursedoc': upload to the current course
 2798: #                   if 'existingfile': write file to tmp/overwrites directory 
 2799: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2800: #                   $context is passed as argument to &finishuserfileupload
 2801: #        $subdir - directory in userfile to store the file into
 2802: #        $parser - instruction to parse file for objects ($parser = parse)    
 2803: #        $allfiles - reference to hash for embedded objects
 2804: #        $codebase - reference to hash for codebase of java objects
 2805: #        $desuname - username for permanent storage of uploaded file
 2806: #        $dsetudom - domain for permanaent storage of uploaded file
 2807: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2808: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2809: #        $resizewidth - width (pixels) to which to resize uploaded image
 2810: #        $resizeheight - height (pixels) to which to resize uploaded image
 2811: #        $mimetype - reference to scalar to accommodate mime type determined
 2812: #                    from File::MMagic.
 2813: # 
 2814: # output: url of file in userspace, or error: <message> 
 2815: #             or /adm/notfound.html if failure to upload occurse
 2816: 
 2817: sub userfileupload {
 2818:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2819:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2820:     if (!defined($subdir)) { $subdir='unknown'; }
 2821:     my $fname=$env{'form.'.$formname.'.filename'};
 2822:     $fname=&clean_filename($fname);
 2823:     # See if there is anything left
 2824:     unless ($fname) { return 'error: no uploaded file'; }
 2825:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2826:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2827:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2828:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2829:         my $now = time;
 2830:         my $filepath;
 2831:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2832:              $filepath = 'tmp/helprequests/'.$now;
 2833:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2834:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2835:                          '_'.$env{'user.domain'}.'/pending';
 2836:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2837:             my ($docuname,$docudom);
 2838:             if ($destudom) {
 2839:                 $docudom = $destudom;
 2840:             } else {
 2841:                 $docudom = $env{'user.domain'};
 2842:             }
 2843:             if ($destuname) {
 2844:                 $docuname = $destuname;
 2845:             } else {
 2846:                 $docuname = $env{'user.name'};
 2847:             }
 2848:             if (exists($env{'form.group'})) {
 2849:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2850:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2851:             }
 2852:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2853:             if ($context eq 'canceloverwrite') {
 2854:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2855:                 if (-e  $tempfile) {
 2856:                     my @info = stat($tempfile);
 2857:                     if ($info[9] eq $env{'form.timestamp'}) {
 2858:                         unlink($tempfile);
 2859:                     }
 2860:                 }
 2861:                 return;
 2862:             }
 2863:         }
 2864:         # Create the directory if not present
 2865:         my @parts=split(/\//,$filepath);
 2866:         my $fullpath = $perlvar{'lonDaemons'};
 2867:         for (my $i=0;$i<@parts;$i++) {
 2868:             $fullpath .= '/'.$parts[$i];
 2869:             if ((-e $fullpath)!=1) {
 2870:                 mkdir($fullpath,0777);
 2871:             }
 2872:         }
 2873:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2874:         print $fh $env{'form.'.$formname};
 2875:         close($fh);
 2876:         if ($context eq 'existingfile') {
 2877:             my @info = stat($fullpath.'/'.$fname);
 2878:             return ($fullpath.'/'.$fname,$info[9]);
 2879:         } else {
 2880:             return $fullpath.'/'.$fname;
 2881:         }
 2882:     }
 2883:     if ($subdir eq 'scantron') {
 2884:         $fname = 'scantron_orig_'.$fname;
 2885:     } else {
 2886:         $fname="$subdir/$fname";
 2887:     }
 2888:     if ($context eq 'coursedoc') {
 2889: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2890: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2891:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2892:             return &finishuserfileupload($docuname,$docudom,
 2893: 					 $formname,$fname,$parser,$allfiles,
 2894: 					 $codebase,$thumbwidth,$thumbheight,
 2895:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2896:         } else {
 2897:             $fname=$env{'form.folder'}.'/'.$fname;
 2898:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2899: 				       $fname,$formname,$parser,
 2900: 				       $allfiles,$codebase,$mimetype);
 2901:         }
 2902:     } elsif (defined($destuname)) {
 2903:         my $docuname=$destuname;
 2904:         my $docudom=$destudom;
 2905: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2906: 				     $parser,$allfiles,$codebase,
 2907:                                      $thumbwidth,$thumbheight,
 2908:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2909:     } else {
 2910:         my $docuname=$env{'user.name'};
 2911:         my $docudom=$env{'user.domain'};
 2912:         if (exists($env{'form.group'})) {
 2913:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2914:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2915:         }
 2916: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2917: 				     $parser,$allfiles,$codebase,
 2918:                                      $thumbwidth,$thumbheight,
 2919:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2920:     }
 2921: }
 2922: 
 2923: sub finishuserfileupload {
 2924:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2925:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2926:     my $path=$docudom.'/'.$docuname.'/';
 2927:     my $filepath=$perlvar{'lonDocRoot'};
 2928:   
 2929:     my ($fnamepath,$file,$fetchthumb);
 2930:     $file=$fname;
 2931:     if ($fname=~m|/|) {
 2932:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2933: 	$path.=$fnamepath.'/';
 2934:     }
 2935:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2936:     my $count;
 2937:     for ($count=4;$count<=$#parts;$count++) {
 2938:         $filepath.="/$parts[$count]";
 2939:         if ((-e $filepath)!=1) {
 2940: 	    mkdir($filepath,0777);
 2941:         }
 2942:     }
 2943: 
 2944: # Save the file
 2945:     {
 2946: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2947: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2948: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2949: 	    return '/adm/notfound.html';
 2950: 	}
 2951:         if ($context eq 'overwrite') {
 2952:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2953:             my $target = $filepath.'/'.$file;
 2954:             if (-e $source) {
 2955:                 my @info = stat($source);
 2956:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2957:                     unless (&File::Copy::move($source,$target)) {
 2958:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2959:                         return "Moving from $source failed";
 2960:                     }
 2961:                 } else {
 2962:                     return "Temporary file: $source had unexpected date/time for last modification";
 2963:                 }
 2964:             } else {
 2965:                 return "Temporary file: $source missing";
 2966:             }
 2967:         } elsif (!print FH ($env{'form.'.$formname})) {
 2968: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2969: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2970: 	    return '/adm/notfound.html';
 2971: 	}
 2972: 	close(FH);
 2973:         if ($resizewidth && $resizeheight) {
 2974:             my $mm = new File::MMagic;
 2975:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2976:             if ($mime_type =~ m{^image/}) {
 2977: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2978:             }  
 2979: 	}
 2980:     }
 2981:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2982:         if (ref($mimetype)) {
 2983:             if ($$mimetype eq '') {
 2984:                 my $mm = new File::MMagic;
 2985:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2986:                 $$mimetype = $type;
 2987:             }
 2988:         }
 2989:     }
 2990:     if ($parser eq 'parse') {
 2991:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2992:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2993:                                                        $allfiles,$codebase);
 2994:             unless ($parse_result eq 'ok') {
 2995:                 &logthis('Failed to parse '.$filepath.$file.
 2996: 	   	         ' for embedded media: '.$parse_result); 
 2997:             }
 2998:         }
 2999:     }
 3000:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3001:         my $input = $filepath.'/'.$file;
 3002:         my $output = $filepath.'/'.'tn-'.$file;
 3003:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3004:         system("convert -sample $thumbsize $input $output");
 3005:         if (-e $filepath.'/'.'tn-'.$file) {
 3006:             $fetchthumb  = 1; 
 3007:         }
 3008:     }
 3009:  
 3010: # Notify homeserver to grep it
 3011: #
 3012:     my $docuhome=&homeserver($docuname,$docudom);	
 3013:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3014:     if ($fetchresult eq 'ok') {
 3015:         if ($fetchthumb) {
 3016:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3017:             if ($thumbresult ne 'ok') {
 3018:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3019:                          $docuhome.': '.$thumbresult);
 3020:             }
 3021:         }
 3022: #
 3023: # Return the URL to it
 3024:         return '/uploaded/'.$path.$file;
 3025:     } else {
 3026:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3027: 		 ': '.$fetchresult);
 3028:         return '/adm/notfound.html';
 3029:     }
 3030: }
 3031: 
 3032: sub extract_embedded_items {
 3033:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3034:     my @state = ();
 3035:     my (%lastids,%related,%shockwave,%flashvars);
 3036:     my %javafiles = (
 3037:                       codebase => '',
 3038:                       code => '',
 3039:                       archive => ''
 3040:                     );
 3041:     my %mediafiles = (
 3042:                       src => '',
 3043:                       movie => '',
 3044:                      );
 3045:     my $p;
 3046:     if ($content) {
 3047:         $p = HTML::LCParser->new($content);
 3048:     } else {
 3049:         $p = HTML::LCParser->new($fullpath);
 3050:     }
 3051:     while (my $t=$p->get_token()) {
 3052: 	if ($t->[0] eq 'S') {
 3053: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3054: 	    push(@state, $tagname);
 3055:             if (lc($tagname) eq 'allow') {
 3056:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3057:             }
 3058: 	    if (lc($tagname) eq 'img') {
 3059: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3060: 	    }
 3061: 	    if (lc($tagname) eq 'a') {
 3062: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3063: 	    }
 3064:             if (lc($tagname) eq 'script') {
 3065:                 my $src;
 3066:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3067:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3068:                 } else {
 3069:                     if ($attr->{'src'} ne '') {
 3070:                         $src = $attr->{'src'};
 3071:                         &add_filetype($allfiles,$src,'src');
 3072:                     }
 3073:                 }
 3074:                 my $text = $p->get_trimmed_text();
 3075:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3076:                     my @swfargs = split(/,/,$1);
 3077:                     foreach my $item (@swfargs) {
 3078:                         $item =~ s/["']//g;
 3079:                         $item =~ s/^\s+//;
 3080:                         $item =~ s/\s+$//;
 3081:                     }
 3082:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3083:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3084:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3085:                         } else {
 3086:                             $related{$swfargs[0]} = [$swfargs[2]];
 3087:                         }
 3088:                     }
 3089:                 }
 3090:             }
 3091:             if (lc($tagname) eq 'link') {
 3092:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3093:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3094:                 }
 3095:             }
 3096: 	    if (lc($tagname) eq 'object' ||
 3097: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3098: 		foreach my $item (keys(%javafiles)) {
 3099: 		    $javafiles{$item} = '';
 3100: 		}
 3101:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3102:                     $lastids{lc($tagname)} = $attr->{'id'};
 3103:                 }
 3104: 	    }
 3105: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3106: 		my $name = lc($attr->{'name'});
 3107: 		foreach my $item (keys(%javafiles)) {
 3108: 		    if ($name eq $item) {
 3109: 			$javafiles{$item} = $attr->{'value'};
 3110: 			last;
 3111: 		    }
 3112: 		}
 3113:                 my $pathfrom;
 3114: 		foreach my $item (keys(%mediafiles)) {
 3115: 		    if ($name eq $item) {
 3116:                         $pathfrom = $attr->{'value'};
 3117:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3118: 			&add_filetype($allfiles,$pathfrom,$name);
 3119: 			last;
 3120: 		    }
 3121: 		}
 3122:                 if ($name eq 'flashvars') {
 3123:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3124:                 }
 3125:                 if ($pathfrom ne '') {
 3126:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3127:                                          $pathfrom);
 3128:                 }
 3129: 	    }
 3130: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3131: 		foreach my $item (keys(%javafiles)) {
 3132: 		    if ($attr->{$item}) {
 3133: 			$javafiles{$item} = $attr->{$item};
 3134: 			last;
 3135: 		    }
 3136: 		}
 3137: 		foreach my $item (keys(%mediafiles)) {
 3138: 		    if ($attr->{$item}) {
 3139: 			&add_filetype($allfiles,$attr->{$item},$item);
 3140: 			last;
 3141: 		    }
 3142: 		}
 3143:                 if (lc($tagname) eq 'embed') {
 3144:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3145:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3146:                                              $attr->{'src'});
 3147:                     }
 3148:                 }
 3149: 	    }
 3150:             if ($t->[4] =~ m{/>$}) {
 3151:                 pop(@state);  
 3152:             }
 3153: 	} elsif ($t->[0] eq 'E') {
 3154: 	    my ($tagname) = ($t->[1]);
 3155: 	    if ($javafiles{'codebase'} ne '') {
 3156: 		$javafiles{'codebase'} .= '/';
 3157: 	    }  
 3158: 	    if (lc($tagname) eq 'applet' ||
 3159: 		lc($tagname) eq 'object' ||
 3160: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3161: 		) {
 3162: 		foreach my $item (keys(%javafiles)) {
 3163: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3164: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3165: 			&add_filetype($allfiles,$file,$item);
 3166: 		    }
 3167: 		}
 3168: 	    } 
 3169: 	    pop @state;
 3170: 	}
 3171:     }
 3172:     foreach my $id (sort(keys(%flashvars))) {
 3173:         if ($shockwave{$id} ne '') {
 3174:             my @pairs = split(/\&/,$flashvars{$id});
 3175:             foreach my $pair (@pairs) {
 3176:                 my ($key,$value) = split(/\=/,$pair);
 3177:                 if ($key eq 'thumb') {
 3178:                     &add_filetype($allfiles,$value,$key);
 3179:                 } elsif ($key eq 'content') {
 3180:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3181:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3182:                     if ($ext ne '') {
 3183:                         &add_filetype($allfiles,$path.$value,$ext);
 3184:                     }
 3185:                 }
 3186:             }
 3187:         }
 3188:     }
 3189:     return 'ok';
 3190: }
 3191: 
 3192: sub add_filetype {
 3193:     my ($allfiles,$file,$type)=@_;
 3194:     if (exists($allfiles->{$file})) {
 3195: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3196: 	    push(@{$allfiles->{$file}}, &escape($type));
 3197: 	}
 3198:     } else {
 3199: 	@{$allfiles->{$file}} = (&escape($type));
 3200:     }
 3201: }
 3202: 
 3203: sub embedded_dependency {
 3204:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3205:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3206:         if (($identifier ne '') &&
 3207:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3208:             ($pathfrom ne '')) {
 3209:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3210:             foreach my $dep (@{$related->{$identifier}}) {
 3211:                 &add_filetype($allfiles,$path.$dep,'object');
 3212:             }
 3213:         }
 3214:     }
 3215:     return;
 3216: }
 3217: 
 3218: sub removeuploadedurl {
 3219:     my ($url)=@_;	
 3220:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3221:     return &removeuserfile($uname,$udom,$fname);
 3222: }
 3223: 
 3224: sub removeuserfile {
 3225:     my ($docuname,$docudom,$fname)=@_;
 3226:     my $home=&homeserver($docuname,$docudom);    
 3227:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3228:     if ($result eq 'ok') {	
 3229:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3230:             my $metafile = $fname.'.meta';
 3231:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3232: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3233:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3234:             my $sqlresult = 
 3235:                 &update_portfolio_table($docuname,$docudom,$file,
 3236:                                         'portfolio_metadata',$group,
 3237:                                         'delete');
 3238:         }
 3239:     }
 3240:     return $result;
 3241: }
 3242: 
 3243: sub mkdiruserfile {
 3244:     my ($docuname,$docudom,$dir)=@_;
 3245:     my $home=&homeserver($docuname,$docudom);
 3246:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3247: }
 3248: 
 3249: sub renameuserfile {
 3250:     my ($docuname,$docudom,$old,$new)=@_;
 3251:     my $home=&homeserver($docuname,$docudom);
 3252:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3253:                         &escape("$old").':'.&escape("$new"),$home);
 3254:     if ($result eq 'ok') {
 3255:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3256:             my $oldmeta = $old.'.meta';
 3257:             my $newmeta = $new.'.meta';
 3258:             my $metaresult = 
 3259:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3260: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3261:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3262:             my $sqlresult = 
 3263:                 &update_portfolio_table($docuname,$docudom,$file,
 3264:                                         'portfolio_metadata',$group,
 3265:                                         'delete');
 3266:         }
 3267:     }
 3268:     return $result;
 3269: }
 3270: 
 3271: # ------------------------------------------------------------------------- Log
 3272: 
 3273: sub log {
 3274:     my ($dom,$nam,$hom,$what)=@_;
 3275:     return critical("log:$dom:$nam:$what",$hom);
 3276: }
 3277: 
 3278: # ------------------------------------------------------------------ Course Log
 3279: #
 3280: # This routine flushes several buffers of non-mission-critical nature
 3281: #
 3282: 
 3283: sub flushcourselogs {
 3284:     &logthis('Flushing log buffers');
 3285: #
 3286: # course logs
 3287: # This is a log of all transactions in a course, which can be used
 3288: # for data mining purposes
 3289: #
 3290: # It also collects the courseid database, which lists last transaction
 3291: # times and course titles for all courseids
 3292: #
 3293:     my %courseidbuffer=();
 3294:     foreach my $crsid (keys(%courselogs)) {
 3295:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3296: 		          &escape($courselogs{$crsid}),
 3297: 		          $coursehombuf{$crsid}) eq 'ok') {
 3298: 	    delete $courselogs{$crsid};
 3299:         } else {
 3300:             &logthis('Failed to flush log buffer for '.$crsid);
 3301:             if (length($courselogs{$crsid})>40000) {
 3302:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3303:                         " exceeded maximum size, deleting.</font>");
 3304:                delete $courselogs{$crsid};
 3305:             }
 3306:         }
 3307:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3308:             'description' => $coursedescrbuf{$crsid},
 3309:             'inst_code'    => $courseinstcodebuf{$crsid},
 3310:             'type'        => $coursetypebuf{$crsid},
 3311:             'owner'       => $courseownerbuf{$crsid},
 3312:         };
 3313:     }
 3314: #
 3315: # Write course id database (reverse lookup) to homeserver of courses 
 3316: # Is used in pickcourse
 3317: #
 3318:     foreach my $crs_home (keys(%courseidbuffer)) {
 3319:         my $response = &courseidput(&host_domain($crs_home),
 3320:                                     $courseidbuffer{$crs_home},
 3321:                                     $crs_home,'timeonly');
 3322:     }
 3323: #
 3324: # File accesses
 3325: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3326: #
 3327:     foreach my $entry (keys(%accesshash)) {
 3328:         if ($entry =~ /___count$/) {
 3329:             my ($dom,$name);
 3330:             ($dom,$name,undef)=
 3331: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3332:             if (! defined($dom) || $dom eq '' || 
 3333:                 ! defined($name) || $name eq '') {
 3334:                 my $cid = $env{'request.course.id'};
 3335:                 $dom  = $env{'request.'.$cid.'.domain'};
 3336:                 $name = $env{'request.'.$cid.'.num'};
 3337:             }
 3338:             my $value = $accesshash{$entry};
 3339:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3340:             my %temphash=($url => $value);
 3341:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3342:             if ($result eq 'ok') {
 3343:                 delete $accesshash{$entry};
 3344:             }
 3345:         } else {
 3346:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3347:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3348:             my %temphash=($entry => $accesshash{$entry});
 3349:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3350:                 delete $accesshash{$entry};
 3351:             }
 3352:         }
 3353:     }
 3354: #
 3355: # Roles
 3356: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3357: #
 3358:     foreach my $entry (keys(%userrolehash)) {
 3359:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3360: 	    split(/\:/,$entry);
 3361:         if (&Apache::lonnet::put('nohist_userroles',
 3362:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3363:                 $rudom,$runame) eq 'ok') {
 3364: 	    delete $userrolehash{$entry};
 3365:         }
 3366:     }
 3367: #
 3368: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3369: #
 3370:     my %domrolebuffer = ();
 3371:     foreach my $entry (keys(%domainrolehash)) {
 3372:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3373:         if ($domrolebuffer{$rudom}) {
 3374:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3375:                       '='.&escape($domainrolehash{$entry});
 3376:         } else {
 3377:             $domrolebuffer{$rudom}.=&escape($entry).
 3378:                       '='.&escape($domainrolehash{$entry});
 3379:         }
 3380:         delete $domainrolehash{$entry};
 3381:     }
 3382:     foreach my $dom (keys(%domrolebuffer)) {
 3383: 	my %servers = &get_servers($dom,'library');
 3384: 	foreach my $tryserver (keys(%servers)) {
 3385: 	    unless (&reply('domroleput:'.$dom.':'.
 3386: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3387: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3388: 	    }
 3389:         }
 3390:     }
 3391:     $dumpcount++;
 3392: }
 3393: 
 3394: sub courselog {
 3395:     my $what=shift;
 3396:     $what=time.':'.$what;
 3397:     unless ($env{'request.course.id'}) { return ''; }
 3398:     $coursedombuf{$env{'request.course.id'}}=
 3399:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3400:     $coursenumbuf{$env{'request.course.id'}}=
 3401:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3402:     $coursehombuf{$env{'request.course.id'}}=
 3403:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3404:     $coursedescrbuf{$env{'request.course.id'}}=
 3405:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3406:     $courseinstcodebuf{$env{'request.course.id'}}=
 3407:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3408:     $courseownerbuf{$env{'request.course.id'}}=
 3409:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3410:     $coursetypebuf{$env{'request.course.id'}}=
 3411:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3412:     if (defined $courselogs{$env{'request.course.id'}}) {
 3413: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3414:     } else {
 3415: 	$courselogs{$env{'request.course.id'}}.=$what;
 3416:     }
 3417:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3418: 	&flushcourselogs();
 3419:     }
 3420: }
 3421: 
 3422: sub courseacclog {
 3423:     my $fnsymb=shift;
 3424:     unless ($env{'request.course.id'}) { return ''; }
 3425:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3426:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3427:         $what.=':POST';
 3428:         # FIXME: Probably ought to escape things....
 3429: 	foreach my $key (keys(%env)) {
 3430:             if ($key=~/^form\.(.*)/) {
 3431:                 my $formitem = $1;
 3432:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3433:                     $what.=':'.$formitem.'='.$env{$key};
 3434:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3435:                     $what.=':'.$formitem.'='.$env{$key};
 3436:                 }
 3437:             }
 3438:         }
 3439:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3440:         # FIXME: We should not be depending on a form parameter that someone
 3441:         # editing lonsearchcat.pm might change in the future.
 3442:         if ($env{'form.phase'} eq 'course_search') {
 3443:             $what.= ':POST';
 3444:             # FIXME: Probably ought to escape things....
 3445:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3446:                                  'crsdiscuss') {
 3447:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3448:             }
 3449:         }
 3450:     }
 3451:     &courselog($what);
 3452: }
 3453: 
 3454: sub countacc {
 3455:     my $url=&declutter(shift);
 3456:     return if (! defined($url) || $url eq '');
 3457:     unless ($env{'request.course.id'}) { return ''; }
 3458: #
 3459: # Mark that this url was used in this course
 3460: #
 3461:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3462: #
 3463: # Increase the access count for this resource in this child process
 3464: #
 3465:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3466:     $accesshash{$key}++;
 3467: }
 3468: 
 3469: sub linklog {
 3470:     my ($from,$to)=@_;
 3471:     $from=&declutter($from);
 3472:     $to=&declutter($to);
 3473:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3474:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3475: }
 3476: 
 3477: sub statslog {
 3478:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3479:     if ($users<2) { return; }
 3480:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3481:             'course'       => $env{'request.course.id'},
 3482:             'sections'     => '"all"',
 3483:             'num_students' => $users,
 3484:             'part'         => $part,
 3485:             'symb'         => $symb,
 3486:             'mean_tries'   => $av_attempts,
 3487:             'deg_of_diff'  => $degdiff});
 3488:     foreach my $key (keys(%dynstore)) {
 3489:         $accesshash{$key}=$dynstore{$key};
 3490:     }
 3491: }
 3492:   
 3493: sub userrolelog {
 3494:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3495:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3496:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3497:        $userrolehash
 3498:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3499:                     =$tend.':'.$tstart;
 3500:     }
 3501:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3502:        $userrolehash
 3503:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3504:                     =$tend.':'.$tstart;
 3505:     }
 3506:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3507:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3508:        $domainrolehash
 3509:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3510:                     = $tend.':'.$tstart;
 3511:     }
 3512: }
 3513: 
 3514: sub courserolelog {
 3515:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3516:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3517:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3518:         ($trole eq 'ta') || ($trole eq 'st') ||
 3519:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3520:         ($trole eq 'co')) {
 3521:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3522:             my $cdom = $1;
 3523:             my $cnum = $2;
 3524:             my $sec = $3;
 3525:             my $namespace = 'rolelog';
 3526:             my %storehash = (
 3527:                                role    => $trole,
 3528:                                start   => $tstart,
 3529:                                end     => $tend,
 3530:                                selfenroll => $selfenroll,
 3531:                                context    => $context,
 3532:                             );
 3533:             if ($trole eq 'gr') {
 3534:                 $namespace = 'groupslog';
 3535:                 $storehash{'group'} = $sec;
 3536:             } else {
 3537:                 $storehash{'section'} = $sec;
 3538:             }
 3539:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3540:             if (($trole ne 'st') || ($sec ne '')) {
 3541:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3542:             }
 3543:         }
 3544:     }
 3545:     return;
 3546: }
 3547: 
 3548: sub get_course_adv_roles {
 3549:     my ($cid,$codes) = @_;
 3550:     $cid=$env{'request.course.id'} unless (defined($cid));
 3551:     my %coursehash=&coursedescription($cid);
 3552:     my $crstype = &Apache::loncommon::course_type($cid);
 3553:     my %nothide=();
 3554:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3555:         if ($user !~ /:/) {
 3556: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3557:         } else {
 3558:             $nothide{$user}=1;
 3559:         }
 3560:     }
 3561:     my %returnhash=();
 3562:     my %dumphash=
 3563:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3564:     my $now=time;
 3565:     my %privileged;
 3566:     foreach my $entry (keys(%dumphash)) {
 3567: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3568:         if (($tstart) && ($tstart<0)) { next; }
 3569:         if (($tend) && ($tend<$now)) { next; }
 3570:         if (($tstart) && ($now<$tstart)) { next; }
 3571:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3572: 	if ($username eq '' || $domain eq '') { next; }
 3573:         unless (ref($privileged{$domain}) eq 'HASH') {
 3574:             my %dompersonnel =
 3575:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3576:             $privileged{$domain} = {};
 3577:             foreach my $server (keys(%dompersonnel)) {
 3578:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3579:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3580:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3581:                         $privileged{$udom}{$uname} = 1;
 3582:                     }
 3583:                 }
 3584:             }
 3585:         }
 3586:         if ((exists($privileged{$domain}{$username})) && 
 3587:             (!$nothide{$username.':'.$domain})) { next; }
 3588: 	if ($role eq 'cr') { next; }
 3589:         if ($codes) {
 3590:             if ($section) { $role .= ':'.$section; }
 3591:             if ($returnhash{$role}) {
 3592:                 $returnhash{$role}.=','.$username.':'.$domain;
 3593:             } else {
 3594:                 $returnhash{$role}=$username.':'.$domain;
 3595:             }
 3596:         } else {
 3597:             my $key=&plaintext($role,$crstype);
 3598:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3599:             if ($returnhash{$key}) {
 3600: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3601:             } else {
 3602:                 $returnhash{$key}=$username.':'.$domain;
 3603:             }
 3604:         }
 3605:     }
 3606:     return %returnhash;
 3607: }
 3608: 
 3609: sub get_my_roles {
 3610:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3611:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3612:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3613:     my (%dumphash,%nothide);
 3614:     if ($context eq 'userroles') {
 3615:         %dumphash = &dump('roles',$udom,$uname);
 3616:     } else {
 3617:         %dumphash=
 3618:             &dump('nohist_userroles',$udom,$uname);
 3619:         if ($hidepriv) {
 3620:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3621:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3622:                 if ($user !~ /:/) {
 3623:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3624:                 } else {
 3625:                     $nothide{$user} = 1;
 3626:                 }
 3627:             }
 3628:         }
 3629:     }
 3630:     my %returnhash=();
 3631:     my $now=time;
 3632:     my %privileged;
 3633:     foreach my $entry (keys(%dumphash)) {
 3634:         my ($role,$tend,$tstart);
 3635:         if ($context eq 'userroles') {
 3636:             next if ($entry =~ /^rolesdef/);
 3637: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3638:         } else {
 3639:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3640:         }
 3641:         if (($tstart) && ($tstart<0)) { next; }
 3642:         my $status = 'active';
 3643:         if (($tend) && ($tend<=$now)) {
 3644:             $status = 'previous';
 3645:         } 
 3646:         if (($tstart) && ($now<$tstart)) {
 3647:             $status = 'future';
 3648:         }
 3649:         if (ref($types) eq 'ARRAY') {
 3650:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3651:                 next;
 3652:             } 
 3653:         } else {
 3654:             if ($status ne 'active') {
 3655:                 next;
 3656:             }
 3657:         }
 3658:         my ($rolecode,$username,$domain,$section,$area);
 3659:         if ($context eq 'userroles') {
 3660:             ($area,$rolecode) = split(/_/,$entry);
 3661:             (undef,$domain,$username,$section) = split(/\//,$area);
 3662:         } else {
 3663:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3664:         }
 3665:         if (ref($roledoms) eq 'ARRAY') {
 3666:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3667:                 next;
 3668:             }
 3669:         }
 3670:         if (ref($roles) eq 'ARRAY') {
 3671:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3672:                 if ($role =~ /^cr\//) {
 3673:                     if (!grep(/^cr$/,@{$roles})) {
 3674:                         next;
 3675:                     }
 3676:                 } elsif ($role =~ /^gr\//) {
 3677:                     if (!grep(/^gr$/,@{$roles})) {
 3678:                         next;
 3679:                     }
 3680:                 } else {
 3681:                     next;
 3682:                 }
 3683:             }
 3684:         }
 3685:         if ($hidepriv) {
 3686:             if ($context eq 'userroles') {
 3687:                 if ((&privileged($username,$domain)) &&
 3688:                     (!$nothide{$username.':'.$domain})) {
 3689:                     next;
 3690:                 }
 3691:             } else {
 3692:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3693:                     my %dompersonnel =
 3694:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3695:                     $privileged{$domain} = {};
 3696:                     if (keys(%dompersonnel)) {
 3697:                         foreach my $server (keys(%dompersonnel)) {
 3698:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3699:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3700:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3701:                                     $privileged{$udom}{$uname} = $trole;
 3702:                                 }
 3703:                             }
 3704:                         }
 3705:                     }
 3706:                 }
 3707:                 if (exists($privileged{$domain}{$username})) {
 3708:                     if (!$nothide{$username.':'.$domain}) {
 3709:                         next;
 3710:                     }
 3711:                 }
 3712:             }
 3713:         }
 3714:         if ($withsec) {
 3715:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3716:                 $tstart.':'.$tend;
 3717:         } else {
 3718:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3719:         }
 3720:     }
 3721:     return %returnhash;
 3722: }
 3723: 
 3724: # ----------------------------------------------------- Frontpage Announcements
 3725: #
 3726: #
 3727: 
 3728: sub postannounce {
 3729:     my ($server,$text)=@_;
 3730:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3731:     unless ($text=~/\w/) { $text=''; }
 3732:     return &reply('setannounce:'.&escape($text),$server);
 3733: }
 3734: 
 3735: sub getannounce {
 3736: 
 3737:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3738: 	my $announcement='';
 3739: 	while (my $line = <$fh>) { $announcement .= $line; }
 3740: 	close($fh);
 3741: 	if ($announcement=~/\w/) { 
 3742: 	    return 
 3743:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3744:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3745: 	} else {
 3746: 	    return '';
 3747: 	}
 3748:     } else {
 3749: 	return '';
 3750:     }
 3751: }
 3752: 
 3753: # ---------------------------------------------------------- Course ID routines
 3754: # Deal with domain's nohist_courseid.db files
 3755: #
 3756: 
 3757: sub courseidput {
 3758:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3759:     return unless (ref($storehash) eq 'HASH');
 3760:     my $outcome;
 3761:     if ($caller eq 'timeonly') {
 3762:         my $cids = '';
 3763:         foreach my $item (keys(%$storehash)) {
 3764:             $cids.=&escape($item).'&';
 3765:         }
 3766:         $cids=~s/\&$//;
 3767:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3768:                           $coursehome);       
 3769:     } else {
 3770:         my $items = '';
 3771:         foreach my $item (keys(%$storehash)) {
 3772:             $items.= &escape($item).'='.
 3773:                      &freeze_escape($$storehash{$item}).'&';
 3774:         }
 3775:         $items=~s/\&$//;
 3776:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3777:                           $coursehome);
 3778:     }
 3779:     if ($outcome eq 'unknown_cmd') {
 3780:         my $what;
 3781:         foreach my $cid (keys(%$storehash)) {
 3782:             $what .= &escape($cid).'=';
 3783:             foreach my $item ('description','inst_code','owner','type') {
 3784:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3785:             }
 3786:             $what =~ s/\:$/&/;
 3787:         }
 3788:         $what =~ s/\&$//;  
 3789:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3790:     } else {
 3791:         return $outcome;
 3792:     }
 3793: }
 3794: 
 3795: sub courseiddump {
 3796:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3797:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3798:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3799:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3800:     my $as_hash = 1;
 3801:     my %returnhash;
 3802:     if (!$domfilter) { $domfilter=''; }
 3803:     my %libserv = &all_library();
 3804:     foreach my $tryserver (keys(%libserv)) {
 3805:         if ( (  $hostidflag == 1 
 3806: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3807: 	     || (!defined($hostidflag)) ) {
 3808: 
 3809: 	    if (($domfilter eq '') ||
 3810: 		(&host_domain($tryserver) eq $domfilter)) {
 3811:                 my $rep = 
 3812:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3813:                          $sincefilter.':'.&escape($descfilter).':'.
 3814:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3815:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3816:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3817:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3818:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3819:                          &escape($cc_clone).':'.$cloneonly.':'.
 3820:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3821:                          &escape($creationcontext).':'.$domcloner,
 3822:                          $tryserver);
 3823:                 my @pairs=split(/\&/,$rep);
 3824:                 foreach my $item (@pairs) {
 3825:                     my ($key,$value)=split(/\=/,$item,2);
 3826:                     $key = &unescape($key);
 3827:                     next if ($key =~ /^error: 2 /);
 3828:                     my $result = &thaw_unescape($value);
 3829:                     if (ref($result) eq 'HASH') {
 3830:                         $returnhash{$key}=$result;
 3831:                     } else {
 3832:                         my @responses = split(/:/,$value);
 3833:                         my @items = ('description','inst_code','owner','type');
 3834:                         for (my $i=0; $i<@responses; $i++) {
 3835:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3836:                         }
 3837:                     }
 3838:                 }
 3839:             }
 3840:         }
 3841:     }
 3842:     return %returnhash;
 3843: }
 3844: 
 3845: sub courselastaccess {
 3846:     my ($cdom,$cnum,$hostidref) = @_;
 3847:     my %returnhash;
 3848:     if ($cdom && $cnum) {
 3849:         my $chome = &homeserver($cnum,$cdom);
 3850:         if ($chome ne 'no_host') {
 3851:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3852:             &extract_lastaccess(\%returnhash,$rep);
 3853:         }
 3854:     } else {
 3855:         if (!$cdom) { $cdom=''; }
 3856:         my %libserv = &all_library();
 3857:         foreach my $tryserver (keys(%libserv)) {
 3858:             if (ref($hostidref) eq 'ARRAY') {
 3859:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3860:             } 
 3861:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3862:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3863:                 &extract_lastaccess(\%returnhash,$rep);
 3864:             }
 3865:         }
 3866:     }
 3867:     return %returnhash;
 3868: }
 3869: 
 3870: sub extract_lastaccess {
 3871:     my ($returnhash,$rep) = @_;
 3872:     if (ref($returnhash) eq 'HASH') {
 3873:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3874:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3875:                  $rep eq '') {
 3876:             my @pairs=split(/\&/,$rep);
 3877:             foreach my $item (@pairs) {
 3878:                 my ($key,$value)=split(/\=/,$item,2);
 3879:                 $key = &unescape($key);
 3880:                 next if ($key =~ /^error: 2 /);
 3881:                 $returnhash->{$key} = &thaw_unescape($value);
 3882:             }
 3883:         }
 3884:     }
 3885:     return;
 3886: }
 3887: 
 3888: # ---------------------------------------------------------- DC e-mail
 3889: 
 3890: sub dcmailput {
 3891:     my ($domain,$msgid,$message,$server)=@_;
 3892:     my $status = &Apache::lonnet::critical(
 3893:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3894:        &escape($message),$server);
 3895:     return $status;
 3896: }
 3897: 
 3898: sub dcmaildump {
 3899:     my ($dom,$startdate,$enddate,$senders) = @_;
 3900:     my %returnhash=();
 3901: 
 3902:     if (defined(&domain($dom,'primary'))) {
 3903:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3904:                                                          &escape($enddate).':';
 3905: 	my @esc_senders=map { &escape($_)} @$senders;
 3906: 	$cmd.=&escape(join('&',@esc_senders));
 3907: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3908:             my ($key,$value) = split(/\=/,$line,2);
 3909:             if (($key) && ($value)) {
 3910:                 $returnhash{&unescape($key)} = &unescape($value);
 3911:             }
 3912:         }
 3913:     }
 3914:     return %returnhash;
 3915: }
 3916: # ---------------------------------------------------------- Domain roles
 3917: 
 3918: sub get_domain_roles {
 3919:     my ($dom,$roles,$startdate,$enddate)=@_;
 3920:     if ((!defined($startdate)) || ($startdate eq '')) {
 3921:         $startdate = '.';
 3922:     }
 3923:     if ((!defined($enddate)) || ($enddate eq '')) {
 3924:         $enddate = '.';
 3925:     }
 3926:     my $rolelist;
 3927:     if (ref($roles) eq 'ARRAY') {
 3928:         $rolelist = join(':',@{$roles});
 3929:     }
 3930:     my %personnel = ();
 3931: 
 3932:     my %servers = &get_servers($dom,'library');
 3933:     foreach my $tryserver (keys(%servers)) {
 3934: 	%{$personnel{$tryserver}}=();
 3935: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3936: 					    &escape($startdate).':'.
 3937: 					    &escape($enddate).':'.
 3938: 					    &escape($rolelist), $tryserver))) {
 3939: 	    my ($key,$value) = split(/\=/,$line,2);
 3940: 	    if (($key) && ($value)) {
 3941: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3942: 	    }
 3943: 	}
 3944:     }
 3945:     return %personnel;
 3946: }
 3947: 
 3948: # ----------------------------------------------------------- Interval timing 
 3949: 
 3950: {
 3951: # Caches needed for speedup of navmaps
 3952: # We don't want to cache this for very long at all (5 seconds at most)
 3953: # 
 3954: # The user for whom we cache
 3955: my $cachedkey='';
 3956: # The cached times for this user
 3957: my %cachedtimes=();
 3958: # When this was last done
 3959: my $cachedtime=();
 3960: 
 3961: sub load_all_first_access {
 3962:     my ($uname,$udom)=@_;
 3963:     if (($cachedkey eq $uname.':'.$udom) &&
 3964:         (abs($cachedtime-time)<5)) {
 3965:         return;
 3966:     }
 3967:     $cachedtime=time;
 3968:     $cachedkey=$uname.':'.$udom;
 3969:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3970: }
 3971: 
 3972: sub get_first_access {
 3973:     my ($type,$argsymb,$argmap)=@_;
 3974:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3975:     if ($argsymb) { $symb=$argsymb; }
 3976:     my ($map,$id,$res)=&decode_symb($symb);
 3977:     if ($argmap) { $map = $argmap; }
 3978:     if ($type eq 'course') {
 3979: 	$res='course';
 3980:     } elsif ($type eq 'map') {
 3981: 	$res=&symbread($map);
 3982:     } else {
 3983: 	$res=$symb;
 3984:     }
 3985:     &load_all_first_access($uname,$udom);
 3986:     return $cachedtimes{"$courseid\0$res"};
 3987: }
 3988: 
 3989: sub set_first_access {
 3990:     my ($type,$interval)=@_;
 3991:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3992:     my ($map,$id,$res)=&decode_symb($symb);
 3993:     if ($type eq 'course') {
 3994: 	$res='course';
 3995:     } elsif ($type eq 'map') {
 3996: 	$res=&symbread($map);
 3997:     } else {
 3998: 	$res=$symb;
 3999:     }
 4000:     $cachedkey='';
 4001:     my $firstaccess=&get_first_access($type,$symb,$map);
 4002:     if (!$firstaccess) {
 4003:         my $start = time;
 4004: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4005:                           $udom,$uname);
 4006:         if ($putres eq 'ok') {
 4007:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4008:                  $udom,$uname); 
 4009:             &appenv(
 4010:                      {
 4011:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4012:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4013:                      }
 4014:                   );
 4015:         }
 4016:         return $putres;
 4017:     }
 4018:     return 'already_set';
 4019: }
 4020: }
 4021: # --------------------------------------------- Set Expire Date for Spreadsheet
 4022: 
 4023: sub expirespread {
 4024:     my ($uname,$udom,$stype,$usymb)=@_;
 4025:     my $cid=$env{'request.course.id'}; 
 4026:     if ($cid) {
 4027:        my $now=time;
 4028:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4029:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4030:                             $env{'course.'.$cid.'.num'}.
 4031: 	        	    ':nohist_expirationdates:'.
 4032:                             &escape($key).'='.$now,
 4033:                             $env{'course.'.$cid.'.home'})
 4034:     }
 4035:     return 'ok';
 4036: }
 4037: 
 4038: # ----------------------------------------------------- Devalidate Spreadsheets
 4039: 
 4040: sub devalidate {
 4041:     my ($symb,$uname,$udom)=@_;
 4042:     my $cid=$env{'request.course.id'}; 
 4043:     if ($cid) {
 4044:         # delete the stored spreadsheets for
 4045:         # - the student level sheet of this user in course's homespace
 4046:         # - the assessment level sheet for this resource 
 4047:         #   for this user in user's homespace
 4048: 	# - current conditional state info
 4049: 	my $key=$uname.':'.$udom.':';
 4050:         my $status=
 4051: 	    &del('nohist_calculatedsheets',
 4052: 		 [$key.'studentcalc:'],
 4053: 		 $env{'course.'.$cid.'.domain'},
 4054: 		 $env{'course.'.$cid.'.num'})
 4055: 		.' '.
 4056: 	    &del('nohist_calculatedsheets_'.$cid,
 4057: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4058:         unless ($status eq 'ok ok') {
 4059:            &logthis('Could not devalidate spreadsheet '.
 4060:                     $uname.' at '.$udom.' for '.
 4061: 		    $symb.': '.$status);
 4062:         }
 4063: 	&delenv('user.state.'.$cid);
 4064:     }
 4065: }
 4066: 
 4067: sub get_scalar {
 4068:     my ($string,$end) = @_;
 4069:     my $value;
 4070:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4071: 	$value = $1;
 4072:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4073: 	$value = $1;
 4074:     }
 4075:     return &unescape($value);
 4076: }
 4077: 
 4078: sub array2str {
 4079:   my (@array) = @_;
 4080:   my $result=&arrayref2str(\@array);
 4081:   $result=~s/^__ARRAY_REF__//;
 4082:   $result=~s/__END_ARRAY_REF__$//;
 4083:   return $result;
 4084: }
 4085: 
 4086: sub arrayref2str {
 4087:   my ($arrayref) = @_;
 4088:   my $result='__ARRAY_REF__';
 4089:   foreach my $elem (@$arrayref) {
 4090:     if(ref($elem) eq 'ARRAY') {
 4091:       $result.=&arrayref2str($elem).'&';
 4092:     } elsif(ref($elem) eq 'HASH') {
 4093:       $result.=&hashref2str($elem).'&';
 4094:     } elsif(ref($elem)) {
 4095:       #print("Got a ref of ".(ref($elem))." skipping.");
 4096:     } else {
 4097:       $result.=&escape($elem).'&';
 4098:     }
 4099:   }
 4100:   $result=~s/\&$//;
 4101:   $result .= '__END_ARRAY_REF__';
 4102:   return $result;
 4103: }
 4104: 
 4105: sub hash2str {
 4106:   my (%hash) = @_;
 4107:   my $result=&hashref2str(\%hash);
 4108:   $result=~s/^__HASH_REF__//;
 4109:   $result=~s/__END_HASH_REF__$//;
 4110:   return $result;
 4111: }
 4112: 
 4113: sub hashref2str {
 4114:   my ($hashref)=@_;
 4115:   my $result='__HASH_REF__';
 4116:   foreach my $key (sort(keys(%$hashref))) {
 4117:     if (ref($key) eq 'ARRAY') {
 4118:       $result.=&arrayref2str($key).'=';
 4119:     } elsif (ref($key) eq 'HASH') {
 4120:       $result.=&hashref2str($key).'=';
 4121:     } elsif (ref($key)) {
 4122:       $result.='=';
 4123:       #print("Got a ref of ".(ref($key))." skipping.");
 4124:     } else {
 4125: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4126:     }
 4127: 
 4128:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4129:       $result.=&arrayref2str($hashref->{$key}).'&';
 4130:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4131:       $result.=&hashref2str($hashref->{$key}).'&';
 4132:     } elsif(ref($hashref->{$key})) {
 4133:        $result.='&';
 4134:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4135:     } else {
 4136:       $result.=&escape($hashref->{$key}).'&';
 4137:     }
 4138:   }
 4139:   $result=~s/\&$//;
 4140:   $result .= '__END_HASH_REF__';
 4141:   return $result;
 4142: }
 4143: 
 4144: sub str2hash {
 4145:     my ($string)=@_;
 4146:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4147:     return %$hash;
 4148: }
 4149: 
 4150: sub str2hashref {
 4151:   my ($string) = @_;
 4152: 
 4153:   my %hash;
 4154: 
 4155:   if($string !~ /^__HASH_REF__/) {
 4156:       if (! ($string eq '' || !defined($string))) {
 4157: 	  $hash{'error'}='Not hash reference';
 4158:       }
 4159:       return (\%hash, $string);
 4160:   }
 4161: 
 4162:   $string =~ s/^__HASH_REF__//;
 4163: 
 4164:   while($string !~ /^__END_HASH_REF__/) {
 4165:       #key
 4166:       my $key='';
 4167:       if($string =~ /^__HASH_REF__/) {
 4168:           ($key, $string)=&str2hashref($string);
 4169:           if(defined($key->{'error'})) {
 4170:               $hash{'error'}='Bad data';
 4171:               return (\%hash, $string);
 4172:           }
 4173:       } elsif($string =~ /^__ARRAY_REF__/) {
 4174:           ($key, $string)=&str2arrayref($string);
 4175:           if($key->[0] eq 'Array reference error') {
 4176:               $hash{'error'}='Bad data';
 4177:               return (\%hash, $string);
 4178:           }
 4179:       } else {
 4180:           $string =~ s/^(.*?)=//;
 4181: 	  $key=&unescape($1);
 4182:       }
 4183:       $string =~ s/^=//;
 4184: 
 4185:       #value
 4186:       my $value='';
 4187:       if($string =~ /^__HASH_REF__/) {
 4188:           ($value, $string)=&str2hashref($string);
 4189:           if(defined($value->{'error'})) {
 4190:               $hash{'error'}='Bad data';
 4191:               return (\%hash, $string);
 4192:           }
 4193:       } elsif($string =~ /^__ARRAY_REF__/) {
 4194:           ($value, $string)=&str2arrayref($string);
 4195:           if($value->[0] eq 'Array reference error') {
 4196:               $hash{'error'}='Bad data';
 4197:               return (\%hash, $string);
 4198:           }
 4199:       } else {
 4200: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4201:       }
 4202:       $string =~ s/^&//;
 4203: 
 4204:       $hash{$key}=$value;
 4205:   }
 4206: 
 4207:   $string =~ s/^__END_HASH_REF__//;
 4208: 
 4209:   return (\%hash, $string);
 4210: }
 4211: 
 4212: sub str2array {
 4213:     my ($string)=@_;
 4214:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4215:     return @$array;
 4216: }
 4217: 
 4218: sub str2arrayref {
 4219:   my ($string) = @_;
 4220:   my @array;
 4221: 
 4222:   if($string !~ /^__ARRAY_REF__/) {
 4223:       if (! ($string eq '' || !defined($string))) {
 4224: 	  $array[0]='Array reference error';
 4225:       }
 4226:       return (\@array, $string);
 4227:   }
 4228: 
 4229:   $string =~ s/^__ARRAY_REF__//;
 4230: 
 4231:   while($string !~ /^__END_ARRAY_REF__/) {
 4232:       my $value='';
 4233:       if($string =~ /^__HASH_REF__/) {
 4234:           ($value, $string)=&str2hashref($string);
 4235:           if(defined($value->{'error'})) {
 4236:               $array[0] ='Array reference error';
 4237:               return (\@array, $string);
 4238:           }
 4239:       } elsif($string =~ /^__ARRAY_REF__/) {
 4240:           ($value, $string)=&str2arrayref($string);
 4241:           if($value->[0] eq 'Array reference error') {
 4242:               $array[0] ='Array reference error';
 4243:               return (\@array, $string);
 4244:           }
 4245:       } else {
 4246: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4247:       }
 4248:       $string =~ s/^&//;
 4249: 
 4250:       push(@array, $value);
 4251:   }
 4252: 
 4253:   $string =~ s/^__END_ARRAY_REF__//;
 4254: 
 4255:   return (\@array, $string);
 4256: }
 4257: 
 4258: # -------------------------------------------------------------------Temp Store
 4259: 
 4260: sub tmpreset {
 4261:   my ($symb,$namespace,$domain,$stuname) = @_;
 4262:   if (!$symb) {
 4263:     $symb=&symbread();
 4264:     if (!$symb) { $symb= $env{'request.url'}; }
 4265:   }
 4266:   $symb=escape($symb);
 4267: 
 4268:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4269:   $namespace=~s/\//\_/g;
 4270:   $namespace=~s/\W//g;
 4271: 
 4272:   if (!$domain) { $domain=$env{'user.domain'}; }
 4273:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4274:   if ($domain eq 'public' && $stuname eq 'public') {
 4275:       $stuname=$ENV{'REMOTE_ADDR'};
 4276:   }
 4277:   my $path=LONCAPA::tempdir();
 4278:   my %hash;
 4279:   if (tie(%hash,'GDBM_File',
 4280: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4281: 	  &GDBM_WRCREAT(),0640)) {
 4282:     foreach my $key (keys(%hash)) {
 4283:       if ($key=~ /:$symb/) {
 4284: 	delete($hash{$key});
 4285:       }
 4286:     }
 4287:   }
 4288: }
 4289: 
 4290: sub tmpstore {
 4291:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4292: 
 4293:   if (!$symb) {
 4294:     $symb=&symbread();
 4295:     if (!$symb) { $symb= $env{'request.url'}; }
 4296:   }
 4297:   $symb=escape($symb);
 4298: 
 4299:   if (!$namespace) {
 4300:     # I don't think we would ever want to store this for a course.
 4301:     # it seems this will only be used if we don't have a course.
 4302:     #$namespace=$env{'request.course.id'};
 4303:     #if (!$namespace) {
 4304:       $namespace=$env{'request.state'};
 4305:     #}
 4306:   }
 4307:   $namespace=~s/\//\_/g;
 4308:   $namespace=~s/\W//g;
 4309:   if (!$domain) { $domain=$env{'user.domain'}; }
 4310:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4311:   if ($domain eq 'public' && $stuname eq 'public') {
 4312:       $stuname=$ENV{'REMOTE_ADDR'};
 4313:   }
 4314:   my $now=time;
 4315:   my %hash;
 4316:   my $path=LONCAPA::tempdir();
 4317:   if (tie(%hash,'GDBM_File',
 4318: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4319: 	  &GDBM_WRCREAT(),0640)) {
 4320:     $hash{"version:$symb"}++;
 4321:     my $version=$hash{"version:$symb"};
 4322:     my $allkeys=''; 
 4323:     foreach my $key (keys(%$storehash)) {
 4324:       $allkeys.=$key.':';
 4325:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4326:     }
 4327:     $hash{"$version:$symb:timestamp"}=$now;
 4328:     $allkeys.='timestamp';
 4329:     $hash{"$version:keys:$symb"}=$allkeys;
 4330:     if (untie(%hash)) {
 4331:       return 'ok';
 4332:     } else {
 4333:       return "error:$!";
 4334:     }
 4335:   } else {
 4336:     return "error:$!";
 4337:   }
 4338: }
 4339: 
 4340: # -----------------------------------------------------------------Temp Restore
 4341: 
 4342: sub tmprestore {
 4343:   my ($symb,$namespace,$domain,$stuname) = @_;
 4344: 
 4345:   if (!$symb) {
 4346:     $symb=&symbread();
 4347:     if (!$symb) { $symb= $env{'request.url'}; }
 4348:   }
 4349:   $symb=escape($symb);
 4350: 
 4351:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4352: 
 4353:   if (!$domain) { $domain=$env{'user.domain'}; }
 4354:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4355:   if ($domain eq 'public' && $stuname eq 'public') {
 4356:       $stuname=$ENV{'REMOTE_ADDR'};
 4357:   }
 4358:   my %returnhash;
 4359:   $namespace=~s/\//\_/g;
 4360:   $namespace=~s/\W//g;
 4361:   my %hash;
 4362:   my $path=LONCAPA::tempdir();
 4363:   if (tie(%hash,'GDBM_File',
 4364: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4365: 	  &GDBM_READER(),0640)) {
 4366:     my $version=$hash{"version:$symb"};
 4367:     $returnhash{'version'}=$version;
 4368:     my $scope;
 4369:     for ($scope=1;$scope<=$version;$scope++) {
 4370:       my $vkeys=$hash{"$scope:keys:$symb"};
 4371:       my @keys=split(/:/,$vkeys);
 4372:       my $key;
 4373:       $returnhash{"$scope:keys"}=$vkeys;
 4374:       foreach $key (@keys) {
 4375: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4376: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4377:       }
 4378:     }
 4379:     if (!(untie(%hash))) {
 4380:       return "error:$!";
 4381:     }
 4382:   } else {
 4383:     return "error:$!";
 4384:   }
 4385:   return %returnhash;
 4386: }
 4387: 
 4388: # ----------------------------------------------------------------------- Store
 4389: 
 4390: sub store {
 4391:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4392:     my $home='';
 4393: 
 4394:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4395: 
 4396:     $symb=&symbclean($symb);
 4397:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4398: 
 4399:     if (!$domain) { $domain=$env{'user.domain'}; }
 4400:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4401: 
 4402:     &devalidate($symb,$stuname,$domain);
 4403: 
 4404:     $symb=escape($symb);
 4405:     if (!$namespace) { 
 4406:        unless ($namespace=$env{'request.course.id'}) { 
 4407:           return ''; 
 4408:        } 
 4409:     }
 4410:     if (!$home) { $home=$env{'user.home'}; }
 4411: 
 4412:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4413:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4414: 
 4415:     my $namevalue='';
 4416:     foreach my $key (keys(%$storehash)) {
 4417:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4418:     }
 4419:     $namevalue=~s/\&$//;
 4420:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4421:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4422: }
 4423: 
 4424: # -------------------------------------------------------------- Critical Store
 4425: 
 4426: sub cstore {
 4427:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4428:     my $home='';
 4429: 
 4430:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4431: 
 4432:     $symb=&symbclean($symb);
 4433:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4434: 
 4435:     if (!$domain) { $domain=$env{'user.domain'}; }
 4436:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4437: 
 4438:     &devalidate($symb,$stuname,$domain);
 4439: 
 4440:     $symb=escape($symb);
 4441:     if (!$namespace) { 
 4442:        unless ($namespace=$env{'request.course.id'}) { 
 4443:           return ''; 
 4444:        } 
 4445:     }
 4446:     if (!$home) { $home=$env{'user.home'}; }
 4447: 
 4448:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4449:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4450: 
 4451:     my $namevalue='';
 4452:     foreach my $key (keys(%$storehash)) {
 4453:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4454:     }
 4455:     $namevalue=~s/\&$//;
 4456:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4457:     return critical
 4458:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4459: }
 4460: 
 4461: # --------------------------------------------------------------------- Restore
 4462: 
 4463: sub restore {
 4464:     my ($symb,$namespace,$domain,$stuname) = @_;
 4465:     my $home='';
 4466: 
 4467:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4468: 
 4469:     if (!$symb) {
 4470:       unless ($symb=escape(&symbread())) { return ''; }
 4471:     } else {
 4472:       $symb=&escape(&symbclean($symb));
 4473:     }
 4474:     if (!$namespace) { 
 4475:        unless ($namespace=$env{'request.course.id'}) { 
 4476:           return ''; 
 4477:        } 
 4478:     }
 4479:     if (!$domain) { $domain=$env{'user.domain'}; }
 4480:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4481:     if (!$home) { $home=$env{'user.home'}; }
 4482:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4483: 
 4484:     my %returnhash=();
 4485:     foreach my $line (split(/\&/,$answer)) {
 4486: 	my ($name,$value)=split(/\=/,$line);
 4487:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4488:     }
 4489:     my $version;
 4490:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4491:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4492:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4493:        }
 4494:     }
 4495:     return %returnhash;
 4496: }
 4497: 
 4498: # ---------------------------------------------------------- Course Description
 4499: #
 4500: #  
 4501: 
 4502: sub coursedescription {
 4503:     my ($courseid,$args)=@_;
 4504:     $courseid=~s/^\///;
 4505:     $courseid=~s/\_/\//g;
 4506:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4507:     my $chome=&homeserver($cnum,$cdomain);
 4508:     my $normalid=$cdomain.'_'.$cnum;
 4509:     # need to always cache even if we get errors otherwise we keep 
 4510:     # trying and trying and trying to get the course description.
 4511:     my %envhash=();
 4512:     my %returnhash=();
 4513:     
 4514:     my $expiretime=600;
 4515:     if ($env{'request.course.id'} eq $normalid) {
 4516: 	$expiretime=120;
 4517:     }
 4518: 
 4519:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4520:     if (!$args->{'freshen_cache'}
 4521: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4522: 	foreach my $key (keys(%env)) {
 4523: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4524: 	    my ($setting) = $1;
 4525: 	    $returnhash{$setting} = $env{$key};
 4526: 	}
 4527: 	return %returnhash;
 4528:     }
 4529: 
 4530:     # get the data again
 4531: 
 4532:     if (!$args->{'one_time'}) {
 4533: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4534:     }
 4535: 
 4536:     if ($chome ne 'no_host') {
 4537:        %returnhash=&dump('environment',$cdomain,$cnum);
 4538:        if (!exists($returnhash{'con_lost'})) {
 4539: 	   my $username = $env{'user.name'}; # Defult username
 4540: 	   if(defined $args->{'user'}) {
 4541: 	       $username = $args->{'user'};
 4542: 	   }
 4543:            $returnhash{'home'}= $chome;
 4544: 	   $returnhash{'domain'} = $cdomain;
 4545: 	   $returnhash{'num'} = $cnum;
 4546:            if (!defined($returnhash{'type'})) {
 4547:                $returnhash{'type'} = 'Course';
 4548:            }
 4549:            while (my ($name,$value) = each %returnhash) {
 4550:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4551:            }
 4552:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4553:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4554: 	       $username.'_'.$cdomain.'_'.$cnum;
 4555:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4556:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4557:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4558:        }
 4559:     }
 4560:     if (!$args->{'one_time'}) {
 4561: 	&appenv(\%envhash);
 4562:     }
 4563:     return %returnhash;
 4564: }
 4565: 
 4566: sub update_released_required {
 4567:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4568:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4569:         $cid = $env{'request.course.id'};
 4570:         $cdom = $env{'course.'.$cid.'.domain'};
 4571:         $cnum = $env{'course.'.$cid.'.num'};
 4572:         $chome = $env{'course.'.$cid.'.home'};
 4573:     }
 4574:     if ($needsrelease) {
 4575:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4576:         my $needsupdate;
 4577:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4578:             $needsupdate = 1;
 4579:         } else {
 4580:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4581:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4582:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4583:                 $needsupdate = 1;
 4584:             }
 4585:         }
 4586:         if ($needsupdate) {
 4587:             my %needshash = (
 4588:                              'internal.releaserequired' => $needsrelease,
 4589:                             );
 4590:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4591:             if ($putresult eq 'ok') {
 4592:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4593:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4594:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4595:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4596:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4597:                 }
 4598:             }
 4599:         }
 4600:     }
 4601:     return;
 4602: }
 4603: 
 4604: # -------------------------------------------------See if a user is privileged
 4605: 
 4606: sub privileged {
 4607:     my ($username,$domain)=@_;
 4608: 
 4609:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4610:     my $now = time;
 4611: 
 4612:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4613:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4614:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4615:                 return 1 unless ($tend && $tend < $now) 
 4616:                     or ($tstart && $tstart > $now);
 4617:             }
 4618: 	}
 4619: 
 4620:     return 0;
 4621: }
 4622: 
 4623: # -------------------------------------------------------- Get user privileges
 4624: 
 4625: sub rolesinit {
 4626:     my ($domain, $username) = @_;
 4627:     my %userroles = ('user.login.time' => time);
 4628:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4629: 
 4630:     # firstaccess and timerinterval are related to timed maps/resources. 
 4631:     # also, blocking can be triggered by an activating timer
 4632:     # it's saved in the user's %env.
 4633:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4634:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4635:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4636:         %timerintchk, %timerintenv);
 4637: 
 4638:     foreach my $key (keys(%firstaccess)) {
 4639:         my ($cid, $rest) = split(/\0/, $key);
 4640:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4641:     }
 4642: 
 4643:     foreach my $key (keys(%timerinterval)) {
 4644:         my ($cid,$rest) = split(/\0/,$key);
 4645:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4646:     }
 4647: 
 4648:     my %allroles=();
 4649:     my %allgroups=();
 4650: 
 4651:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4652:         my $role = $rolesdump{$area};
 4653:         $area =~ s/\_\w\w$//;
 4654: 
 4655:         my ($trole, $tend, $tstart, $group_privs);
 4656: 
 4657:         if ($role =~ /^cr/) {
 4658:         # Custom role, defined by a user 
 4659:         # e.g., user.role.cr/msu/smith/mynewrole
 4660:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4661:                 $trole = $1;
 4662:                 ($tend, $tstart) = split('_', $2);
 4663:             } else {
 4664:                 $trole = $role;
 4665:             }
 4666:         } elsif ($role =~ m|^gr/|) {
 4667:         # Role of member in a group, defined within a course/community
 4668:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4669:             ($trole, $tend, $tstart) = split(/_/, $role);
 4670:             next if $tstart eq '-1';
 4671:             ($trole, $group_privs) = split(/\//, $trole);
 4672:             $group_privs = &unescape($group_privs);
 4673:         } else {
 4674:         # Just a normal role, defined in roles.tab
 4675:             ($trole, $tend, $tstart) = split(/_/,$role);
 4676:         }
 4677: 
 4678:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4679:                  $username);
 4680:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4681: 
 4682:         # role expired or not available yet?
 4683:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4684:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4685: 
 4686:         next if $area eq '' or $trole eq '';
 4687: 
 4688:         my $spec = "$trole.$area";
 4689:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4690: 
 4691:         if ($trole =~ /^cr\//) {
 4692:         # Custom role, defined by a user
 4693:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4694:         } elsif ($trole eq 'gr') {
 4695:         # Role of a member in a group, defined within a course/community
 4696:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4697:             next;
 4698:         } else {
 4699:         # Normal role, defined in roles.tab
 4700:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4701:         }
 4702: 
 4703:         my $cid = $tdomain.'_'.$trest;
 4704:         unless ($firstaccchk{$cid}) {
 4705:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4706:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4707:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4708:                         $coursetimerstarts{$cid}{$item}; 
 4709:                 }
 4710:             }
 4711:             $firstaccchk{$cid} = 1;
 4712:         }
 4713:         unless ($timerintchk{$cid}) {
 4714:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4715:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4716:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4717:                        $coursetimerintervals{$cid}{$item};
 4718:                 }
 4719:             }
 4720:             $timerintchk{$cid} = 1;
 4721:         }
 4722:     }
 4723: 
 4724:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 4725:         \%allroles, \%allgroups);
 4726:     $env{'user.adv'} = $userroles{'user.adv'};
 4727: 
 4728:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4729: }
 4730: 
 4731: sub set_arearole {
 4732:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4733: # log the associated role with the area
 4734:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4735:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4736: }
 4737: 
 4738: sub custom_roleprivs {
 4739:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4740:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4741:     my $homsvr=homeserver($rauthor,$rdomain);
 4742:     if (&hostname($homsvr) ne '') {
 4743:         my ($rdummy,$roledef)=
 4744:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4745:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4746:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4747:             if (defined($syspriv)) {
 4748:                 if ($trest =~ /^$match_community$/) {
 4749:                     $syspriv =~ s/bre\&S//; 
 4750:                 }
 4751:                 $$allroles{'cm./'}.=':'.$syspriv;
 4752:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4753:             }
 4754:             if ($tdomain ne '') {
 4755:                 if (defined($dompriv)) {
 4756:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4757:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4758:                 }
 4759:                 if (($trest ne '') && (defined($coursepriv))) {
 4760:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4761:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4762:                 }
 4763:             }
 4764:         }
 4765:     }
 4766: }
 4767: 
 4768: sub group_roleprivs {
 4769:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4770:     my $access = 1;
 4771:     my $now = time;
 4772:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4773:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4774:     if ($access) {
 4775:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4776:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4777:     }
 4778: }
 4779: 
 4780: sub standard_roleprivs {
 4781:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4782:     if (defined($pr{$trole.':s'})) {
 4783:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4784:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4785:     }
 4786:     if ($tdomain ne '') {
 4787:         if (defined($pr{$trole.':d'})) {
 4788:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4789:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4790:         }
 4791:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4792:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4793:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4794:         }
 4795:     }
 4796: }
 4797: 
 4798: sub set_userprivs {
 4799:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4800:     my $author=0;
 4801:     my $adv=0;
 4802:     my %grouproles = ();
 4803:     if (keys(%{$allgroups}) > 0) {
 4804:         my @groupkeys; 
 4805:         foreach my $role (keys(%{$allroles})) {
 4806:             push(@groupkeys,$role);
 4807:         }
 4808:         if (ref($groups_roles) eq 'HASH') {
 4809:             foreach my $key (keys(%{$groups_roles})) {
 4810:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4811:                     push(@groupkeys,$key);
 4812:                 }
 4813:             }
 4814:         }
 4815:         if (@groupkeys > 0) {
 4816:             foreach my $role (@groupkeys) {
 4817:                 my ($trole,$area,$sec,$extendedarea);
 4818:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4819:                     $trole = $1;
 4820:                     $area = $2;
 4821:                     $sec = $3;
 4822:                     $extendedarea = $area.$sec;
 4823:                     if (exists($$allgroups{$area})) {
 4824:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4825:                             my $spec = $trole.'.'.$extendedarea;
 4826:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4827:                                                 $$allgroups{$area}{$group};
 4828:                         }
 4829:                     }
 4830:                 }
 4831:             }
 4832:         }
 4833:     }
 4834:     foreach my $group (keys(%grouproles)) {
 4835:         $$allroles{$group} = $grouproles{$group};
 4836:     }
 4837:     foreach my $role (keys(%{$allroles})) {
 4838:         my %thesepriv;
 4839:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4840:         foreach my $item (split(/:/,$$allroles{$role})) {
 4841:             if ($item ne '') {
 4842:                 my ($privilege,$restrictions)=split(/&/,$item);
 4843:                 if ($restrictions eq '') {
 4844:                     $thesepriv{$privilege}='F';
 4845:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4846:                     $thesepriv{$privilege}.=$restrictions;
 4847:                 }
 4848:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4849:             }
 4850:         }
 4851:         my $thesestr='';
 4852:         foreach my $priv (sort(keys(%thesepriv))) {
 4853: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4854: 	}
 4855:         $userroles->{'user.priv.'.$role} = $thesestr;
 4856:     }
 4857:     return ($author,$adv);
 4858: }
 4859: 
 4860: sub role_status {
 4861:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4862:     my @pwhere = ();
 4863:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4864:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4865:         unless (!defined($$role) || $$role eq '') {
 4866:             $$where=join('.',@pwhere);
 4867:             $$trolecode=$$role.'.'.$$where;
 4868:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4869:             $$tstatus='is';
 4870:             if ($$tstart && $$tstart>$update) {
 4871:                 $$tstatus='future';
 4872:                 if ($$tstart<$now) {
 4873:                     if ($$tstart && $$tstart>$refresh) {
 4874:                         if (($$where ne '') && ($$role ne '')) {
 4875:                             my (%allroles,%allgroups,$group_privs,
 4876:                                 %groups_roles,@rolecodes);
 4877:                             my %userroles = (
 4878:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4879:                             );
 4880:                             @rolecodes = ('cm'); 
 4881:                             my $spec=$$role.'.'.$$where;
 4882:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4883:                             if ($$role =~ /^cr\//) {
 4884:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4885:                                 push(@rolecodes,'cr');
 4886:                             } elsif ($$role eq 'gr') {
 4887:                                 push(@rolecodes,$$role);
 4888:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4889:                                                     $env{'user.name'});
 4890:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4891:                                 (undef,my $group_privs) = split(/\//,$trole);
 4892:                                 $group_privs = &unescape($group_privs);
 4893:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4894:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4895:                                 &get_groups_roles($tdomain,$trest,
 4896:                                                   \%course_roles,\@rolecodes,
 4897:                                                   \%groups_roles);
 4898:                             } else {
 4899:                                 push(@rolecodes,$$role);
 4900:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4901:                             }
 4902:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4903:                             &appenv(\%userroles,\@rolecodes);
 4904:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4905:                         }
 4906:                     }
 4907:                     $$tstatus = 'is';
 4908:                 }
 4909:             }
 4910:             if ($$tend) {
 4911:                 if ($$tend<$update) {
 4912:                     $$tstatus='expired';
 4913:                 } elsif ($$tend<$now) {
 4914:                     $$tstatus='will_not';
 4915:                 }
 4916:             }
 4917:         }
 4918:     }
 4919: }
 4920: 
 4921: sub get_groups_roles {
 4922:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4923:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4924:                   (ref($rolecodes) eq 'ARRAY') && 
 4925:                   (ref($groups_roles) eq 'HASH')); 
 4926:     if (keys(%{$cdom_courseroles}) > 0) {
 4927:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4928:         if ($cdom ne '' && $cnum ne '') {
 4929:             foreach my $key (keys(%{$cdom_courseroles})) {
 4930:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4931:                     my $crsrole = $1;
 4932:                     my $crssec = $2;
 4933:                     if ($crsrole =~ /^cr/) {
 4934:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4935:                             push(@{$rolecodes},'cr');
 4936:                         }
 4937:                     } else {
 4938:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4939:                             push(@{$rolecodes},$crsrole);
 4940:                         }
 4941:                     }
 4942:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4943:                     if ($crssec ne '') {
 4944:                         $rolekey .= "/$crssec";
 4945:                     }
 4946:                     $rolekey .= './';
 4947:                     $groups_roles->{$rolekey} = $rolecodes;
 4948:                 }
 4949:             }
 4950:         }
 4951:     }
 4952:     return;
 4953: }
 4954: 
 4955: sub delete_env_groupprivs {
 4956:     my ($where,$courseroles,$possroles) = @_;
 4957:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4958:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4959:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4960:         %{$courseroles->{$udom}} =
 4961:             &get_my_roles('','','userroles',['active'],
 4962:                           $possroles,[$udom],1);
 4963:     }
 4964:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4965:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4966:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4967:             my $area = '/'.$cdom.'/'.$cnum;
 4968:             my $privkey = "user.priv.$crsrole.$area";
 4969:             if ($crssec ne '') {
 4970:                 $privkey .= '/'.$crssec;
 4971:             }
 4972:             $privkey .= ".$area/$group";
 4973:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4974:         }
 4975:     }
 4976:     return;
 4977: }
 4978: 
 4979: sub check_adhoc_privs {
 4980:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4981:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4982:     if ($env{$cckey}) {
 4983:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4984:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4985:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4986:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4987:         }
 4988:     } else {
 4989:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4990:     }
 4991: }
 4992: 
 4993: sub set_adhoc_privileges {
 4994: # role can be cc or ca
 4995:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4996:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4997:     my $spec = $role.'.'.$area;
 4998:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4999:                                   $env{'user.name'});
 5000:     my %ccrole = ();
 5001:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5002:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5003:     &appenv(\%userroles,[$role,'cm']);
 5004:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5005:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5006:         &appenv( {'request.role'        => $spec,
 5007:                   'request.role.domain' => $dcdom,
 5008:                   'request.course.sec'  => ''
 5009:                  }
 5010:                );
 5011:         my $tadv=0;
 5012:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5013:         &appenv({'request.role.adv'    => $tadv});
 5014:     }
 5015: }
 5016: 
 5017: # --------------------------------------------------------------- get interface
 5018: 
 5019: sub get {
 5020:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5021:    my $items='';
 5022:    foreach my $item (@$storearr) {
 5023:        $items.=&escape($item).'&';
 5024:    }
 5025:    $items=~s/\&$//;
 5026:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5027:    if (!$uname) { $uname=$env{'user.name'}; }
 5028:    my $uhome=&homeserver($uname,$udomain);
 5029: 
 5030:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5031:    my @pairs=split(/\&/,$rep);
 5032:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5033:      return @pairs;
 5034:    }
 5035:    my %returnhash=();
 5036:    my $i=0;
 5037:    foreach my $item (@$storearr) {
 5038:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5039:       $i++;
 5040:    }
 5041:    return %returnhash;
 5042: }
 5043: 
 5044: # --------------------------------------------------------------- del interface
 5045: 
 5046: sub del {
 5047:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5048:    my $items='';
 5049:    foreach my $item (@$storearr) {
 5050:        $items.=&escape($item).'&';
 5051:    }
 5052: 
 5053:    $items=~s/\&$//;
 5054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5055:    if (!$uname) { $uname=$env{'user.name'}; }
 5056:    my $uhome=&homeserver($uname,$udomain);
 5057:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5058: }
 5059: 
 5060: # -------------------------------------------------------------- dump interface
 5061: 
 5062: sub dump {
 5063:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5064:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5065:     if (!$uname) { $uname=$env{'user.name'}; }
 5066:     my $uhome=&homeserver($uname,$udomain);
 5067: 
 5068:     if ($regexp) {
 5069: 	$regexp=&escape($regexp);
 5070:     } else {
 5071: 	$regexp='.';
 5072:     }
 5073:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5074:     my @pairs=split(/\&/,$rep);
 5075:     my %returnhash=();
 5076:     if (!($rep =~ /^error/ )) {
 5077: 	foreach my $item (@pairs) {
 5078: 	    my ($key,$value)=split(/=/,$item,2);
 5079: 	    $key = &unescape($key);
 5080: 	    next if ($key =~ /^error: 2 /);
 5081: 	    $returnhash{$key}=&thaw_unescape($value);
 5082: 	}
 5083:     }
 5084:     return %returnhash;
 5085: }
 5086: 
 5087: 
 5088: # --------------------------------------------------------- dumpstore interface
 5089: 
 5090: sub dumpstore {
 5091:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5093:    if (!$uname) { $uname=$env{'user.name'}; }
 5094:    my $uhome=&homeserver($uname,$udomain);
 5095:    if ($regexp) {
 5096:        $regexp=&escape($regexp);
 5097:    } else {
 5098:        $regexp='.';
 5099:    }
 5100:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5101:    my @pairs=split(/\&/,$rep);
 5102:    my %returnhash=();
 5103:    foreach my $item (@pairs) {
 5104:        my ($key,$value)=split(/=/,$item,2);
 5105:        next if ($key =~ /^error: 2 /);
 5106:        $returnhash{$key}=&thaw_unescape($value);
 5107:    }
 5108:    return %returnhash;
 5109: }
 5110: 
 5111: # -------------------------------------------------------------- keys interface
 5112: 
 5113: sub getkeys {
 5114:    my ($namespace,$udomain,$uname)=@_;
 5115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5116:    if (!$uname) { $uname=$env{'user.name'}; }
 5117:    my $uhome=&homeserver($uname,$udomain);
 5118:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5119:    my @keyarray=();
 5120:    foreach my $key (split(/\&/,$rep)) {
 5121:       next if ($key =~ /^error: 2 /);
 5122:       push(@keyarray,&unescape($key));
 5123:    }
 5124:    return @keyarray;
 5125: }
 5126: 
 5127: # --------------------------------------------------------------- currentdump
 5128: sub currentdump {
 5129:    my ($courseid,$sdom,$sname)=@_;
 5130:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5131:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5132:    $sname    = $env{'user.name'}         if (! defined($sname));
 5133:    my $uhome = &homeserver($sname,$sdom);
 5134:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5135:    return if ($rep =~ /^(error:|no_such_host)/);
 5136:    #
 5137:    my %returnhash=();
 5138:    #
 5139:    if ($rep eq "unknown_cmd") { 
 5140:        # an old lond will not know currentdump
 5141:        # Do a dump and make it look like a currentdump
 5142:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5143:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5144:        my %hash = @tmp;
 5145:        @tmp=();
 5146:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5147:    } else {
 5148:        my @pairs=split(/\&/,$rep);
 5149:        foreach my $pair (@pairs) {
 5150:            my ($key,$value)=split(/=/,$pair,2);
 5151:            my ($symb,$param) = split(/:/,$key);
 5152:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5153:                                                         &thaw_unescape($value);
 5154:        }
 5155:    }
 5156:    return %returnhash;
 5157: }
 5158: 
 5159: sub convert_dump_to_currentdump{
 5160:     my %hash = %{shift()};
 5161:     my %returnhash;
 5162:     # Code ripped from lond, essentially.  The only difference
 5163:     # here is the unescaping done by lonnet::dump().  Conceivably
 5164:     # we might run in to problems with parameter names =~ /^v\./
 5165:     while (my ($key,$value) = each(%hash)) {
 5166:         my ($v,$symb,$param) = split(/:/,$key);
 5167: 	$symb  = &unescape($symb);
 5168: 	$param = &unescape($param);
 5169:         next if ($v eq 'version' || $symb eq 'keys');
 5170:         next if (exists($returnhash{$symb}) &&
 5171:                  exists($returnhash{$symb}->{$param}) &&
 5172:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5173:         $returnhash{$symb}->{$param}=$value;
 5174:         $returnhash{$symb}->{'v.'.$param}=$v;
 5175:     }
 5176:     #
 5177:     # Remove all of the keys in the hashes which keep track of
 5178:     # the version of the parameter.
 5179:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5180:         # use a foreach because we are going to delete from the hash.
 5181:         foreach my $key (keys(%$param_hash)) {
 5182:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5183:         }
 5184:     }
 5185:     return \%returnhash;
 5186: }
 5187: 
 5188: # ------------------------------------------------------ critical inc interface
 5189: 
 5190: sub cinc {
 5191:     return &inc(@_,'critical');
 5192: }
 5193: 
 5194: # --------------------------------------------------------------- inc interface
 5195: 
 5196: sub inc {
 5197:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5198:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5199:     if (!$uname) { $uname=$env{'user.name'}; }
 5200:     my $uhome=&homeserver($uname,$udomain);
 5201:     my $items='';
 5202:     if (! ref($store)) {
 5203:         # got a single value, so use that instead
 5204:         $items = &escape($store).'=&';
 5205:     } elsif (ref($store) eq 'SCALAR') {
 5206:         $items = &escape($$store).'=&';        
 5207:     } elsif (ref($store) eq 'ARRAY') {
 5208:         $items = join('=&',map {&escape($_);} @{$store});
 5209:     } elsif (ref($store) eq 'HASH') {
 5210:         while (my($key,$value) = each(%{$store})) {
 5211:             $items.= &escape($key).'='.&escape($value).'&';
 5212:         }
 5213:     }
 5214:     $items=~s/\&$//;
 5215:     if ($critical) {
 5216: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5217:     } else {
 5218: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5219:     }
 5220: }
 5221: 
 5222: # --------------------------------------------------------------- put interface
 5223: 
 5224: sub put {
 5225:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5226:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5227:    if (!$uname) { $uname=$env{'user.name'}; }
 5228:    my $uhome=&homeserver($uname,$udomain);
 5229:    my $items='';
 5230:    foreach my $item (keys(%$storehash)) {
 5231:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5232:    }
 5233:    $items=~s/\&$//;
 5234:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5235: }
 5236: 
 5237: # ------------------------------------------------------------ newput interface
 5238: 
 5239: sub newput {
 5240:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5241:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5242:    if (!$uname) { $uname=$env{'user.name'}; }
 5243:    my $uhome=&homeserver($uname,$udomain);
 5244:    my $items='';
 5245:    foreach my $key (keys(%$storehash)) {
 5246:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5247:    }
 5248:    $items=~s/\&$//;
 5249:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5250: }
 5251: 
 5252: # ---------------------------------------------------------  putstore interface
 5253: 
 5254: sub putstore {
 5255:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5256:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5257:    if (!$uname) { $uname=$env{'user.name'}; }
 5258:    my $uhome=&homeserver($uname,$udomain);
 5259:    my $items='';
 5260:    foreach my $key (keys(%$storehash)) {
 5261:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5262:    }
 5263:    $items=~s/\&$//;
 5264:    my $esc_symb=&escape($symb);
 5265:    my $esc_v=&escape($version);
 5266:    my $reply =
 5267:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5268: 	      $uhome);
 5269:    if ($reply eq 'unknown_cmd') {
 5270:        # gfall back to way things use to be done
 5271:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5272: 			    $uname);
 5273:    }
 5274:    return $reply;
 5275: }
 5276: 
 5277: sub old_putstore {
 5278:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5279:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5280:     if (!$uname) { $uname=$env{'user.name'}; }
 5281:     my $uhome=&homeserver($uname,$udomain);
 5282:     my %newstorehash;
 5283:     foreach my $item (keys(%$storehash)) {
 5284: 	my $key = $version.':'.&escape($symb).':'.$item;
 5285: 	$newstorehash{$key} = $storehash->{$item};
 5286:     }
 5287:     my $items='';
 5288:     my %allitems = ();
 5289:     foreach my $item (keys(%newstorehash)) {
 5290: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5291: 	    my $key = $1.':keys:'.$2;
 5292: 	    $allitems{$key} .= $3.':';
 5293: 	}
 5294: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5295:     }
 5296:     foreach my $item (keys(%allitems)) {
 5297: 	$allitems{$item} =~ s/\:$//;
 5298: 	$items.= $item.'='.$allitems{$item}.'&';
 5299:     }
 5300:     $items=~s/\&$//;
 5301:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5302: }
 5303: 
 5304: # ------------------------------------------------------ critical put interface
 5305: 
 5306: sub cput {
 5307:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5308:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5309:    if (!$uname) { $uname=$env{'user.name'}; }
 5310:    my $uhome=&homeserver($uname,$udomain);
 5311:    my $items='';
 5312:    foreach my $item (keys(%$storehash)) {
 5313:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5314:    }
 5315:    $items=~s/\&$//;
 5316:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5317: }
 5318: 
 5319: # -------------------------------------------------------------- eget interface
 5320: 
 5321: sub eget {
 5322:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5323:    my $items='';
 5324:    foreach my $item (@$storearr) {
 5325:        $items.=&escape($item).'&';
 5326:    }
 5327:    $items=~s/\&$//;
 5328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5329:    if (!$uname) { $uname=$env{'user.name'}; }
 5330:    my $uhome=&homeserver($uname,$udomain);
 5331:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5332:    my @pairs=split(/\&/,$rep);
 5333:    my %returnhash=();
 5334:    my $i=0;
 5335:    foreach my $item (@$storearr) {
 5336:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5337:       $i++;
 5338:    }
 5339:    return %returnhash;
 5340: }
 5341: 
 5342: # ------------------------------------------------------------ tmpput interface
 5343: sub tmpput {
 5344:     my ($storehash,$server,$context)=@_;
 5345:     my $items='';
 5346:     foreach my $item (keys(%$storehash)) {
 5347: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5348:     }
 5349:     $items=~s/\&$//;
 5350:     if (defined($context)) {
 5351:         $items .= ':'.&escape($context);
 5352:     }
 5353:     return &reply("tmpput:$items",$server);
 5354: }
 5355: 
 5356: # ------------------------------------------------------------ tmpget interface
 5357: sub tmpget {
 5358:     my ($token,$server)=@_;
 5359:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5360:     my $rep=&reply("tmpget:$token",$server);
 5361:     my %returnhash;
 5362:     foreach my $item (split(/\&/,$rep)) {
 5363: 	my ($key,$value)=split(/=/,$item);
 5364:         next if ($key =~ /^error: 2 /);
 5365: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5366:     }
 5367:     return %returnhash;
 5368: }
 5369: 
 5370: # ------------------------------------------------------------ tmpdel interface
 5371: sub tmpdel {
 5372:     my ($token,$server)=@_;
 5373:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5374:     return &reply("tmpdel:$token",$server);
 5375: }
 5376: 
 5377: # -------------------------------------------------- portfolio access checking
 5378: 
 5379: sub portfolio_access {
 5380:     my ($requrl) = @_;
 5381:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5382:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5383:     if ($result) {
 5384:         my %setters;
 5385:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5386:             my ($startblock,$endblock) =
 5387:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5388:             if ($startblock && $endblock) {
 5389:                 return 'B';
 5390:             }
 5391:         } else {
 5392:             my ($startblock,$endblock) =
 5393:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5394:             if ($startblock && $endblock) {
 5395:                 return 'B';
 5396:             }
 5397:         }
 5398:     }
 5399:     if ($result eq 'ok') {
 5400:        return 'F';
 5401:     } elsif ($result =~ /^[^:]+:guest_/) {
 5402:        return 'A';
 5403:     }
 5404:     return '';
 5405: }
 5406: 
 5407: sub get_portfolio_access {
 5408:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5409: 
 5410:     if (!ref($access_hash)) {
 5411: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5412: 	my %access_controls = &get_access_controls($current_perms,$group,
 5413: 						   $file_name);
 5414: 	$access_hash = $access_controls{$file_name};
 5415:     }
 5416: 
 5417:     my ($public,$guest,@domains,@users,@courses,@groups);
 5418:     my $now = time;
 5419:     if (ref($access_hash) eq 'HASH') {
 5420:         foreach my $key (keys(%{$access_hash})) {
 5421:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5422:             if ($start > $now) {
 5423:                 next;
 5424:             }
 5425:             if ($end && $end<$now) {
 5426:                 next;
 5427:             }
 5428:             if ($scope eq 'public') {
 5429:                 $public = $key;
 5430:                 last;
 5431:             } elsif ($scope eq 'guest') {
 5432:                 $guest = $key;
 5433:             } elsif ($scope eq 'domains') {
 5434:                 push(@domains,$key);
 5435:             } elsif ($scope eq 'users') {
 5436:                 push(@users,$key);
 5437:             } elsif ($scope eq 'course') {
 5438:                 push(@courses,$key);
 5439:             } elsif ($scope eq 'group') {
 5440:                 push(@groups,$key);
 5441:             }
 5442:         }
 5443:         if ($public) {
 5444:             return 'ok';
 5445:         }
 5446:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5447:             if ($guest) {
 5448:                 return $guest;
 5449:             }
 5450:         } else {
 5451:             if (@domains > 0) {
 5452:                 foreach my $domkey (@domains) {
 5453:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5454:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5455:                             return 'ok';
 5456:                         }
 5457:                     }
 5458:                 }
 5459:             }
 5460:             if (@users > 0) {
 5461:                 foreach my $userkey (@users) {
 5462:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5463:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5464:                             if (ref($item) eq 'HASH') {
 5465:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5466:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5467:                                     return 'ok';
 5468:                                 }
 5469:                             }
 5470:                         }
 5471:                     } 
 5472:                 }
 5473:             }
 5474:             my %roleshash;
 5475:             my @courses_and_groups = @courses;
 5476:             push(@courses_and_groups,@groups); 
 5477:             if (@courses_and_groups > 0) {
 5478:                 my (%allgroups,%allroles); 
 5479:                 my ($start,$end,$role,$sec,$group);
 5480:                 foreach my $envkey (%env) {
 5481:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5482:                         my $cid = $2.'_'.$3; 
 5483:                         if ($1 eq 'gr') {
 5484:                             $group = $4;
 5485:                             $allgroups{$cid}{$group} = $env{$envkey};
 5486:                         } else {
 5487:                             if ($4 eq '') {
 5488:                                 $sec = 'none';
 5489:                             } else {
 5490:                                 $sec = $4;
 5491:                             }
 5492:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5493:                         }
 5494:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5495:                         my $cid = $2.'_'.$3;
 5496:                         if ($4 eq '') {
 5497:                             $sec = 'none';
 5498:                         } else {
 5499:                             $sec = $4;
 5500:                         }
 5501:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5502:                     }
 5503:                 }
 5504:                 if (keys(%allroles) == 0) {
 5505:                     return;
 5506:                 }
 5507:                 foreach my $key (@courses_and_groups) {
 5508:                     my %content = %{$$access_hash{$key}};
 5509:                     my $cnum = $content{'number'};
 5510:                     my $cdom = $content{'domain'};
 5511:                     my $cid = $cdom.'_'.$cnum;
 5512:                     if (!exists($allroles{$cid})) {
 5513:                         next;
 5514:                     }    
 5515:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5516:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5517:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5518:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5519:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5520:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5521:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5522:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5523:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5524:                                         if (grep/^all$/,@sections) {
 5525:                                             return 'ok';
 5526:                                         } else {
 5527:                                             if (grep/^$sec$/,@sections) {
 5528:                                                 return 'ok';
 5529:                                             }
 5530:                                         }
 5531:                                     }
 5532:                                 }
 5533:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5534:                                     if (grep/^none$/,@groups) {
 5535:                                         return 'ok';
 5536:                                     }
 5537:                                 } else {
 5538:                                     if (grep/^all$/,@groups) {
 5539:                                         return 'ok';
 5540:                                     } 
 5541:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5542:                                         if (grep/^$group$/,@groups) {
 5543:                                             return 'ok';
 5544:                                         }
 5545:                                     }
 5546:                                 } 
 5547:                             }
 5548:                         }
 5549:                     }
 5550:                 }
 5551:             }
 5552:             if ($guest) {
 5553:                 return $guest;
 5554:             }
 5555:         }
 5556:     }
 5557:     return;
 5558: }
 5559: 
 5560: sub course_group_datechecker {
 5561:     my ($dates,$now,$status) = @_;
 5562:     my ($start,$end) = split(/\./,$dates);
 5563:     if (!$start && !$end) {
 5564:         return 'ok';
 5565:     }
 5566:     if (grep/^active$/,@{$status}) {
 5567:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5568:             return 'ok';
 5569:         }
 5570:     }
 5571:     if (grep/^previous$/,@{$status}) {
 5572:         if ($end > $now ) {
 5573:             return 'ok';
 5574:         }
 5575:     }
 5576:     if (grep/^future$/,@{$status}) {
 5577:         if ($start > $now) {
 5578:             return 'ok';
 5579:         }
 5580:     }
 5581:     return; 
 5582: }
 5583: 
 5584: sub parse_portfolio_url {
 5585:     my ($url) = @_;
 5586: 
 5587:     my ($type,$udom,$unum,$group,$file_name);
 5588:     
 5589:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5590: 	$type = 1;
 5591:         $udom = $1;
 5592:         $unum = $2;
 5593:         $file_name = $3;
 5594:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5595: 	$type = 2;
 5596:         $udom = $1;
 5597:         $unum = $2;
 5598:         $group = $3;
 5599:         $file_name = $3.'/'.$4;
 5600:     }
 5601:     if (wantarray) {
 5602: 	return ($type,$udom,$unum,$file_name,$group);
 5603:     }
 5604:     return $type;
 5605: }
 5606: 
 5607: sub is_portfolio_url {
 5608:     my ($url) = @_;
 5609:     return scalar(&parse_portfolio_url($url));
 5610: }
 5611: 
 5612: sub is_portfolio_file {
 5613:     my ($file) = @_;
 5614:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5615:         return 1;
 5616:     }
 5617:     return;
 5618: }
 5619: 
 5620: sub usertools_access {
 5621:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5622:     my ($access,%tools);
 5623:     if ($context eq '') {
 5624:         $context = 'tools';
 5625:     }
 5626:     if ($context eq 'requestcourses') {
 5627:         %tools = (
 5628:                       official   => 1,
 5629:                       unofficial => 1,
 5630:                       community  => 1,
 5631:                  );
 5632:     } else {
 5633:         %tools = (
 5634:                       aboutme   => 1,
 5635:                       blog      => 1,
 5636:                       portfolio => 1,
 5637:                  );
 5638:     }
 5639:     return if (!defined($tools{$tool}));
 5640: 
 5641:     if ((!defined($udom)) || (!defined($uname))) {
 5642:         $udom = $env{'user.domain'};
 5643:         $uname = $env{'user.name'};
 5644:     }
 5645: 
 5646:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5647:         if ($action ne 'reload') {
 5648:             if ($context eq 'requestcourses') {
 5649:                 return $env{'environment.canrequest.'.$tool};
 5650:             } else {
 5651:                 return $env{'environment.availabletools.'.$tool};
 5652:             }
 5653:         }
 5654:     }
 5655: 
 5656:     my ($toolstatus,$inststatus);
 5657: 
 5658:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5659:          ($action ne 'reload')) {
 5660:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5661:         $inststatus = $env{'environment.inststatus'};
 5662:     } else {
 5663:         if (ref($userenvref) eq 'HASH') {
 5664:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5665:             $inststatus = $userenvref->{'inststatus'};
 5666:         } else {
 5667:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5668:             $toolstatus = $userenv{$context.'.'.$tool};
 5669:             $inststatus = $userenv{'inststatus'};
 5670:         }
 5671:     }
 5672: 
 5673:     if ($toolstatus ne '') {
 5674:         if ($toolstatus) {
 5675:             $access = 1;
 5676:         } else {
 5677:             $access = 0;
 5678:         }
 5679:         return $access;
 5680:     }
 5681: 
 5682:     my ($is_adv,%domdef);
 5683:     if (ref($is_advref) eq 'HASH') {
 5684:         $is_adv = $is_advref->{'is_adv'};
 5685:     } else {
 5686:         $is_adv = &is_advanced_user($udom,$uname);
 5687:     }
 5688:     if (ref($domdefref) eq 'HASH') {
 5689:         %domdef = %{$domdefref};
 5690:     } else {
 5691:         %domdef = &get_domain_defaults($udom);
 5692:     }
 5693:     if (ref($domdef{$tool}) eq 'HASH') {
 5694:         if ($is_adv) {
 5695:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5696:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5697:                     $access = 1;
 5698:                 } else {
 5699:                     $access = 0;
 5700:                 }
 5701:                 return $access;
 5702:             }
 5703:         }
 5704:         if ($inststatus ne '') {
 5705:             my ($hasaccess,$hasnoaccess);
 5706:             foreach my $affiliation (split(/:/,$inststatus)) {
 5707:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5708:                     if ($domdef{$tool}{$affiliation}) {
 5709:                         $hasaccess = 1;
 5710:                     } else {
 5711:                         $hasnoaccess = 1;
 5712:                     }
 5713:                 }
 5714:             }
 5715:             if ($hasaccess || $hasnoaccess) {
 5716:                 if ($hasaccess) {
 5717:                     $access = 1;
 5718:                 } elsif ($hasnoaccess) {
 5719:                     $access = 0; 
 5720:                 }
 5721:                 return $access;
 5722:             }
 5723:         } else {
 5724:             if ($domdef{$tool}{'default'} ne '') {
 5725:                 if ($domdef{$tool}{'default'}) {
 5726:                     $access = 1;
 5727:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5728:                     $access = 0;
 5729:                 }
 5730:                 return $access;
 5731:             }
 5732:         }
 5733:     } else {
 5734:         if ($context eq 'tools') {
 5735:             $access = 1;
 5736:         } else {
 5737:             $access = 0;
 5738:         }
 5739:         return $access;
 5740:     }
 5741: }
 5742: 
 5743: sub is_course_owner {
 5744:     my ($cdom,$cnum,$udom,$uname) = @_;
 5745:     if (($udom eq '') || ($uname eq '')) {
 5746:         $udom = $env{'user.domain'};
 5747:         $uname = $env{'user.name'};
 5748:     }
 5749:     unless (($udom eq '') || ($uname eq '')) {
 5750:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5751:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5752:                 return 1;
 5753:             } else {
 5754:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5755:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5756:                     return 1;
 5757:                 }
 5758:             }
 5759:         }
 5760:     }
 5761:     return;
 5762: }
 5763: 
 5764: sub is_advanced_user {
 5765:     my ($udom,$uname) = @_;
 5766:     if ($udom ne '' && $uname ne '') {
 5767:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5768:             if (wantarray) {
 5769:                 return ($env{'user.adv'},$env{'user.author'});
 5770:             } else {
 5771:                 return $env{'user.adv'};
 5772:             }
 5773:         }
 5774:     }
 5775:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5776:     my %allroles;
 5777:     my ($is_adv,$is_author);
 5778:     foreach my $role (keys(%roleshash)) {
 5779:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5780:         my $area = '/'.$tdomain.'/'.$trest;
 5781:         if ($sec ne '') {
 5782:             $area .= '/'.$sec;
 5783:         }
 5784:         if (($area ne '') && ($trole ne '')) {
 5785:             my $spec=$trole.'.'.$area;
 5786:             if ($trole =~ /^cr\//) {
 5787:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5788:             } elsif ($trole ne 'gr') {
 5789:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5790:             }
 5791:             if ($trole eq 'au') {
 5792:                 $is_author = 1;
 5793:             }
 5794:         }
 5795:     }
 5796:     foreach my $role (keys(%allroles)) {
 5797:         last if ($is_adv);
 5798:         foreach my $item (split(/:/,$allroles{$role})) {
 5799:             if ($item ne '') {
 5800:                 my ($privilege,$restrictions)=split(/&/,$item);
 5801:                 if ($privilege eq 'adv') {
 5802:                     $is_adv = 1;
 5803:                     last;
 5804:                 }
 5805:             }
 5806:         }
 5807:     }
 5808:     if (wantarray) {
 5809:         return ($is_adv,$is_author);
 5810:     }
 5811:     return $is_adv;
 5812: }
 5813: 
 5814: sub check_can_request {
 5815:     my ($dom,$can_request,$request_domains) = @_;
 5816:     my $canreq = 0;
 5817:     my ($types,$typename) = &Apache::loncommon::course_types();
 5818:     my @options = ('approval','validate','autolimit');
 5819:     my $optregex = join('|',@options);
 5820:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5821:         foreach my $type (@{$types}) {
 5822:             if (&usertools_access($env{'user.name'},
 5823:                                   $env{'user.domain'},
 5824:                                   $type,undef,'requestcourses')) {
 5825:                 $canreq ++;
 5826:                 if (ref($request_domains) eq 'HASH') {
 5827:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5828:                 }
 5829:                 if ($dom eq $env{'user.domain'}) {
 5830:                     $can_request->{$type} = 1;
 5831:                 }
 5832:             }
 5833:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5834:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5835:                 if (@curr > 0) {
 5836:                     foreach my $item (@curr) {
 5837:                         if (ref($request_domains) eq 'HASH') {
 5838:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5839:                             if ($otherdom ne '') {
 5840:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5841:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5842:                                         push(@{$request_domains->{$type}},$otherdom);
 5843:                                     }
 5844:                                 } else {
 5845:                                     push(@{$request_domains->{$type}},$otherdom);
 5846:                                 }
 5847:                             }
 5848:                         }
 5849:                     }
 5850:                     unless($dom eq $env{'user.domain'}) {
 5851:                         $canreq ++;
 5852:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5853:                             $can_request->{$type} = 1;
 5854:                         }
 5855:                     }
 5856:                 }
 5857:             }
 5858:         }
 5859:     }
 5860:     return $canreq;
 5861: }
 5862: 
 5863: # ---------------------------------------------- Custom access rule evaluation
 5864: 
 5865: sub customaccess {
 5866:     my ($priv,$uri)=@_;
 5867:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5868:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5869:     $udom = &LONCAPA::clean_domain($udom);
 5870:     $ucrs = &LONCAPA::clean_username($ucrs);
 5871:     my $access=0;
 5872:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5873: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5874: 	if ($type eq 'user') {
 5875: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5876: 		my ($tdom,$tuname)=split(m{/},$scope);
 5877: 		if ($tdom) {
 5878: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5879: 		}
 5880: 		if ($tuname) {
 5881: 		    if ($tuname ne $env{'user.name'}) { next; }
 5882: 		}
 5883: 		$access=($effect eq 'allow');
 5884: 		last;
 5885: 	    }
 5886: 	} else {
 5887: 	    if ($role) {
 5888: 		if ($role ne $urole) { next; }
 5889: 	    }
 5890: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5891: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5892: 		if ($tdom) {
 5893: 		    if ($tdom ne $udom) { next; }
 5894: 		}
 5895: 		if ($tcrs) {
 5896: 		    if ($tcrs ne $ucrs) { next; }
 5897: 		}
 5898: 		if ($tsec) {
 5899: 		    if ($tsec ne $usec) { next; }
 5900: 		}
 5901: 		$access=($effect eq 'allow');
 5902: 		last;
 5903: 	    }
 5904: 	    if ($realm eq '' && $role eq '') {
 5905: 		$access=($effect eq 'allow');
 5906: 	    }
 5907: 	}
 5908:     }
 5909:     return $access;
 5910: }
 5911: 
 5912: # ------------------------------------------------- Check for a user privilege
 5913: 
 5914: sub allowed {
 5915:     my ($priv,$uri,$symb,$role)=@_;
 5916:     my $ver_orguri=$uri;
 5917:     $uri=&deversion($uri);
 5918:     my $orguri=$uri;
 5919:     $uri=&declutter($uri);
 5920: 
 5921:     if ($priv eq 'evb') {
 5922: # Evade communication block restrictions for specified role in a course
 5923:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5924:             return $1;
 5925:         } else {
 5926:             return;
 5927:         }
 5928:     }
 5929: 
 5930:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5931: # Free bre access to adm and meta resources
 5932:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5933: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5934: 	&& ($priv eq 'bre')) {
 5935: 	return 'F';
 5936:     }
 5937: 
 5938: # Free bre access to user's own portfolio contents
 5939:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5940:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5941: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5942:         my %setters;
 5943:         my ($startblock,$endblock) = 
 5944:             &Apache::loncommon::blockcheck(\%setters,'port');
 5945:         if ($startblock && $endblock) {
 5946:             return 'B';
 5947:         } else {
 5948:             return 'F';
 5949:         }
 5950:     }
 5951: 
 5952: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5953:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5954:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5955:         if (exists($env{'request.course.id'})) {
 5956:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5957:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5958:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5959:                 my $courseprivid=$env{'request.course.id'};
 5960:                 $courseprivid=~s/\_/\//;
 5961:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5962:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5963:                     return $1; 
 5964:                 } else {
 5965:                     if ($env{'request.course.sec'}) {
 5966:                         $courseprivid.='/'.$env{'request.course.sec'};
 5967:                     }
 5968:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5969:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5970:                         return $2;
 5971:                     }
 5972:                 }
 5973:             }
 5974:         }
 5975:     }
 5976: 
 5977: # Free bre to public access
 5978: 
 5979:     if ($priv eq 'bre') {
 5980:         my $copyright=&metadata($uri,'copyright');
 5981: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5982:            return 'F'; 
 5983:         }
 5984:         if ($copyright eq 'priv') {
 5985:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5986: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5987: 		return '';
 5988:             }
 5989:         }
 5990:         if ($copyright eq 'domain') {
 5991:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5992: 	    unless (($env{'user.domain'} eq $1) ||
 5993:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5994: 		return '';
 5995:             }
 5996:         }
 5997:         if ($env{'request.role'}=~ /li\.\//) {
 5998:             # Library role, so allow browsing of resources in this domain.
 5999:             return 'F';
 6000:         }
 6001:         if ($copyright eq 'custom') {
 6002: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6003:         }
 6004:     }
 6005:     # Domain coordinator is trying to create a course
 6006:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6007:         # uri is the requested domain in this case.
 6008:         # comparison to 'request.role.domain' shows if the user has selected
 6009:         # a role of dc for the domain in question.
 6010:         return 'F' if ($uri eq $env{'request.role.domain'});
 6011:     }
 6012: 
 6013:     my $thisallowed='';
 6014:     my $statecond=0;
 6015:     my $courseprivid='';
 6016: 
 6017:     my $ownaccess;
 6018:     # Community Coordinator or Assistant Co-author browsing resource space.
 6019:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6020:         if ($uri eq '') {
 6021:             $ownaccess = 1;
 6022:         } else {
 6023:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6024:                 my $udom = $env{'user.domain'};
 6025:                 my $uname = $env{'user.name'};
 6026:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6027:                     $ownaccess = 1;
 6028:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6029:                     unless ($uri =~ m{\.\./}) {
 6030:                         $ownaccess = 1;
 6031:                     }
 6032:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6033:                     my $now = time;
 6034:                     if ($uri =~ m{^([^/]+)/?$}) {
 6035:                         my $adom = $1;
 6036:                         foreach my $key (keys(%env)) {
 6037:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6038:                                 my ($start,$end) = split('.',$env{$key});
 6039:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6040:                                     $ownaccess = 1;
 6041:                                     last;
 6042:                                 }
 6043:                             }
 6044:                         }
 6045:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6046:                         my $adom = $1;
 6047:                         my $aname = $2;
 6048:                         foreach my $role ('ca','aa') { 
 6049:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6050:                                 my ($start,$end) =
 6051:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6052:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6053:                                     $ownaccess = 1;
 6054:                                     last;
 6055:                                 }
 6056:                             }
 6057:                         }
 6058:                     }
 6059:                 }
 6060:             }
 6061:         }
 6062:     }
 6063: 
 6064: # Course
 6065: 
 6066:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6067:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6068:             $thisallowed.=$1;
 6069:         }
 6070:     }
 6071: 
 6072: # Domain
 6073: 
 6074:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6075:        =~/\Q$priv\E\&([^\:]*)/) {
 6076:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6077:             $thisallowed.=$1;
 6078:         }
 6079:     }
 6080: 
 6081: # User who is not author or co-author might still be able to edit
 6082: # resource of an author in the domain (e.g., if Domain Coordinator).
 6083:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6084:         (&allowed('mdc',$env{'request.course.id'}))) {
 6085:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6086:             $thisallowed.=$1;
 6087:         }
 6088:     }
 6089: 
 6090: # Course: uri itself is a course
 6091:     my $courseuri=$uri;
 6092:     $courseuri=~s/\_(\d)/\/$1/;
 6093:     $courseuri=~s/^([^\/])/\/$1/;
 6094: 
 6095:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6096:        =~/\Q$priv\E\&([^\:]*)/) {
 6097:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6098:             $thisallowed.=$1;
 6099:         }
 6100:     }
 6101: 
 6102: # URI is an uploaded document for this course, default permissions don't matter
 6103: # not allowing 'edit' access (editupload) to uploaded course docs
 6104:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6105: 	$thisallowed='';
 6106:         my ($match)=&is_on_map($uri);
 6107:         if ($match) {
 6108:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6109:                   =~/\Q$priv\E\&([^\:]*)/) {
 6110:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6111:                 if (@blockers > 0) {
 6112:                     $thisallowed = 'B';
 6113:                 } else {
 6114:                     $thisallowed.=$1;
 6115:                 }
 6116:             }
 6117:         } else {
 6118:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6119:             if ($refuri) {
 6120:                 if ($refuri =~ m|^/adm/|) {
 6121:                     $thisallowed='F';
 6122:                 } else {
 6123:                     $refuri=&declutter($refuri);
 6124:                     my ($match) = &is_on_map($refuri);
 6125:                     if ($match) {
 6126:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6127:                         if (@blockers > 0) {
 6128:                             $thisallowed = 'B';
 6129:                         } else {
 6130:                             $thisallowed='F';
 6131:                         }
 6132:                     }
 6133:                 }
 6134:             }
 6135:         }
 6136:     }
 6137: 
 6138:     if ($priv eq 'bre'
 6139: 	&& $thisallowed ne 'F' 
 6140: 	&& $thisallowed ne '2'
 6141: 	&& &is_portfolio_url($uri)) {
 6142: 	$thisallowed = &portfolio_access($uri);
 6143:     }
 6144:     
 6145: # Full access at system, domain or course-wide level? Exit.
 6146:     if ($thisallowed=~/F/) {
 6147: 	return 'F';
 6148:     }
 6149: 
 6150: # If this is generating or modifying users, exit with special codes
 6151: 
 6152:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6153: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6154: 	    my ($audom,$auname)=split('/',$uri);
 6155: # no author name given, so this just checks on the general right to make a co-author in this domain
 6156: 	    unless ($auname) { return $thisallowed; }
 6157: # an author name is given, so we are about to actually make a co-author for a certain account
 6158: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6159: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6160: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6161: 	}
 6162: 	return $thisallowed;
 6163:     }
 6164: #
 6165: # Gathered so far: system, domain and course wide privileges
 6166: #
 6167: # Course: See if uri or referer is an individual resource that is part of 
 6168: # the course
 6169: 
 6170:     if ($env{'request.course.id'}) {
 6171: 
 6172:        $courseprivid=$env{'request.course.id'};
 6173:        if ($env{'request.course.sec'}) {
 6174:           $courseprivid.='/'.$env{'request.course.sec'};
 6175:        }
 6176:        $courseprivid=~s/\_/\//;
 6177:        my $checkreferer=1;
 6178:        my ($match,$cond)=&is_on_map($uri);
 6179:        if ($match) {
 6180:            $statecond=$cond;
 6181:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6182:                =~/\Q$priv\E\&([^\:]*)/) {
 6183:                my $value = $1;
 6184:                if ($priv eq 'bre') {
 6185:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6186:                    if (@blockers > 0) {
 6187:                        $thisallowed = 'B';
 6188:                    } else {
 6189:                        $thisallowed.=$value;
 6190:                    }
 6191:                } else {
 6192:                    $thisallowed.=$value;
 6193:                }
 6194:                $checkreferer=0;
 6195:            }
 6196:        }
 6197:        
 6198:        if ($checkreferer) {
 6199: 	  my $refuri=$env{'httpref.'.$orguri};
 6200:             unless ($refuri) {
 6201:                 foreach my $key (keys(%env)) {
 6202: 		    if ($key=~/^httpref\..*\*/) {
 6203: 			my $pattern=$key;
 6204:                         $pattern=~s/^httpref\.\/res\///;
 6205:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6206:                         $pattern=~s/\//\\\//g;
 6207:                         if ($orguri=~/$pattern/) {
 6208: 			    $refuri=$env{$key};
 6209:                         }
 6210:                     }
 6211:                 }
 6212:             }
 6213: 
 6214:          if ($refuri) { 
 6215: 	  $refuri=&declutter($refuri);
 6216:           my ($match,$cond)=&is_on_map($refuri);
 6217:             if ($match) {
 6218:               my $refstatecond=$cond;
 6219:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6220:                   =~/\Q$priv\E\&([^\:]*)/) {
 6221:                   my $value = $1;
 6222:                   if ($priv eq 'bre') {
 6223:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6224:                       if (@blockers > 0) {
 6225:                           $thisallowed = 'B';
 6226:                       } else {
 6227:                           $thisallowed.=$value;
 6228:                       }
 6229:                   } else {
 6230:                       $thisallowed.=$value;
 6231:                   }
 6232:                   $uri=$refuri;
 6233:                   $statecond=$refstatecond;
 6234:               }
 6235:           }
 6236:         }
 6237:        }
 6238:    }
 6239: 
 6240: #
 6241: # Gathered now: all privileges that could apply, and condition number
 6242: # 
 6243: #
 6244: # Full or no access?
 6245: #
 6246: 
 6247:     if ($thisallowed=~/F/) {
 6248: 	return 'F';
 6249:     }
 6250: 
 6251:     unless ($thisallowed) {
 6252:         return '';
 6253:     }
 6254: 
 6255: # Restrictions exist, deal with them
 6256: #
 6257: #   C:according to course preferences
 6258: #   R:according to resource settings
 6259: #   L:unless locked
 6260: #   X:according to user session state
 6261: #
 6262: 
 6263: # Possibly locked functionality, check all courses
 6264: # Locks might take effect only after 10 minutes cache expiration for other
 6265: # courses, and 2 minutes for current course
 6266: 
 6267:     my $envkey;
 6268:     if ($thisallowed=~/L/) {
 6269:         foreach $envkey (keys(%env)) {
 6270:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6271:                my $courseid=$2;
 6272:                my $roleid=$1.'.'.$2;
 6273:                $courseid=~s/^\///;
 6274:                my $expiretime=600;
 6275:                if ($env{'request.role'} eq $roleid) {
 6276: 		  $expiretime=120;
 6277:                }
 6278: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6279:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6280:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6281: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6282:                }
 6283:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6284:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6285: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6286:                        &log($env{'user.domain'},$env{'user.name'},
 6287:                             $env{'user.home'},
 6288:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6289:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6290:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6291: 		       return '';
 6292:                    }
 6293:                }
 6294:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6295:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6296: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6297:                        &log($env{'user.domain'},$env{'user.name'},
 6298:                             $env{'user.home'},
 6299:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6300:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6301:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6302: 		       return '';
 6303:                    }
 6304:                }
 6305: 	   }
 6306:        }
 6307:     }
 6308:    
 6309: #
 6310: # Rest of the restrictions depend on selected course
 6311: #
 6312: 
 6313:     unless ($env{'request.course.id'}) {
 6314: 	if ($thisallowed eq 'A') {
 6315: 	    return 'A';
 6316:         } elsif ($thisallowed eq 'B') {
 6317:             return 'B';
 6318: 	} else {
 6319: 	    return '1';
 6320: 	}
 6321:     }
 6322: 
 6323: #
 6324: # Now user is definitely in a course
 6325: #
 6326: 
 6327: 
 6328: # Course preferences
 6329: 
 6330:    if ($thisallowed=~/C/) {
 6331:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6332:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6333:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6334: 	   =~/\Q$rolecode\E/) {
 6335: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6336: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6337: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6338: 			$env{'request.course.id'});
 6339: 	   }
 6340:            return '';
 6341:        }
 6342: 
 6343:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6344: 	   =~/\Q$unamedom\E/) {
 6345: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6346: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6347: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6348: 			$env{'request.course.id'});
 6349: 	   }
 6350:            return '';
 6351:        }
 6352:    }
 6353: 
 6354: # Resource preferences
 6355: 
 6356:    if ($thisallowed=~/R/) {
 6357:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6358:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6359: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6360: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6361: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6362: 	   }
 6363: 	   return '';
 6364:        }
 6365:    }
 6366: 
 6367: # Restricted by state or randomout?
 6368: 
 6369:    if ($thisallowed=~/X/) {
 6370:       if ($env{'acc.randomout'}) {
 6371: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6372:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6373:             return ''; 
 6374:          }
 6375:       }
 6376:       if (&condval($statecond)) {
 6377: 	 return '2';
 6378:       } else {
 6379:          return '';
 6380:       }
 6381:    }
 6382: 
 6383:     if ($thisallowed eq 'A') {
 6384: 	return 'A';
 6385:     } elsif ($thisallowed eq 'B') {
 6386:         return 'B';
 6387:     }
 6388:    return 'F';
 6389: }
 6390: 
 6391: sub get_comm_blocks {
 6392:     my ($cdom,$cnum) = @_;
 6393:     if ($cdom eq '' || $cnum eq '') {
 6394:         return unless ($env{'request.course.id'});
 6395:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6396:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6397:     }
 6398:     my %commblocks;
 6399:     my $hashid=$cdom.'_'.$cnum;
 6400:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6401:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6402:         %commblocks = %{$blocksref};
 6403:     } else {
 6404:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6405:         my $cachetime = 600;
 6406:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6407:     }
 6408:     return %commblocks;
 6409: }
 6410: 
 6411: sub has_comm_blocking {
 6412:     my ($priv,$symb,$uri,$blocks) = @_;
 6413:     return unless ($env{'request.course.id'});
 6414:     return unless ($priv eq 'bre');
 6415:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6416:     my %commblocks;
 6417:     if (ref($blocks) eq 'HASH') {
 6418:         %commblocks = %{$blocks};
 6419:     } else {
 6420:         %commblocks = &get_comm_blocks();
 6421:     }
 6422:     return unless (keys(%commblocks) > 0);
 6423:     if (!$symb) { $symb=&symbread($uri,1); }
 6424:     my ($map,$resid,undef)=&decode_symb($symb);
 6425:     my %tocheck = (
 6426:                     maps      => $map,
 6427:                     resources => $symb,
 6428:                   );
 6429:     my @blockers;
 6430:     my $now = time;
 6431:     my $navmap = Apache::lonnavmaps::navmap->new();
 6432:     foreach my $block (keys(%commblocks)) {
 6433:         if ($block =~ /^(\d+)____(\d+)$/) {
 6434:             my ($start,$end) = ($1,$2);
 6435:             if ($start <= $now && $end >= $now) {
 6436:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6437:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6438:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6439:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6440:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6441:                                     push(@blockers,$block);
 6442:                                 }
 6443:                             }
 6444:                         }
 6445:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6446:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6447:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6448:                                     push(@blockers,$block);
 6449:                                 }
 6450:                             }
 6451:                         }
 6452:                     }
 6453:                 }
 6454:             }
 6455:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6456:             my $item = $1;
 6457:             my @to_test;
 6458:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6459:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6460:                     my $check_interval;
 6461:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6462:                         my @interval;
 6463:                         my $type = 'map';
 6464:                         if ($item eq 'course') {
 6465:                             $type = 'course';
 6466:                             @interval=&EXT("resource.0.interval");
 6467:                         } else {
 6468:                             if ($item =~ /___\d+___/) {
 6469:                                 $type = 'resource';
 6470:                                 @interval=&EXT("resource.0.interval",$item);
 6471:                                 if (ref($navmap)) {                        
 6472:                                     my $res = $navmap->getBySymb($item); 
 6473:                                     push(@to_test,$res);
 6474:                                 }
 6475:                             } else {
 6476:                                 my $mapsymb = &symbread($item,1);
 6477:                                 if ($mapsymb) {
 6478:                                     if (ref($navmap)) {
 6479:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6480:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6481:                                         foreach my $res (@to_test) {
 6482:                                             my $symb = $res->symb();
 6483:                                             next if ($symb eq $mapsymb);
 6484:                                             if ($symb ne '') {
 6485:                                                 @interval=&EXT("resource.0.interval",$symb);
 6486:                                                 last;
 6487:                                             }
 6488:                                         }
 6489:                                     }
 6490:                                 }
 6491:                             }
 6492:                         }
 6493:                         if ($interval[0] =~ /\d+/) {
 6494:                             my $first_access;
 6495:                             if ($type eq 'resource') {
 6496:                                 $first_access=&get_first_access($interval[1],$item);
 6497:                             } elsif ($type eq 'map') {
 6498:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6499:                             } else {
 6500:                                 $first_access=&get_first_access($interval[1]);
 6501:                             }
 6502:                             if ($first_access) {
 6503:                                 my $timesup = $first_access+$interval[0];
 6504:                                 if ($timesup > $now) {
 6505:                                     foreach my $res (@to_test) {
 6506:                                         if ($res->is_problem()) {
 6507:                                             if ($res->completable()) {
 6508:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6509:                                                     push(@blockers,$block);
 6510:                                                 }
 6511:                                                 last;
 6512:                                             }
 6513:                                         }
 6514:                                     }
 6515:                                 }
 6516:                             }
 6517:                         }
 6518:                     }
 6519:                 }
 6520:             }
 6521:         }
 6522:     }
 6523:     return @blockers;
 6524: }
 6525: 
 6526: sub check_docs_block {
 6527:     my ($docsblock,$tocheck) =@_;
 6528:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6529:         return;
 6530:     }
 6531:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6532:         if ($tocheck->{'maps'}) {
 6533:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6534:                 return 1;
 6535:             }
 6536:         }
 6537:     }
 6538:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6539:         if ($tocheck->{'resources'}) {
 6540:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6541:                 return 1;
 6542:             }
 6543:         }
 6544:     }
 6545:     return;
 6546: }
 6547: 
 6548: #
 6549: #   Removes the versino from a URI and
 6550: #   splits it in to its filename and path to the filename.
 6551: #   Seems like File::Basename could have done this more clearly.
 6552: #   Parameters:
 6553: #      $uri   - input URI
 6554: #   Returns:
 6555: #     Two element list consisting of 
 6556: #     $pathname  - the URI up to and excluding the trailing /
 6557: #     $filename  - The part of the URI following the last /
 6558: #  NOTE:
 6559: #    Another realization of this is simply:
 6560: #    use File::Basename;
 6561: #    ...
 6562: #    $uri = shift;
 6563: #    $filename = basename($uri);
 6564: #    $path     = dirname($uri);
 6565: #    return ($filename, $path);
 6566: #
 6567: #     The implementation below is probably faster however.
 6568: #
 6569: sub split_uri_for_cond {
 6570:     my $uri=&deversion(&declutter(shift));
 6571:     my @uriparts=split(/\//,$uri);
 6572:     my $filename=pop(@uriparts);
 6573:     my $pathname=join('/',@uriparts);
 6574:     return ($pathname,$filename);
 6575: }
 6576: # --------------------------------------------------- Is a resource on the map?
 6577: 
 6578: sub is_on_map {
 6579:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6580:     #Trying to find the conditional for the file
 6581:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6582: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6583:     if ($match) {
 6584: 	return (1,$1);
 6585:     } else {
 6586: 	return (0,0);
 6587:     }
 6588: }
 6589: 
 6590: # --------------------------------------------------------- Get symb from alias
 6591: 
 6592: sub get_symb_from_alias {
 6593:     my $symb=shift;
 6594:     my ($map,$resid,$url)=&decode_symb($symb);
 6595: # Already is a symb
 6596:     if ($url) { return $symb; }
 6597: # Must be an alias
 6598:     my $aliassymb='';
 6599:     my %bighash;
 6600:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6601:                             &GDBM_READER(),0640)) {
 6602:         my $rid=$bighash{'mapalias_'.$symb};
 6603: 	if ($rid) {
 6604: 	    my ($mapid,$resid)=split(/\./,$rid);
 6605: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6606: 				    $resid,$bighash{'src_'.$rid});
 6607: 	}
 6608:         untie %bighash;
 6609:     }
 6610:     return $aliassymb;
 6611: }
 6612: 
 6613: # ----------------------------------------------------------------- Define Role
 6614: 
 6615: sub definerole {
 6616:   if (allowed('mcr','/')) {
 6617:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6618:     foreach my $role (split(':',$sysrole)) {
 6619: 	my ($crole,$cqual)=split(/\&/,$role);
 6620:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6621:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6622: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6623:                return "refused:s:$crole&$cqual"; 
 6624:             }
 6625:         }
 6626:     }
 6627:     foreach my $role (split(':',$domrole)) {
 6628: 	my ($crole,$cqual)=split(/\&/,$role);
 6629:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6630:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6631: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6632:                return "refused:d:$crole&$cqual"; 
 6633:             }
 6634:         }
 6635:     }
 6636:     foreach my $role (split(':',$courole)) {
 6637: 	my ($crole,$cqual)=split(/\&/,$role);
 6638:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6639:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6640: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6641:                return "refused:c:$crole&$cqual"; 
 6642:             }
 6643:         }
 6644:     }
 6645:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6646:                 "$env{'user.domain'}:$env{'user.name'}:".
 6647: 	        "rolesdef_$rolename=".
 6648:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6649:     return reply($command,$env{'user.home'});
 6650:   } else {
 6651:     return 'refused';
 6652:   }
 6653: }
 6654: 
 6655: # ---------------- Make a metadata query against the network of library servers
 6656: 
 6657: sub metadata_query {
 6658:     my ($query,$custom,$customshow,$server_array)=@_;
 6659:     my %rhash;
 6660:     my %libserv = &all_library();
 6661:     my @server_list = (defined($server_array) ? @$server_array
 6662:                                               : keys(%libserv) );
 6663:     for my $server (@server_list) {
 6664: 	unless ($custom or $customshow) {
 6665: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6666: 	    $rhash{$server}=$reply;
 6667: 	}
 6668: 	else {
 6669: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6670: 			     &escape($custom).':'.&escape($customshow),
 6671: 			     $server);
 6672: 	    $rhash{$server}=$reply;
 6673: 	}
 6674:     }
 6675:     return \%rhash;
 6676: }
 6677: 
 6678: # ----------------------------------------- Send log queries and wait for reply
 6679: 
 6680: sub log_query {
 6681:     my ($uname,$udom,$query,%filters)=@_;
 6682:     my $uhome=&homeserver($uname,$udom);
 6683:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6684:     my $uhost=&hostname($uhome);
 6685:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6686:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6687:                        $uhome);
 6688:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6689:     return get_query_reply($queryid);
 6690: }
 6691: 
 6692: # -------------------------- Update MySQL table for portfolio file
 6693: 
 6694: sub update_portfolio_table {
 6695:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6696:     if ($group ne '') {
 6697:         $file_name =~s /^\Q$group\E//;
 6698:     }
 6699:     my $homeserver = &homeserver($uname,$udom);
 6700:     my $queryid=
 6701:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6702:                ':'.&escape($file_name).':'.$action,$homeserver);
 6703:     my $reply = &get_query_reply($queryid);
 6704:     return $reply;
 6705: }
 6706: 
 6707: # -------------------------- Update MySQL allusers table
 6708: 
 6709: sub update_allusers_table {
 6710:     my ($uname,$udom,$names) = @_;
 6711:     my $homeserver = &homeserver($uname,$udom);
 6712:     my $queryid=
 6713:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6714:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6715:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6716:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6717:                'generation='.&escape($names->{'generation'}).'%%'.
 6718:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6719:                'id='.&escape($names->{'id'}),$homeserver);
 6720:     return;
 6721: }
 6722: 
 6723: # ------- Request retrieval of institutional classlists for course(s)
 6724: 
 6725: sub fetch_enrollment_query {
 6726:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6727:     my $homeserver;
 6728:     my $maxtries = 1;
 6729:     if ($context eq 'automated') {
 6730:         $homeserver = $perlvar{'lonHostID'};
 6731:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6732:     } else {
 6733:         $homeserver = &homeserver($cnum,$dom);
 6734:     }
 6735:     my $host=&hostname($homeserver);
 6736:     my $cmd = '';
 6737:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6738:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6739:     }
 6740:     $cmd =~ s/%%$//;
 6741:     $cmd = &escape($cmd);
 6742:     my $query = 'fetchenrollment';
 6743:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6744:     unless ($queryid=~/^\Q$host\E\_/) { 
 6745:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6746:         return 'error: '.$queryid;
 6747:     }
 6748:     my $reply = &get_query_reply($queryid);
 6749:     my $tries = 1;
 6750:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6751:         $reply = &get_query_reply($queryid);
 6752:         $tries ++;
 6753:     }
 6754:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6755:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6756:     } else {
 6757:         my @responses = split(/:/,$reply);
 6758:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6759:             foreach my $line (@responses) {
 6760:                 my ($key,$value) = split(/=/,$line,2);
 6761:                 $$replyref{$key} = $value;
 6762:             }
 6763:         } else {
 6764:             my $pathname = LONCAPA::tempdir();
 6765:             foreach my $line (@responses) {
 6766:                 my ($key,$value) = split(/=/,$line);
 6767:                 $$replyref{$key} = $value;
 6768:                 if ($value > 0) {
 6769:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6770:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6771:                         my $destname = $pathname.'/'.$filename;
 6772:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6773:                         if ($xml_classlist =~ /^error/) {
 6774:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6775:                         } else {
 6776:                             if ( open(FILE,">$destname") ) {
 6777:                                 print FILE &unescape($xml_classlist);
 6778:                                 close(FILE);
 6779:                             } else {
 6780:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6781:                             }
 6782:                         }
 6783:                     }
 6784:                 }
 6785:             }
 6786:         }
 6787:         return 'ok';
 6788:     }
 6789:     return 'error';
 6790: }
 6791: 
 6792: sub get_query_reply {
 6793:     my $queryid=shift;
 6794:     my $replyfile=LONCAPA::tempdir().$queryid;
 6795:     my $reply='';
 6796:     for (1..100) {
 6797: 	sleep 2;
 6798:         if (-e $replyfile.'.end') {
 6799: 	    if (open(my $fh,$replyfile)) {
 6800: 		$reply = join('',<$fh>);
 6801: 		close($fh);
 6802: 	   } else { return 'error: reply_file_error'; }
 6803:            return &unescape($reply);
 6804: 	}
 6805:     }
 6806:     return 'timeout:'.$queryid;
 6807: }
 6808: 
 6809: sub courselog_query {
 6810: #
 6811: # possible filters:
 6812: # url: url or symb
 6813: # username
 6814: # domain
 6815: # action: view, submit, grade
 6816: # start: timestamp
 6817: # end: timestamp
 6818: #
 6819:     my (%filters)=@_;
 6820:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6821:     if ($filters{'url'}) {
 6822: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6823:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6824:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6825:     }
 6826:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6827:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6828:     return &log_query($cname,$cdom,'courselog',%filters);
 6829: }
 6830: 
 6831: sub userlog_query {
 6832: #
 6833: # possible filters:
 6834: # action: log check role
 6835: # start: timestamp
 6836: # end: timestamp
 6837: #
 6838:     my ($uname,$udom,%filters)=@_;
 6839:     return &log_query($uname,$udom,'userlog',%filters);
 6840: }
 6841: 
 6842: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6843: 
 6844: sub auto_run {
 6845:     my ($cnum,$cdom) = @_;
 6846:     my $response = 0;
 6847:     my $settings;
 6848:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6849:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6850:         $settings = $domconfig{'autoenroll'};
 6851:         if ($settings->{'run'} eq '1') {
 6852:             $response = 1;
 6853:         }
 6854:     } else {
 6855:         my $homeserver;
 6856:         if (&is_course($cdom,$cnum)) {
 6857:             $homeserver = &homeserver($cnum,$cdom);
 6858:         } else {
 6859:             $homeserver = &domain($cdom,'primary');
 6860:         }
 6861:         if ($homeserver ne 'no_host') {
 6862:             $response = &reply('autorun:'.$cdom,$homeserver);
 6863:         }
 6864:     }
 6865:     return $response;
 6866: }
 6867: 
 6868: sub auto_get_sections {
 6869:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6870:     my $homeserver;
 6871:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6872:         $homeserver = &homeserver($cnum,$cdom);
 6873:     }
 6874:     if (!defined($homeserver)) { 
 6875:         if ($cdom =~ /^$match_domain$/) {
 6876:             $homeserver = &domain($cdom,'primary');
 6877:         }
 6878:     }
 6879:     my @secs;
 6880:     if (defined($homeserver)) {
 6881:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6882:         unless ($response eq 'refused') {
 6883:             @secs = split(/:/,$response);
 6884:         }
 6885:     }
 6886:     return @secs;
 6887: }
 6888: 
 6889: sub auto_new_course {
 6890:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6891:     my $homeserver = &homeserver($cnum,$cdom);
 6892:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6893:     return $response;
 6894: }
 6895: 
 6896: sub auto_validate_courseID {
 6897:     my ($cnum,$cdom,$inst_course_id) = @_;
 6898:     my $homeserver = &homeserver($cnum,$cdom);
 6899:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6900:     return $response;
 6901: }
 6902: 
 6903: sub auto_validate_instcode {
 6904:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6905:     my ($homeserver,$response);
 6906:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6907:         $homeserver = &homeserver($cnum,$cdom);
 6908:     }
 6909:     if (!defined($homeserver)) {
 6910:         if ($cdom =~ /^$match_domain$/) {
 6911:             $homeserver = &domain($cdom,'primary');
 6912:         }
 6913:     }
 6914:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6915:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6916:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6917:     return ($outcome,$description);
 6918: }
 6919: 
 6920: sub auto_create_password {
 6921:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6922:     my ($homeserver,$response);
 6923:     my $create_passwd = 0;
 6924:     my $authchk = '';
 6925:     if ($udom =~ /^$match_domain$/) {
 6926:         $homeserver = &domain($udom,'primary');
 6927:     }
 6928:     if ($homeserver eq '') {
 6929:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6930:             $homeserver = &homeserver($cnum,$cdom);
 6931:         }
 6932:     }
 6933:     if ($homeserver eq '') {
 6934:         $authchk = 'nodomain';
 6935:     } else {
 6936:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6937:         if ($response eq 'refused') {
 6938:             $authchk = 'refused';
 6939:         } else {
 6940:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6941:         }
 6942:     }
 6943:     return ($authparam,$create_passwd,$authchk);
 6944: }
 6945: 
 6946: sub auto_photo_permission {
 6947:     my ($cnum,$cdom,$students) = @_;
 6948:     my $homeserver = &homeserver($cnum,$cdom);
 6949:     my ($outcome,$perm_reqd,$conditions) = 
 6950: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6951:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6952: 	return (undef,undef);
 6953:     }
 6954:     return ($outcome,$perm_reqd,$conditions);
 6955: }
 6956: 
 6957: sub auto_checkphotos {
 6958:     my ($uname,$udom,$pid) = @_;
 6959:     my $homeserver = &homeserver($uname,$udom);
 6960:     my ($result,$resulttype);
 6961:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6962: 				   &escape($uname).':'.&escape($pid),
 6963: 				   $homeserver));
 6964:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6965: 	return (undef,undef);
 6966:     }
 6967:     if ($outcome) {
 6968:         ($result,$resulttype) = split(/:/,$outcome);
 6969:     } 
 6970:     return ($result,$resulttype);
 6971: }
 6972: 
 6973: sub auto_photochoice {
 6974:     my ($cnum,$cdom) = @_;
 6975:     my $homeserver = &homeserver($cnum,$cdom);
 6976:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6977: 						       &escape($cdom),
 6978: 						       $homeserver)));
 6979:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6980: 	return (undef,undef);
 6981:     }
 6982:     return ($update,$comment);
 6983: }
 6984: 
 6985: sub auto_photoupdate {
 6986:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6987:     my $homeserver = &homeserver($cnum,$dom);
 6988:     my $host=&hostname($homeserver);
 6989:     my $cmd = '';
 6990:     my $maxtries = 1;
 6991:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6992:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6993:     }
 6994:     $cmd =~ s/%%$//;
 6995:     $cmd = &escape($cmd);
 6996:     my $query = 'institutionalphotos';
 6997:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6998:     unless ($queryid=~/^\Q$host\E\_/) {
 6999:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7000:         return 'error: '.$queryid;
 7001:     }
 7002:     my $reply = &get_query_reply($queryid);
 7003:     my $tries = 1;
 7004:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7005:         $reply = &get_query_reply($queryid);
 7006:         $tries ++;
 7007:     }
 7008:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7009:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7010:     } else {
 7011:         my @responses = split(/:/,$reply);
 7012:         my $outcome = shift(@responses); 
 7013:         foreach my $item (@responses) {
 7014:             my ($key,$value) = split(/=/,$item);
 7015:             $$photo{$key} = $value;
 7016:         }
 7017:         return $outcome;
 7018:     }
 7019:     return 'error';
 7020: }
 7021: 
 7022: sub auto_instcode_format {
 7023:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7024: 	$cat_order) = @_;
 7025:     my $courses = '';
 7026:     my @homeservers;
 7027:     if ($caller eq 'global') {
 7028: 	my %servers = &get_servers($codedom,'library');
 7029: 	foreach my $tryserver (keys(%servers)) {
 7030: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7031: 		push(@homeservers,$tryserver);
 7032: 	    }
 7033:         }
 7034:     } elsif ($caller eq 'requests') {
 7035:         if ($codedom =~ /^$match_domain$/) {
 7036:             my $chome = &domain($codedom,'primary');
 7037:             unless ($chome eq 'no_host') {
 7038:                 push(@homeservers,$chome);
 7039:             }
 7040:         }
 7041:     } else {
 7042:         push(@homeservers,&homeserver($caller,$codedom));
 7043:     }
 7044:     foreach my $code (keys(%{$instcodes})) {
 7045:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7046:     }
 7047:     chop($courses);
 7048:     my $ok_response = 0;
 7049:     my $response;
 7050:     while (@homeservers > 0 && $ok_response == 0) {
 7051:         my $server = shift(@homeservers); 
 7052:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7053:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7054:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7055: 		split(/:/,$response);
 7056:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7057:             push(@{$codetitles},&str2array($codetitles_str));
 7058:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7059:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7060:             $ok_response = 1;
 7061:         }
 7062:     }
 7063:     if ($ok_response) {
 7064:         return 'ok';
 7065:     } else {
 7066:         return $response;
 7067:     }
 7068: }
 7069: 
 7070: sub auto_instcode_defaults {
 7071:     my ($domain,$returnhash,$code_order) = @_;
 7072:     my @homeservers;
 7073: 
 7074:     my %servers = &get_servers($domain,'library');
 7075:     foreach my $tryserver (keys(%servers)) {
 7076: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7077: 	    push(@homeservers,$tryserver);
 7078: 	}
 7079:     }
 7080: 
 7081:     my $response;
 7082:     foreach my $server (@homeservers) {
 7083:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7084:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7085: 	
 7086: 	foreach my $pair (split(/\&/,$response)) {
 7087: 	    my ($name,$value)=split(/\=/,$pair);
 7088: 	    if ($name eq 'code_order') {
 7089: 		@{$code_order} = split(/\&/,&unescape($value));
 7090: 	    } else {
 7091: 		$returnhash->{&unescape($name)}=&unescape($value);
 7092: 	    }
 7093: 	}
 7094: 	return 'ok';
 7095:     }
 7096: 
 7097:     return $response;
 7098: }
 7099: 
 7100: sub auto_possible_instcodes {
 7101:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7102:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7103:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7104:         return;
 7105:     }
 7106:     my (@homeservers,$uhome);
 7107:     if (defined(&domain($domain,'primary'))) {
 7108:         $uhome=&domain($domain,'primary');
 7109:         push(@homeservers,&domain($domain,'primary'));
 7110:     } else {
 7111:         my %servers = &get_servers($domain,'library');
 7112:         foreach my $tryserver (keys(%servers)) {
 7113:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7114:                 push(@homeservers,$tryserver);
 7115:             }
 7116:         }
 7117:     }
 7118:     my $response;
 7119:     foreach my $server (@homeservers) {
 7120:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7121:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7122:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7123:             split(':',$response);
 7124:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7125:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7126:         foreach my $item (split('&',$cat_title)) {   
 7127:             my ($name,$value)=split('=',$item);
 7128:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7129:         }
 7130:         foreach my $item (split('&',$cat_order)) {
 7131:             my ($name,$value)=split('=',$item);
 7132:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7133:         }
 7134:         return 'ok';
 7135:     }
 7136:     return $response;
 7137: }
 7138: 
 7139: sub auto_courserequest_checks {
 7140:     my ($dom) = @_;
 7141:     my ($homeserver,%validations);
 7142:     if ($dom =~ /^$match_domain$/) {
 7143:         $homeserver = &domain($dom,'primary');
 7144:     }
 7145:     unless ($homeserver eq 'no_host') {
 7146:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7147:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7148:             my @items = split(/&/,$response);
 7149:             foreach my $item (@items) {
 7150:                 my ($key,$value) = split('=',$item);
 7151:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7152:             }
 7153:         }
 7154:     }
 7155:     return %validations; 
 7156: }
 7157: 
 7158: sub auto_courserequest_validation {
 7159:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7160:     my ($homeserver,$response);
 7161:     if ($dom =~ /^$match_domain$/) {
 7162:         $homeserver = &domain($dom,'primary');
 7163:     }
 7164:     unless ($homeserver eq 'no_host') {  
 7165:           
 7166:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7167:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7168:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7169:                                     $homeserver));
 7170:     }
 7171:     return $response;
 7172: }
 7173: 
 7174: sub auto_validate_class_sec {
 7175:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7176:     my $homeserver = &homeserver($cnum,$cdom);
 7177:     my $ownerlist;
 7178:     if (ref($owners) eq 'ARRAY') {
 7179:         $ownerlist = join(',',@{$owners});
 7180:     } else {
 7181:         $ownerlist = $owners;
 7182:     }
 7183:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7184:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7185:     return $response;
 7186: }
 7187: 
 7188: # ------------------------------------------------------- Course Group routines
 7189: 
 7190: sub get_coursegroups {
 7191:     my ($cdom,$cnum,$group,$namespace) = @_;
 7192:     return(&dump($namespace,$cdom,$cnum,$group));
 7193: }
 7194: 
 7195: sub modify_coursegroup {
 7196:     my ($cdom,$cnum,$groupsettings) = @_;
 7197:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7198: }
 7199: 
 7200: sub toggle_coursegroup_status {
 7201:     my ($cdom,$cnum,$group,$action) = @_;
 7202:     my ($from_namespace,$to_namespace);
 7203:     if ($action eq 'delete') {
 7204:         $from_namespace = 'coursegroups';
 7205:         $to_namespace = 'deleted_groups';
 7206:     } else {
 7207:         $from_namespace = 'deleted_groups';
 7208:         $to_namespace = 'coursegroups';
 7209:     }
 7210:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7211:     if (my $tmp = &error(%curr_group)) {
 7212:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7213:         return ('read error',$tmp);
 7214:     } else {
 7215:         my %savedsettings = %curr_group; 
 7216:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7217:         my $deloutcome;
 7218:         if ($result eq 'ok') {
 7219:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7220:         } else {
 7221:             return ('write error',$result);
 7222:         }
 7223:         if ($deloutcome eq 'ok') {
 7224:             return 'ok';
 7225:         } else {
 7226:             return ('delete error',$deloutcome);
 7227:         }
 7228:     }
 7229: }
 7230: 
 7231: sub modify_group_roles {
 7232:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7233:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7234:     my $role = 'gr/'.&escape($userprivs);
 7235:     my ($uname,$udom) = split(/:/,$user);
 7236:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7237:     if ($result eq 'ok') {
 7238:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7239:     }
 7240:     return $result;
 7241: }
 7242: 
 7243: sub modify_coursegroup_membership {
 7244:     my ($cdom,$cnum,$membership) = @_;
 7245:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7246:     return $result;
 7247: }
 7248: 
 7249: sub get_active_groups {
 7250:     my ($udom,$uname,$cdom,$cnum) = @_;
 7251:     my $now = time;
 7252:     my %groups = ();
 7253:     foreach my $key (keys(%env)) {
 7254:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7255:             my ($start,$end) = split(/\./,$env{$key});
 7256:             if (($end!=0) && ($end<$now)) { next; }
 7257:             if (($start!=0) && ($start>$now)) { next; }
 7258:             if ($1 eq $cdom && $2 eq $cnum) {
 7259:                 $groups{$3} = $env{$key} ;
 7260:             }
 7261:         }
 7262:     }
 7263:     return %groups;
 7264: }
 7265: 
 7266: sub get_group_membership {
 7267:     my ($cdom,$cnum,$group) = @_;
 7268:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7269: }
 7270: 
 7271: sub get_users_groups {
 7272:     my ($udom,$uname,$courseid) = @_;
 7273:     my @usersgroups;
 7274:     my $cachetime=1800;
 7275: 
 7276:     my $hashid="$udom:$uname:$courseid";
 7277:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7278:     if (defined($cached)) {
 7279:         @usersgroups = split(/:/,$grouplist);
 7280:     } else {  
 7281:         $grouplist = '';
 7282:         my $courseurl = &courseid_to_courseurl($courseid);
 7283:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7284:         my $access_end = $env{'course.'.$courseid.
 7285:                               '.default_enrollment_end_date'};
 7286:         my $now = time;
 7287:         foreach my $key (keys(%roleshash)) {
 7288:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7289:                 my $group = $1;
 7290:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7291:                     my $start = $2;
 7292:                     my $end = $1;
 7293:                     if ($start == -1) { next; } # deleted from group
 7294:                     if (($start!=0) && ($start>$now)) { next; }
 7295:                     if (($end!=0) && ($end<$now)) {
 7296:                         if ($access_end && $access_end < $now) {
 7297:                             if ($access_end - $end < 86400) {
 7298:                                 push(@usersgroups,$group);
 7299:                             }
 7300:                         }
 7301:                         next;
 7302:                     }
 7303:                     push(@usersgroups,$group);
 7304:                 }
 7305:             }
 7306:         }
 7307:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7308:         $grouplist = join(':',@usersgroups);
 7309:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7310:     }
 7311:     return @usersgroups;
 7312: }
 7313: 
 7314: sub devalidate_getgroups_cache {
 7315:     my ($udom,$uname,$cdom,$cnum)=@_;
 7316:     my $courseid = $cdom.'_'.$cnum;
 7317: 
 7318:     my $hashid="$udom:$uname:$courseid";
 7319:     &devalidate_cache_new('getgroups',$hashid);
 7320: }
 7321: 
 7322: # ------------------------------------------------------------------ Plain Text
 7323: 
 7324: sub plaintext {
 7325:     my ($short,$type,$cid,$forcedefault) = @_;
 7326:     if ($short =~ m{^cr/}) {
 7327: 	return (split('/',$short))[-1];
 7328:     }
 7329:     if (!defined($cid)) {
 7330:         $cid = $env{'request.course.id'};
 7331:     }
 7332:     my %rolenames = (
 7333:                       Course    => 'std',
 7334:                       Community => 'alt1',
 7335:                     );
 7336:     if ($cid ne '') {
 7337:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7338:             unless ($forcedefault) {
 7339:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7340:                 &Apache::lonlocal::mt_escape(\$roletext);
 7341:                 return &Apache::lonlocal::mt($roletext);
 7342:             }
 7343:         }
 7344:     }
 7345:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7346:         (defined($rolenames{$type})) && 
 7347:         (defined($prp{$short}{$rolenames{$type}}))) {
 7348:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7349:     } elsif ($cid ne '') {
 7350:         my $crstype = $env{'course.'.$cid.'.type'};
 7351:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7352:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7353:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7354:         }
 7355:     }
 7356:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7357: }
 7358: 
 7359: # ----------------------------------------------------------------- Assign Role
 7360: 
 7361: sub assignrole {
 7362:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7363:         $context)=@_;
 7364:     my $mrole;
 7365:     if ($role =~ /^cr\//) {
 7366:         my $cwosec=$url;
 7367:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7368: 	unless (&allowed('ccr',$cwosec)) {
 7369:            my $refused = 1;
 7370:            if ($context eq 'requestcourses') {
 7371:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7372:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7373:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7374:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7375:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7376:                            if ($crsenv{'internal.courseowner'} eq
 7377:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7378:                                $refused = '';
 7379:                            }
 7380:                        }
 7381:                    }
 7382:                }
 7383:            }
 7384:            if ($refused) {
 7385:                &logthis('Refused custom assignrole: '.
 7386:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7387:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7388:                return 'refused';
 7389:            }
 7390:         }
 7391:         $mrole='cr';
 7392:     } elsif ($role =~ /^gr\//) {
 7393:         my $cwogrp=$url;
 7394:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7395:         unless (&allowed('mdg',$cwogrp)) {
 7396:             &logthis('Refused group assignrole: '.
 7397:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7398:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7399:             return 'refused';
 7400:         }
 7401:         $mrole='gr';
 7402:     } else {
 7403:         my $cwosec=$url;
 7404:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7405:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7406:             my $refused;
 7407:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7408:                 if (!(&allowed('c'.$role,$url))) {
 7409:                     $refused = 1;
 7410:                 }
 7411:             } else {
 7412:                 $refused = 1;
 7413:             }
 7414:             if ($refused) {
 7415:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7416:                 if (!$selfenroll && $context eq 'course') {
 7417:                     my %crsenv;
 7418:                     if ($role eq 'cc' || $role eq 'co') {
 7419:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7420:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7421:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7422:                                 if ($crsenv{'internal.courseowner'} eq 
 7423:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7424:                                     $refused = '';
 7425:                                 }
 7426:                             }
 7427:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7428:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7429:                                 if ($crsenv{'internal.courseowner'} eq 
 7430:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7431:                                     $refused = '';
 7432:                                 }
 7433:                             }
 7434:                         }
 7435:                     }
 7436:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7437:                     $refused = '';
 7438:                 } elsif ($context eq 'requestcourses') {
 7439:                     my @possroles = ('st','ta','ep','in','cc','co');
 7440:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7441:                         my $wrongcc;
 7442:                         if ($cnum =~ /^$match_community$/) {
 7443:                             $wrongcc = 1 if ($role eq 'cc');
 7444:                         } else {
 7445:                             $wrongcc = 1 if ($role eq 'co');
 7446:                         }
 7447:                         unless ($wrongcc) {
 7448:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7449:                             if ($crsenv{'internal.courseowner'} eq 
 7450:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7451:                                 $refused = '';
 7452:                             }
 7453:                         }
 7454:                     }
 7455:                 }
 7456:                 if ($refused) {
 7457:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7458:                              ' '.$role.' '.$end.' '.$start.' by '.
 7459: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7460:                     return 'refused';
 7461:                 }
 7462:             }
 7463:         } elsif ($role eq 'au') {
 7464:             if ($url ne '/'.$udom.'/') {
 7465:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7466:                          ' to assign author role for '.$uname.':'.$udom.
 7467:                          ' in domain: '.$url.' refused (wrong domain).');
 7468:                 return 'refused';
 7469:             }
 7470:         }
 7471:         $mrole=$role;
 7472:     }
 7473:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7474:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7475:     if ($end) { $command.='_'.$end; }
 7476:     if ($start) {
 7477: 	if ($end) { 
 7478:            $command.='_'.$start; 
 7479:         } else {
 7480:            $command.='_0_'.$start;
 7481:         }
 7482:     }
 7483:     my $origstart = $start;
 7484:     my $origend = $end;
 7485:     my $delflag;
 7486: # actually delete
 7487:     if ($deleteflag) {
 7488: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7489: # modify command to delete the role
 7490:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7491:                 "$udom:$uname:$url".'_'."$mrole";
 7492: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7493: # set start and finish to negative values for userrolelog
 7494:            $start=-1;
 7495:            $end=-1;
 7496:            $delflag = 1;
 7497:         }
 7498:     }
 7499: # send command
 7500:     my $answer=&reply($command,&homeserver($uname,$udom));
 7501: # log new user role if status is ok
 7502:     if ($answer eq 'ok') {
 7503: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7504: # for course roles, perform group memberships changes triggered by role change.
 7505:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7506:         unless ($role =~ /^gr/) {
 7507:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7508:                                              $origstart,$selfenroll,$context);
 7509:         }
 7510:         if ($role eq 'cc') {
 7511:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7512:         }
 7513:     }
 7514:     return $answer;
 7515: }
 7516: 
 7517: sub autoupdate_coowners {
 7518:     my ($url,$end,$start,$uname,$udom) = @_;
 7519:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7520:     if (($cdom ne '') && ($cnum ne '')) {
 7521:         my $now = time;
 7522:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7523:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7524:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7525:             my $instcode = $coursehash{'internal.coursecode'};
 7526:             if ($instcode ne '') {
 7527:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7528:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7529:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7530:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7531:                         if ($result eq 'valid') {
 7532:                             if ($coursehash{'internal.co-owners'}) {
 7533:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7534:                                     push(@newcoowners,$coowner);
 7535:                                 }
 7536:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7537:                                     push(@newcoowners,$uname.':'.$udom);
 7538:                                 }
 7539:                                 @newcoowners = sort(@newcoowners);
 7540:                             } else {
 7541:                                 push(@newcoowners,$uname.':'.$udom);
 7542:                             }
 7543:                         } else {
 7544:                             if ($coursehash{'internal.co-owners'}) {
 7545:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7546:                                     unless ($coowner eq $uname.':'.$udom) {
 7547:                                         push(@newcoowners,$coowner);
 7548:                                     }
 7549:                                 }
 7550:                                 unless (@newcoowners > 0) {
 7551:                                     $delcoowners = 1;
 7552:                                     $coowners = '';
 7553:                                 }
 7554:                             }
 7555:                         }
 7556:                         if (@newcoowners || $delcoowners) {
 7557:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7558:                                             $delcoowners,@newcoowners);
 7559:                         }
 7560:                     }
 7561:                 }
 7562:             }
 7563:         }
 7564:     }
 7565: }
 7566: 
 7567: sub store_coowners {
 7568:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7569:     my $cid = $cdom.'_'.$cnum;
 7570:     my ($coowners,$delresult,$putresult);
 7571:     if (@newcoowners) {
 7572:         $coowners = join(',',@newcoowners);
 7573:         my %coownershash = (
 7574:                             'internal.co-owners' => $coowners,
 7575:                            );
 7576:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7577:         if ($putresult eq 'ok') {
 7578:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7579:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7580:             }
 7581:         }
 7582:     }
 7583:     if ($delcoowners) {
 7584:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7585:         if ($delresult eq 'ok') {
 7586:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7587:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7588:             }
 7589:         }
 7590:     }
 7591:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7592:         my %crsinfo =
 7593:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7594:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7595:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7596:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7597:         }
 7598:     }
 7599: }
 7600: 
 7601: # -------------------------------------------------- Modify user authentication
 7602: # Overrides without validation
 7603: 
 7604: sub modifyuserauth {
 7605:     my ($udom,$uname,$umode,$upass)=@_;
 7606:     my $uhome=&homeserver($uname,$udom);
 7607:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7608:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7609:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7610:              ' in domain '.$env{'request.role.domain'});  
 7611:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7612: 		     &escape($upass),$uhome);
 7613:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7614:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7615:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7616:     &log($udom,,$uname,$uhome,
 7617:         'Authentication changed by '.$env{'user.domain'}.', '.
 7618:                                      $env{'user.name'}.', '.$umode.
 7619:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7620:     unless ($reply eq 'ok') {
 7621:         &logthis('Authentication mode error: '.$reply);
 7622: 	return 'error: '.$reply;
 7623:     }   
 7624:     return 'ok';
 7625: }
 7626: 
 7627: # --------------------------------------------------------------- Modify a user
 7628: 
 7629: sub modifyuser {
 7630:     my ($udom,    $uname, $uid,
 7631:         $umode,   $upass, $first,
 7632:         $middle,  $last,  $gene,
 7633:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7634:     $udom= &LONCAPA::clean_domain($udom);
 7635:     $uname=&LONCAPA::clean_username($uname);
 7636:     my $showcandelete = 'none';
 7637:     if (ref($candelete) eq 'ARRAY') {
 7638:         if (@{$candelete} > 0) {
 7639:             $showcandelete = join(', ',@{$candelete});
 7640:         }
 7641:     }
 7642:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7643:              $umode.', '.$first.', '.$middle.', '.
 7644: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7645:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7646:                                      ' desiredhome not specified'). 
 7647:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7648:              ' in domain '.$env{'request.role.domain'});
 7649:     my $uhome=&homeserver($uname,$udom,'true');
 7650:     my $newuser;
 7651:     if ($uhome eq 'no_host') {
 7652:         $newuser = 1;
 7653:     }
 7654: # ----------------------------------------------------------------- Create User
 7655:     if (($uhome eq 'no_host') && 
 7656: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7657:         my $unhome='';
 7658:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7659:             $unhome = $desiredhome;
 7660: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7661: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7662:         } else { # load balancing routine for determining $unhome
 7663:             my $loadm=10000000;
 7664: 	    my %servers = &get_servers($udom,'library');
 7665: 	    foreach my $tryserver (keys(%servers)) {
 7666: 		my $answer=reply('load',$tryserver);
 7667: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7668: 		    $loadm=$answer;
 7669: 		    $unhome=$tryserver;
 7670: 		}
 7671: 	    }
 7672:         }
 7673:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7674: 	    return 'error: unable to find a home server for '.$uname.
 7675:                    ' in domain '.$udom;
 7676:         }
 7677:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7678:                          &escape($upass),$unhome);
 7679: 	unless ($reply eq 'ok') {
 7680:             return 'error: '.$reply;
 7681:         }   
 7682:         $uhome=&homeserver($uname,$udom,'true');
 7683:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7684: 	    return 'error: unable verify users home machine.';
 7685:         }
 7686:     }   # End of creation of new user
 7687: # ---------------------------------------------------------------------- Add ID
 7688:     if ($uid) {
 7689:        $uid=~tr/A-Z/a-z/;
 7690:        my %uidhash=&idrget($udom,$uname);
 7691:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7692:          && (!$forceid)) {
 7693: 	  unless ($uid eq $uidhash{$uname}) {
 7694: 	      return 'error: user id "'.$uid.'" does not match '.
 7695:                   'current user id "'.$uidhash{$uname}.'".';
 7696:           }
 7697:        } else {
 7698: 	  &idput($udom,($uname => $uid));
 7699:        }
 7700:     }
 7701: # -------------------------------------------------------------- Add names, etc
 7702:     my @tmp=&get('environment',
 7703: 		   ['firstname','middlename','lastname','generation','id',
 7704:                     'permanentemail','inststatus'],
 7705: 		   $udom,$uname);
 7706:     my (%names,%oldnames);
 7707:     if ($tmp[0] =~ m/^error:.*/) { 
 7708:         %names=(); 
 7709:     } else {
 7710:         %names = @tmp;
 7711:         %oldnames = %names;
 7712:     }
 7713: #
 7714: # If name, email and/or uid are blank (e.g., because an uploaded file
 7715: # of users did not contain them), do not overwrite existing values
 7716: # unless field is in $candelete array ref.  
 7717: #
 7718: 
 7719:     my @fields = ('firstname','middlename','lastname','generation',
 7720:                   'permanentemail','id');
 7721:     my %newvalues;
 7722:     if (ref($candelete) eq 'ARRAY') {
 7723:         foreach my $field (@fields) {
 7724:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7725:                 if ($field eq 'firstname') {
 7726:                     $names{$field} = $first;
 7727:                 } elsif ($field eq 'middlename') {
 7728:                     $names{$field} = $middle;
 7729:                 } elsif ($field eq 'lastname') {
 7730:                     $names{$field} = $last;
 7731:                 } elsif ($field eq 'generation') { 
 7732:                     $names{$field} = $gene;
 7733:                 } elsif ($field eq 'permanentemail') {
 7734:                     $names{$field} = $email;
 7735:                 } elsif ($field eq 'id') {
 7736:                     $names{$field}  = $uid;
 7737:                 }
 7738:             }
 7739:         }
 7740:     }
 7741:     if ($first)  { $names{'firstname'}  = $first; }
 7742:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7743:     if ($last)   { $names{'lastname'}   = $last; }
 7744:     if (defined($gene))   { $names{'generation'} = $gene; }
 7745:     if ($email) {
 7746:        $email=~s/[^\w\@\.\-\,]//gs;
 7747:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7748:     }
 7749:     if ($uid) { $names{'id'}  = $uid; }
 7750:     if (defined($inststatus)) {
 7751:         $names{'inststatus'} = '';
 7752:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7753:         if (ref($usertypes) eq 'HASH') {
 7754:             my @okstatuses; 
 7755:             foreach my $item (split(/:/,$inststatus)) {
 7756:                 if (defined($usertypes->{$item})) {
 7757:                     push(@okstatuses,$item);  
 7758:                 }
 7759:             }
 7760:             if (@okstatuses) {
 7761:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7762:             }
 7763:         }
 7764:     }
 7765:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7766:                  $umode.', '.$first.', '.$middle.', '.
 7767:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7768:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7769:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7770:     } else {
 7771:         $logmsg .= ' during self creation';
 7772:     }
 7773:     my $changed;
 7774:     if ($newuser) {
 7775:         $changed = 1;
 7776:     } else {
 7777:         foreach my $field (@fields) {
 7778:             if ($names{$field} ne $oldnames{$field}) {
 7779:                 $changed = 1;
 7780:                 last;
 7781:             }
 7782:         }
 7783:     }
 7784:     unless ($changed) {
 7785:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7786:         &logthis($logmsg);
 7787:         return 'ok';
 7788:     }
 7789:     my $reply = &put('environment', \%names, $udom,$uname);
 7790:     if ($reply ne 'ok') { 
 7791:         return 'error: '.$reply;
 7792:     }
 7793:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7794:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7795:     }
 7796:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7797:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7798:     $logmsg = 'Success modifying user '.$logmsg;
 7799:     &logthis($logmsg);
 7800:     return 'ok';
 7801: }
 7802: 
 7803: # -------------------------------------------------------------- Modify student
 7804: 
 7805: sub modifystudent {
 7806:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7807:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7808:         $selfenroll,$context,$inststatus)=@_;
 7809:     if (!$cid) {
 7810: 	unless ($cid=$env{'request.course.id'}) {
 7811: 	    return 'not_in_class';
 7812: 	}
 7813:     }
 7814: # --------------------------------------------------------------- Make the user
 7815:     my $reply=&modifyuser
 7816: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7817:          $desiredhome,$email,$inststatus);
 7818:     unless ($reply eq 'ok') { return $reply; }
 7819:     # This will cause &modify_student_enrollment to get the uid from the
 7820:     # students environment
 7821:     $uid = undef if (!$forceid);
 7822:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7823: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7824:     return $reply;
 7825: }
 7826: 
 7827: sub modify_student_enrollment {
 7828:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7829:     my ($cdom,$cnum,$chome);
 7830:     if (!$cid) {
 7831: 	unless ($cid=$env{'request.course.id'}) {
 7832: 	    return 'not_in_class';
 7833: 	}
 7834: 	$cdom=$env{'course.'.$cid.'.domain'};
 7835: 	$cnum=$env{'course.'.$cid.'.num'};
 7836:     } else {
 7837: 	($cdom,$cnum)=split(/_/,$cid);
 7838:     }
 7839:     $chome=$env{'course.'.$cid.'.home'};
 7840:     if (!$chome) {
 7841: 	$chome=&homeserver($cnum,$cdom);
 7842:     }
 7843:     if (!$chome) { return 'unknown_course'; }
 7844:     # Make sure the user exists
 7845:     my $uhome=&homeserver($uname,$udom);
 7846:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7847: 	return 'error: no such user';
 7848:     }
 7849:     # Get student data if we were not given enough information
 7850:     if (!defined($first)  || $first  eq '' || 
 7851:         !defined($last)   || $last   eq '' || 
 7852:         !defined($uid)    || $uid    eq '' || 
 7853:         !defined($middle) || $middle eq '' || 
 7854:         !defined($gene)   || $gene   eq '') {
 7855:         # They did not supply us with enough data to enroll the student, so
 7856:         # we need to pick up more information.
 7857:         my %tmp = &get('environment',
 7858:                        ['firstname','middlename','lastname', 'generation','id']
 7859:                        ,$udom,$uname);
 7860: 
 7861:         #foreach my $key (keys(%tmp)) {
 7862:         #    &logthis("key $key = ".$tmp{$key});
 7863:         #}
 7864:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7865:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7866:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7867:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7868:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7869:     }
 7870:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7871:     my $user = "$uname:$udom";
 7872:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7873:     my $reply=cput('classlist',
 7874: 		   {$user => 
 7875: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7876: 		   $cdom,$cnum);
 7877:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7878:         &devalidate_getsection_cache($udom,$uname,$cid);
 7879:     } else { 
 7880: 	return 'error: '.$reply;
 7881:     }
 7882:     # Add student role to user
 7883:     my $uurl='/'.$cid;
 7884:     $uurl=~s/\_/\//g;
 7885:     if ($usec) {
 7886: 	$uurl.='/'.$usec;
 7887:     }
 7888:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7889:                              $selfenroll,$context);
 7890:     if ($result ne 'ok') {
 7891:         if ($old_entry{$user} ne '') {
 7892:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7893:         } else {
 7894:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7895:         }
 7896:     }
 7897:     return $result; 
 7898: }
 7899: 
 7900: sub format_name {
 7901:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7902:     my $name;
 7903:     if ($first ne 'lastname') {
 7904: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7905:     } else {
 7906: 	if ($lastname=~/\S/) {
 7907: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7908: 	    $name=~s/\s+,/,/;
 7909: 	} else {
 7910: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7911: 	}
 7912:     }
 7913:     $name=~s/^\s+//;
 7914:     $name=~s/\s+$//;
 7915:     $name=~s/\s+/ /g;
 7916:     return $name;
 7917: }
 7918: 
 7919: # ------------------------------------------------- Write to course preferences
 7920: 
 7921: sub writecoursepref {
 7922:     my ($courseid,%prefs)=@_;
 7923:     $courseid=~s/^\///;
 7924:     $courseid=~s/\_/\//g;
 7925:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7926:     my $chome=homeserver($cnum,$cdomain);
 7927:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7928: 	return 'error: no such course';
 7929:     }
 7930:     my $cstring='';
 7931:     foreach my $pref (keys(%prefs)) {
 7932: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7933:     }
 7934:     $cstring=~s/\&$//;
 7935:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7936: }
 7937: 
 7938: # ---------------------------------------------------------- Make/modify course
 7939: 
 7940: sub createcourse {
 7941:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7942:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7943:     $url=&declutter($url);
 7944:     my $cid='';
 7945:     if ($context eq 'requestcourses') {
 7946:         my $can_create = 0;
 7947:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7948:         if ($udom eq $ownerdom) {
 7949:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7950:                                   $context)) {
 7951:                 $can_create = 1;
 7952:             }
 7953:         } else {
 7954:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7955:                                            $category);
 7956:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7957:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7958:                 if (@curr > 0) {
 7959:                     my @options = qw(approval validate autolimit);
 7960:                     my $optregex = join('|',@options);
 7961:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7962:                         $can_create = 1;
 7963:                     }
 7964:                 }
 7965:             }
 7966:         }
 7967:         if ($can_create) {
 7968:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7969:                 unless (&allowed('ccc',$udom)) {
 7970:                     return 'refused'; 
 7971:                 }
 7972:             }
 7973:         } else {
 7974:             return 'refused';
 7975:         }
 7976:     } elsif (!&allowed('ccc',$udom)) {
 7977:         return 'refused';
 7978:     }
 7979: # --------------------------------------------------------------- Get Unique ID
 7980:     my $uname;
 7981:     if ($cnum =~ /^$match_courseid$/) {
 7982:         my $chome=&homeserver($cnum,$udom,'true');
 7983:         if (($chome eq '') || ($chome eq 'no_host')) {
 7984:             $uname = $cnum;
 7985:         } else {
 7986:             $uname = &generate_coursenum($udom,$crstype);
 7987:         }
 7988:     } else {
 7989:         $uname = &generate_coursenum($udom,$crstype);
 7990:     }
 7991:     return $uname if ($uname =~ /^error/);
 7992: # -------------------------------------------------- Check supplied server name
 7993:     if (!defined($course_server)) {
 7994:         if (defined(&domain($udom,'primary'))) {
 7995:             $course_server = &domain($udom,'primary');
 7996:         } else {
 7997:             $course_server = $env{'user.home'}; 
 7998:         }
 7999:     }
 8000:     my %host_servers =
 8001:         &Apache::lonnet::get_servers($udom,'library');
 8002:     unless ($host_servers{$course_server}) {
 8003:         return 'error: invalid home server for course: '.$course_server;
 8004:     }
 8005: # ------------------------------------------------------------- Make the course
 8006:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8007:                       $course_server);
 8008:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8009:     my $uhome=&homeserver($uname,$udom,'true');
 8010:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8011: 	return 'error: no such course';
 8012:     }
 8013: # ----------------------------------------------------------------- Course made
 8014: # log existence
 8015:     my $now = time;
 8016:     my $newcourse = {
 8017:                     $udom.'_'.$uname => {
 8018:                                      description => $description,
 8019:                                      inst_code   => $inst_code,
 8020:                                      owner       => $course_owner,
 8021:                                      type        => $crstype,
 8022:                                      creator     => $env{'user.name'}.':'.
 8023:                                                     $env{'user.domain'},
 8024:                                      created     => $now,
 8025:                                      context     => $context,
 8026:                                                 },
 8027:                     };
 8028:     &courseidput($udom,$newcourse,$uhome,'notime');
 8029: # set toplevel url
 8030:     my $topurl=$url;
 8031:     unless ($nonstandard) {
 8032: # ------------------------------------------ For standard courses, make top url
 8033:         my $mapurl=&clutter($url);
 8034:         if ($mapurl eq '/res/') { $mapurl=''; }
 8035:         $env{'form.initmap'}=(<<ENDINITMAP);
 8036: <map>
 8037: <resource id="1" type="start"></resource>
 8038: <resource id="2" src="$mapurl"></resource>
 8039: <resource id="3" type="finish"></resource>
 8040: <link index="1" from="1" to="2"></link>
 8041: <link index="2" from="2" to="3"></link>
 8042: </map>
 8043: ENDINITMAP
 8044:         $topurl=&declutter(
 8045:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8046:                           );
 8047:     }
 8048: # ----------------------------------------------------------- Write preferences
 8049:     &writecoursepref($udom.'_'.$uname,
 8050:                      ('description'              => $description,
 8051:                       'url'                      => $topurl,
 8052:                       'internal.creator'         => $env{'user.name'}.':'.
 8053:                                                     $env{'user.domain'},
 8054:                       'internal.created'         => $now,
 8055:                       'internal.creationcontext' => $context)
 8056:                     );
 8057:     return '/'.$udom.'/'.$uname;
 8058: }
 8059: 
 8060: # ------------------------------------------------------------------- Create ID
 8061: sub generate_coursenum {
 8062:     my ($udom,$crstype) = @_;
 8063:     my $domdesc = &domain($udom);
 8064:     return 'error: invalid domain' if ($domdesc eq '');
 8065:     my $first;
 8066:     if ($crstype eq 'Community') {
 8067:         $first = '0';
 8068:     } else {
 8069:         $first = int(1+rand(9)); 
 8070:     } 
 8071:     my $uname=$first.
 8072:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8073:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8074:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8075: # ----------------------------------------------- Make sure that does not exist
 8076:     my $uhome=&homeserver($uname,$udom,'true');
 8077:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8078:         if ($crstype eq 'Community') {
 8079:             $first = '0';
 8080:         } else {
 8081:             $first = int(1+rand(9));
 8082:         }
 8083:         $uname=$first.
 8084:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8085:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8086:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8087:         $uhome=&homeserver($uname,$udom,'true');
 8088:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8089:             return 'error: unable to generate unique course-ID';
 8090:         }
 8091:     }
 8092:     return $uname;
 8093: }
 8094: 
 8095: sub is_course {
 8096:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8097:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8098: 
 8099:     return unless $cdom and $cnum;
 8100: 
 8101:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8102:         '.');
 8103: 
 8104:     return unless exists($courses{$cdom.'_'.$cnum});
 8105:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8106: }
 8107: 
 8108: sub store_userdata {
 8109:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8110:     my $result;
 8111:     if ($datakey ne '') {
 8112:         if (ref($storehash) eq 'HASH') {
 8113:             if ($udom eq '' || $uname eq '') {
 8114:                 $udom = $env{'user.domain'};
 8115:                 $uname = $env{'user.name'};
 8116:             }
 8117:             my $uhome=&homeserver($uname,$udom);
 8118:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8119:                 $result = 'error: no_host';
 8120:             } else {
 8121:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8122:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8123: 
 8124:                 my $namevalue='';
 8125:                 foreach my $key (keys(%{$storehash})) {
 8126:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8127:                 }
 8128:                 $namevalue=~s/\&$//;
 8129:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8130:                                   $namevalue,$uhome);
 8131:             }
 8132:         } else {
 8133:             $result = 'error: data to store was not a hash reference'; 
 8134:         }
 8135:     } else {
 8136:         $result= 'error: invalid requestkey'; 
 8137:     }
 8138:     return $result;
 8139: }
 8140: 
 8141: # ---------------------------------------------------------- Assign Custom Role
 8142: 
 8143: sub assigncustomrole {
 8144:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8145:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8146:                        $end,$start,$deleteflag,$selfenroll,$context);
 8147: }
 8148: 
 8149: # ----------------------------------------------------------------- Revoke Role
 8150: 
 8151: sub revokerole {
 8152:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8153:     my $now=time;
 8154:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8155: }
 8156: 
 8157: # ---------------------------------------------------------- Revoke Custom Role
 8158: 
 8159: sub revokecustomrole {
 8160:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8161:     my $now=time;
 8162:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8163:            $deleteflag,$selfenroll,$context);
 8164: }
 8165: 
 8166: # ------------------------------------------------------------ Disk usage
 8167: sub diskusage {
 8168:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8169:     $directorypath =~ s/\/$//;
 8170:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8171:                        .&escape($getpropath).':'.&escape($uname).':'
 8172:                        .&escape($udom),homeserver($uname,$udom));
 8173:     if ($listing eq 'unknown_cmd') {
 8174:         if ($getpropath) {
 8175:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8176:         }
 8177:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8178:     }
 8179:     return $listing;
 8180: }
 8181: 
 8182: sub is_locked {
 8183:     my ($file_name, $domain, $user, $which) = @_;
 8184:     my @check;
 8185:     my $is_locked;
 8186:     push (@check,$file_name);
 8187:     my %locked = &get('file_permissions',\@check,
 8188: 		      $env{'user.domain'},$env{'user.name'});
 8189:     my ($tmp)=keys(%locked);
 8190:     if ($tmp=~/^error:/) { undef(%locked); }
 8191:     
 8192:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8193:         $is_locked = 'false';
 8194:         foreach my $entry (@{$locked{$file_name}}) {
 8195:            if (ref($entry) eq 'ARRAY') {
 8196:                $is_locked = 'true';
 8197:                if (ref($which) eq 'ARRAY') {
 8198:                    push(@{$which},$entry);
 8199:                } else {
 8200:                    last;
 8201:                }
 8202:            }
 8203:        }
 8204:     } else {
 8205:         $is_locked = 'false';
 8206:     }
 8207:     return $is_locked;
 8208: }
 8209: 
 8210: sub declutter_portfile {
 8211:     my ($file) = @_;
 8212:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8213:     return $file;
 8214: }
 8215: 
 8216: # ------------------------------------------------------------- Mark as Read Only
 8217: 
 8218: sub mark_as_readonly {
 8219:     my ($domain,$user,$files,$what) = @_;
 8220:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8221:     my ($tmp)=keys(%current_permissions);
 8222:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8223:     foreach my $file (@{$files}) {
 8224: 	$file = &declutter_portfile($file);
 8225:         push(@{$current_permissions{$file}},$what);
 8226:     }
 8227:     &put('file_permissions',\%current_permissions,$domain,$user);
 8228:     return;
 8229: }
 8230: 
 8231: # ------------------------------------------------------------Save Selected Files
 8232: 
 8233: sub save_selected_files {
 8234:     my ($user, $path, @files) = @_;
 8235:     my $filename = $user."savedfiles";
 8236:     my @other_files = &files_not_in_path($user, $path);
 8237:     open (OUT, '>'.$tmpdir.$filename);
 8238:     foreach my $file (@files) {
 8239:         print (OUT $env{'form.currentpath'}.$file."\n");
 8240:     }
 8241:     foreach my $file (@other_files) {
 8242:         print (OUT $file."\n");
 8243:     }
 8244:     close (OUT);
 8245:     return 'ok';
 8246: }
 8247: 
 8248: sub clear_selected_files {
 8249:     my ($user) = @_;
 8250:     my $filename = $user."savedfiles";
 8251:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8252:     print (OUT undef);
 8253:     close (OUT);
 8254:     return ("ok");    
 8255: }
 8256: 
 8257: sub files_in_path {
 8258:     my ($user, $path) = @_;
 8259:     my $filename = $user."savedfiles";
 8260:     my %return_files;
 8261:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8262:     while (my $line_in = <IN>) {
 8263:         chomp ($line_in);
 8264:         my @paths_and_file = split (m!/!, $line_in);
 8265:         my $file_part = pop (@paths_and_file);
 8266:         my $path_part = join ('/', @paths_and_file);
 8267:         $path_part.='/';
 8268:         my $path_and_file = $path_part.$file_part;
 8269:         if ($path_part eq $path) {
 8270:             $return_files{$file_part}= 'selected';
 8271:         }
 8272:     }
 8273:     close (IN);
 8274:     return (\%return_files);
 8275: }
 8276: 
 8277: # called in portfolio select mode, to show files selected NOT in current directory
 8278: sub files_not_in_path {
 8279:     my ($user, $path) = @_;
 8280:     my $filename = $user."savedfiles";
 8281:     my @return_files;
 8282:     my $path_part;
 8283:     open(IN, '<'.LONCAPA::.$filename);
 8284:     while (my $line = <IN>) {
 8285:         #ok, I know it's clunky, but I want it to work
 8286:         my @paths_and_file = split(m|/|, $line);
 8287:         my $file_part = pop(@paths_and_file);
 8288:         chomp($file_part);
 8289:         my $path_part = join('/', @paths_and_file);
 8290:         $path_part .= '/';
 8291:         my $path_and_file = $path_part.$file_part;
 8292:         if ($path_part ne $path) {
 8293:             push(@return_files, ($path_and_file));
 8294:         }
 8295:     }
 8296:     close(OUT);
 8297:     return (@return_files);
 8298: }
 8299: 
 8300: #----------------------------------------------Get portfolio file permissions
 8301: 
 8302: sub get_portfile_permissions {
 8303:     my ($domain,$user) = @_;
 8304:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8305:     my ($tmp)=keys(%current_permissions);
 8306:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8307:     return \%current_permissions;
 8308: }
 8309: 
 8310: #---------------------------------------------Get portfolio file access controls
 8311: 
 8312: sub get_access_controls {
 8313:     my ($current_permissions,$group,$file) = @_;
 8314:     my %access;
 8315:     my $real_file = $file;
 8316:     $file =~ s/\.meta$//;
 8317:     if (defined($file)) {
 8318:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8319:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8320:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8321:             }
 8322:         }
 8323:     } else {
 8324:         foreach my $key (keys(%{$current_permissions})) {
 8325:             if ($key =~ /\0accesscontrol$/) {
 8326:                 if (defined($group)) {
 8327:                     if ($key !~ m-^\Q$group\E/-) {
 8328:                         next;
 8329:                     }
 8330:                 }
 8331:                 my ($fullpath) = split(/\0/,$key);
 8332:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8333:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8334:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8335:                     }
 8336:                 }
 8337:             }
 8338:         }
 8339:     }
 8340:     return %access;
 8341: }
 8342: 
 8343: sub modify_access_controls {
 8344:     my ($file_name,$changes,$domain,$user)=@_;
 8345:     my ($outcome,$deloutcome);
 8346:     my %store_permissions;
 8347:     my %new_values;
 8348:     my %new_control;
 8349:     my %translation;
 8350:     my @deletions = ();
 8351:     my $now = time;
 8352:     if (exists($$changes{'activate'})) {
 8353:         if (ref($$changes{'activate'}) eq 'HASH') {
 8354:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8355:             my $numnew = scalar(@newitems);
 8356:             for (my $i=0; $i<$numnew; $i++) {
 8357:                 my $newkey = $newitems[$i];
 8358:                 my $newid = &Apache::loncommon::get_cgi_id();
 8359:                 if ($newkey =~ /^\d+:/) { 
 8360:                     $newkey =~ s/^(\d+)/$newid/;
 8361:                     $translation{$1} = $newid;
 8362:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8363:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8364:                     $translation{$1} = $newid;
 8365:                 }
 8366:                 $new_values{$file_name."\0".$newkey} = 
 8367:                                           $$changes{'activate'}{$newitems[$i]};
 8368:                 $new_control{$newkey} = $now;
 8369:             }
 8370:         }
 8371:     }
 8372:     my %todelete;
 8373:     my %changed_items;
 8374:     foreach my $action ('delete','update') {
 8375:         if (exists($$changes{$action})) {
 8376:             if (ref($$changes{$action}) eq 'HASH') {
 8377:                 foreach my $key (keys(%{$$changes{$action}})) {
 8378:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8379:                     if ($action eq 'delete') { 
 8380:                         $todelete{$itemnum} = 1;
 8381:                     } else {
 8382:                         $changed_items{$itemnum} = $key;
 8383:                     }
 8384:                 }
 8385:             }
 8386:         }
 8387:     }
 8388:     # get lock on access controls for file.
 8389:     my $lockhash = {
 8390:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8391:                                                        ':'.$env{'user.domain'},
 8392:                    }; 
 8393:     my $tries = 0;
 8394:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8395:    
 8396:     while (($gotlock ne 'ok') && $tries <3) {
 8397:         $tries ++;
 8398:         sleep 1;
 8399:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8400:     }
 8401:     if ($gotlock eq 'ok') {
 8402:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8403:         my ($tmp)=keys(%curr_permissions);
 8404:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8405:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8406:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8407:             if (ref($curr_controls) eq 'HASH') {
 8408:                 foreach my $control_item (keys(%{$curr_controls})) {
 8409:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8410:                     if (defined($todelete{$itemnum})) {
 8411:                         push(@deletions,$file_name."\0".$control_item);
 8412:                     } else {
 8413:                         if (defined($changed_items{$itemnum})) {
 8414:                             $new_control{$changed_items{$itemnum}} = $now;
 8415:                             push(@deletions,$file_name."\0".$control_item);
 8416:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8417:                         } else {
 8418:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8419:                         }
 8420:                     }
 8421:                 }
 8422:             }
 8423:         }
 8424:         my ($group);
 8425:         if (&is_course($domain,$user)) {
 8426:             ($group,my $file) = split(/\//,$file_name,2);
 8427:         }
 8428:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8429:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8430:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8431:         #  remove lock
 8432:         my @del_lock = ($file_name."\0".'locked_access_records');
 8433:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8434:         my $sqlresult =
 8435:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8436:                                     $group);
 8437:     } else {
 8438:         $outcome = "error: could not obtain lockfile\n";  
 8439:     }
 8440:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8441: }
 8442: 
 8443: sub make_public_indefinitely {
 8444:     my ($requrl) = @_;
 8445:     my $now = time;
 8446:     my $action = 'activate';
 8447:     my $aclnum = 0;
 8448:     if (&is_portfolio_url($requrl)) {
 8449:         my (undef,$udom,$unum,$file_name,$group) =
 8450:             &parse_portfolio_url($requrl);
 8451:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8452:         my %access_controls = &get_access_controls($current_perms,
 8453:                                                    $group,$file_name);
 8454:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8455:             my ($num,$scope,$end,$start) = 
 8456:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8457:             if ($scope eq 'public') {
 8458:                 if ($start <= $now && $end == 0) {
 8459:                     $action = 'none';
 8460:                 } else {
 8461:                     $action = 'update';
 8462:                     $aclnum = $num;
 8463:                 }
 8464:                 last;
 8465:             }
 8466:         }
 8467:         if ($action eq 'none') {
 8468:              return 'ok';
 8469:         } else {
 8470:             my %changes;
 8471:             my $newend = 0;
 8472:             my $newstart = $now;
 8473:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8474:             $changes{$action}{$newkey} = {
 8475:                 type => 'public',
 8476:                 time => {
 8477:                     start => $newstart,
 8478:                     end   => $newend,
 8479:                 },
 8480:             };
 8481:             my ($outcome,$deloutcome,$new_values,$translation) =
 8482:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8483:             return $outcome;
 8484:         }
 8485:     } else {
 8486:         return 'invalid';
 8487:     }
 8488: }
 8489: 
 8490: #------------------------------------------------------Get Marked as Read Only
 8491: 
 8492: sub get_marked_as_readonly {
 8493:     my ($domain,$user,$what,$group) = @_;
 8494:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8495:     my @readonly_files;
 8496:     my $cmp1=$what;
 8497:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8498:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8499:         if (defined($group)) {
 8500:             if ($file_name !~ m-^\Q$group\E/-) {
 8501:                 next;
 8502:             }
 8503:         }
 8504:         if (ref($value) eq "ARRAY"){
 8505:             foreach my $stored_what (@{$value}) {
 8506:                 my $cmp2=$stored_what;
 8507:                 if (ref($stored_what) eq 'ARRAY') {
 8508:                     $cmp2=join('',@{$stored_what});
 8509:                 }
 8510:                 if ($cmp1 eq $cmp2) {
 8511:                     push(@readonly_files, $file_name);
 8512:                     last;
 8513:                 } elsif (!defined($what)) {
 8514:                     push(@readonly_files, $file_name);
 8515:                     last;
 8516:                 }
 8517:             }
 8518:         }
 8519:     }
 8520:     return @readonly_files;
 8521: }
 8522: #-----------------------------------------------------------Get Marked as Read Only Hash
 8523: 
 8524: sub get_marked_as_readonly_hash {
 8525:     my ($current_permissions,$group,$what) = @_;
 8526:     my %readonly_files;
 8527:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8528:         if (defined($group)) {
 8529:             if ($file_name !~ m-^\Q$group\E/-) {
 8530:                 next;
 8531:             }
 8532:         }
 8533:         if (ref($value) eq "ARRAY"){
 8534:             foreach my $stored_what (@{$value}) {
 8535:                 if (ref($stored_what) eq 'ARRAY') {
 8536:                     foreach my $lock_descriptor(@{$stored_what}) {
 8537:                         if ($lock_descriptor eq 'graded') {
 8538:                             $readonly_files{$file_name} = 'graded';
 8539:                         } elsif ($lock_descriptor eq 'handback') {
 8540:                             $readonly_files{$file_name} = 'handback';
 8541:                         } else {
 8542:                             if (!exists($readonly_files{$file_name})) {
 8543:                                 $readonly_files{$file_name} = 'locked';
 8544:                             }
 8545:                         }
 8546:                     }
 8547:                 } 
 8548:             }
 8549:         } 
 8550:     }
 8551:     return %readonly_files;
 8552: }
 8553: # ------------------------------------------------------------ Unmark as Read Only
 8554: 
 8555: sub unmark_as_readonly {
 8556:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8557:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8558:     my ($domain,$user,$what,$file_name,$group) = @_;
 8559:     $file_name = &declutter_portfile($file_name);
 8560:     my $symb_crs = $what;
 8561:     if (ref($what)) { $symb_crs=join('',@$what); }
 8562:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8563:     my ($tmp)=keys(%current_permissions);
 8564:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8565:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8566:     foreach my $file (@readonly_files) {
 8567: 	my $clean_file = &declutter_portfile($file);
 8568: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8569: 	my $current_locks = $current_permissions{$file};
 8570:         my @new_locks;
 8571:         my @del_keys;
 8572:         if (ref($current_locks) eq "ARRAY"){
 8573:             foreach my $locker (@{$current_locks}) {
 8574:                 my $compare=$locker;
 8575:                 if (ref($locker) eq 'ARRAY') {
 8576:                     $compare=join('',@{$locker});
 8577:                     if ($compare ne $symb_crs) {
 8578:                         push(@new_locks, $locker);
 8579:                     }
 8580:                 }
 8581:             }
 8582:             if (scalar(@new_locks) > 0) {
 8583:                 $current_permissions{$file} = \@new_locks;
 8584:             } else {
 8585:                 push(@del_keys, $file);
 8586:                 &del('file_permissions',\@del_keys, $domain, $user);
 8587:                 delete($current_permissions{$file});
 8588:             }
 8589:         }
 8590:     }
 8591:     &put('file_permissions',\%current_permissions,$domain,$user);
 8592:     return;
 8593: }
 8594: 
 8595: # ------------------------------------------------------------ Directory lister
 8596: 
 8597: sub dirlist {
 8598:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8599:     $uri=~s/^\///;
 8600:     $uri=~s/\/$//;
 8601:     my ($udom, $uname);
 8602:     if ($getuserdir) {
 8603:         $udom = $userdomain;
 8604:         $uname = $username;
 8605:     } else {
 8606:         (undef,$udom,$uname)=split(/\//,$uri);
 8607:         if(defined($userdomain)) {
 8608:             $udom = $userdomain;
 8609:         }
 8610:         if(defined($username)) {
 8611:             $uname = $username;
 8612:         }
 8613:     }
 8614:     my ($dirRoot,$listing,@listing_results);
 8615: 
 8616:     $dirRoot = $perlvar{'lonDocRoot'};
 8617:     if (defined($getpropath)) {
 8618:         $dirRoot = &propath($udom,$uname);
 8619:         $dirRoot =~ s/\/$//;
 8620:     } elsif (defined($getuserdir)) {
 8621:         my $subdir=$uname.'__';
 8622:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8623:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8624:                    ."/$udom/$subdir/$uname";
 8625:     } elsif (defined($alternateRoot)) {
 8626:         $dirRoot = $alternateRoot;
 8627:     }
 8628: 
 8629:     if($udom) {
 8630:         if($uname) {
 8631:             my $uhome = &homeserver($uname,$udom);
 8632:             if ($uhome eq 'no_host') {
 8633:                 return ([],'no_host');
 8634:             }
 8635:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8636:                               .$getuserdir.':'.&escape($dirRoot)
 8637:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8638:             if ($listing eq 'unknown_cmd') {
 8639:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8640:             } else {
 8641:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8642:             }
 8643:             if ($listing eq 'unknown_cmd') {
 8644:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8645:                 @listing_results = split(/:/,$listing);
 8646:             } else {
 8647:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8648:             }
 8649:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8650:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8651:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8652:                 return ([],$listing);
 8653:             } else {
 8654:                 return (\@listing_results);
 8655:             }
 8656:         } elsif(!$alternateRoot) {
 8657:             my (%allusers,%listerror);
 8658: 	    my %servers = &get_servers($udom,'library');
 8659:  	    foreach my $tryserver (keys(%servers)) {
 8660:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8661:                                   &escape($udom),$tryserver);
 8662:                 if ($listing eq 'unknown_cmd') {
 8663: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8664: 				      $udom, $tryserver);
 8665:                 } else {
 8666:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8667:                 }
 8668: 		if ($listing eq 'unknown_cmd') {
 8669: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8670: 				      $udom, $tryserver);
 8671: 		    @listing_results = split(/:/,$listing);
 8672: 		} else {
 8673: 		    @listing_results =
 8674: 			map { &unescape($_); } split(/:/,$listing);
 8675: 		}
 8676:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8677:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8678:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8679:                     $listerror{$tryserver} = $listing;
 8680:                 } else {
 8681: 		    foreach my $line (@listing_results) {
 8682: 			my ($entry) = split(/&/,$line,2);
 8683: 			$allusers{$entry} = 1;
 8684: 		    }
 8685: 		}
 8686:             }
 8687:             my @alluserslist=();
 8688:             foreach my $user (sort(keys(%allusers))) {
 8689:                 push(@alluserslist,$user.'&user');
 8690:             }
 8691:             return (\@alluserslist);
 8692:         } else {
 8693:             return ([],'missing username');
 8694:         }
 8695:     } elsif(!defined($getpropath)) {
 8696:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8697:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8698:         return (\@all_domains);
 8699:     } else {
 8700:         return ([],'missing domain');
 8701:     }
 8702: }
 8703: 
 8704: # --------------------------------------------- GetFileTimestamp
 8705: # This function utilizes dirlist and returns the date stamp for
 8706: # when it was last modified.  It will also return an error of -1
 8707: # if an error occurs
 8708: 
 8709: sub GetFileTimestamp {
 8710:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8711:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8712:     $studentName   = &LONCAPA::clean_username($studentName);
 8713:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8714:                                     undef,$getuserdir);
 8715:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8716:         return -1;
 8717:     }
 8718:     if (ref($fileref) eq 'ARRAY') {
 8719:         my @stats = split('&',$fileref->[0]);
 8720:         # @stats contains first the filename, then the stat output
 8721:         return $stats[10]; # so this is 10 instead of 9.
 8722:     } else {
 8723:         return -1;
 8724:     }
 8725: }
 8726: 
 8727: sub stat_file {
 8728:     my ($uri) = @_;
 8729:     $uri = &clutter_with_no_wrapper($uri);
 8730: 
 8731:     my ($udom,$uname,$file);
 8732:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8733: 	($udom,$uname,$file) =
 8734: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8735: 	$file = 'userfiles/'.$file;
 8736:     }
 8737:     if ($uri =~ m-^/res/-) {
 8738: 	($udom,$uname) = 
 8739: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8740: 	$file = $uri;
 8741:     }
 8742: 
 8743:     if (!$udom || !$uname || !$file) {
 8744: 	# unable to handle the uri
 8745: 	return ();
 8746:     }
 8747:     my $getpropath;
 8748:     if ($file =~ /^userfiles\//) {
 8749:         $getpropath = 1;
 8750:     }
 8751:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8752:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8753:         return ();
 8754:     } else {
 8755:         if (ref($listref) eq 'ARRAY') {
 8756:             my @stats = split('&',$listref->[0]);
 8757: 	    shift(@stats); #filename is first
 8758: 	    return @stats;
 8759:         }
 8760:     }
 8761:     return ();
 8762: }
 8763: 
 8764: # -------------------------------------------------------- Value of a Condition
 8765: 
 8766: # gets the value of a specific preevaluated condition
 8767: #    stored in the string  $env{user.state.<cid>}
 8768: # or looks up a condition reference in the bighash and if if hasn't
 8769: # already been evaluated recurses into docondval to get the value of
 8770: # the condition, then memoizing it to 
 8771: #   $env{user.state.<cid>.<condition>}
 8772: sub directcondval {
 8773:     my $number=shift;
 8774:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8775: 	&Apache::lonuserstate::evalstate();
 8776:     }
 8777:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8778: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8779:     } elsif ($number =~ /^_/) {
 8780: 	my $sub_condition;
 8781: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8782: 		&GDBM_READER(),0640)) {
 8783: 	    $sub_condition=$bighash{'conditions'.$number};
 8784: 	    untie(%bighash);
 8785: 	}
 8786: 	my $value = &docondval($sub_condition);
 8787: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8788: 	return $value;
 8789:     }
 8790:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8791:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8792:     } else {
 8793:        return 2;
 8794:     }
 8795: }
 8796: 
 8797: # get the collection of conditions for this resource
 8798: sub condval {
 8799:     my $condidx=shift;
 8800:     my $allpathcond='';
 8801:     foreach my $cond (split(/\|/,$condidx)) {
 8802: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8803: 	    $allpathcond.=
 8804: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8805: 	}
 8806:     }
 8807:     $allpathcond=~s/\|$//;
 8808:     return &docondval($allpathcond);
 8809: }
 8810: 
 8811: #evaluates an expression of conditions
 8812: sub docondval {
 8813:     my ($allpathcond) = @_;
 8814:     my $result=0;
 8815:     if ($env{'request.course.id'}
 8816: 	&& defined($allpathcond)) {
 8817: 	my $operand='|';
 8818: 	my @stack;
 8819: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8820: 	    if ($chunk eq '(') {
 8821: 		push @stack,($operand,$result);
 8822: 	    } elsif ($chunk eq ')') {
 8823: 		my $before=pop @stack;
 8824: 		if (pop @stack eq '&') {
 8825: 		    $result=$result>$before?$before:$result;
 8826: 		} else {
 8827: 		    $result=$result>$before?$result:$before;
 8828: 		}
 8829: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8830: 		$operand=$chunk;
 8831: 	    } else {
 8832: 		my $new=directcondval($chunk);
 8833: 		if ($operand eq '&') {
 8834: 		    $result=$result>$new?$new:$result;
 8835: 		} else {
 8836: 		    $result=$result>$new?$result:$new;
 8837: 		}
 8838: 	    }
 8839: 	}
 8840:     }
 8841:     return $result;
 8842: }
 8843: 
 8844: # ---------------------------------------------------- Devalidate courseresdata
 8845: 
 8846: sub devalidatecourseresdata {
 8847:     my ($coursenum,$coursedomain)=@_;
 8848:     my $hashid=$coursenum.':'.$coursedomain;
 8849:     &devalidate_cache_new('courseres',$hashid);
 8850: }
 8851: 
 8852: 
 8853: # --------------------------------------------------- Course Resourcedata Query
 8854: #
 8855: #  Parameters:
 8856: #      $coursenum    - Number of the course.
 8857: #      $coursedomain - Domain at which the course was created.
 8858: #  Returns:
 8859: #     A hash of the course parameters along (I think) with timestamps
 8860: #     and version info.
 8861: 
 8862: sub get_courseresdata {
 8863:     my ($coursenum,$coursedomain)=@_;
 8864:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8865:     my $hashid=$coursenum.':'.$coursedomain;
 8866:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8867:     my %dumpreply;
 8868:     unless (defined($cached)) {
 8869: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8870: 	$result=\%dumpreply;
 8871: 	my ($tmp) = keys(%dumpreply);
 8872: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8873: 	    &do_cache_new('courseres',$hashid,$result,600);
 8874: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8875: 	    return $tmp;
 8876: 	} elsif ($tmp =~ /^(error)/) {
 8877: 	    $result=undef;
 8878: 	    &do_cache_new('courseres',$hashid,$result,600);
 8879: 	}
 8880:     }
 8881:     return $result;
 8882: }
 8883: 
 8884: sub devalidateuserresdata {
 8885:     my ($uname,$udom)=@_;
 8886:     my $hashid="$udom:$uname";
 8887:     &devalidate_cache_new('userres',$hashid);
 8888: }
 8889: 
 8890: sub get_userresdata {
 8891:     my ($uname,$udom)=@_;
 8892:     #most student don\'t have any data set, check if there is some data
 8893:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8894: 
 8895:     my $hashid="$udom:$uname";
 8896:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8897:     if (!defined($cached)) {
 8898: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8899: 	$result=\%resourcedata;
 8900: 	&do_cache_new('userres',$hashid,$result,600);
 8901:     }
 8902:     my ($tmp)=keys(%$result);
 8903:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8904: 	return $result;
 8905:     }
 8906:     #error 2 occurs when the .db doesn't exist
 8907:     if ($tmp!~/error: 2 /) {
 8908: 	&logthis("<font color=\"blue\">WARNING:".
 8909: 		 " Trying to get resource data for ".
 8910: 		 $uname." at ".$udom.": ".
 8911: 		 $tmp."</font>");
 8912:     } elsif ($tmp=~/error: 2 /) {
 8913: 	#&EXT_cache_set($udom,$uname);
 8914: 	&do_cache_new('userres',$hashid,undef,600);
 8915: 	undef($tmp); # not really an error so don't send it back
 8916:     }
 8917:     return $tmp;
 8918: }
 8919: #----------------------------------------------- resdata - return resource data
 8920: #  Purpose:
 8921: #    Return resource data for either users or for a course.
 8922: #  Parameters:
 8923: #     $name      - Course/user name.
 8924: #     $domain    - Name of the domain the user/course is registered on.
 8925: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8926: #     @which     - Array of names of resources desired.
 8927: #  Returns:
 8928: #     The value of the first reasource in @which that is found in the
 8929: #     resource hash.
 8930: #  Exceptional Conditions:
 8931: #     If the $type passed in is not valid (not the string 'course' or 
 8932: #     'user', an undefined  reference is returned.
 8933: #     If none of the resources are found, an undef is returned
 8934: sub resdata {
 8935:     my ($name,$domain,$type,@which)=@_;
 8936:     my $result;
 8937:     if ($type eq 'course') {
 8938: 	$result=&get_courseresdata($name,$domain);
 8939:     } elsif ($type eq 'user') {
 8940: 	$result=&get_userresdata($name,$domain);
 8941:     }
 8942:     if (!ref($result)) { return $result; }    
 8943:     foreach my $item (@which) {
 8944: 	if (defined($result->{$item->[0]})) {
 8945: 	    return [$result->{$item->[0]},$item->[1]];
 8946: 	}
 8947:     }
 8948:     return undef;
 8949: }
 8950: 
 8951: #
 8952: # EXT resource caching routines
 8953: #
 8954: 
 8955: sub clear_EXT_cache_status {
 8956:     &delenv('cache.EXT.');
 8957: }
 8958: 
 8959: sub EXT_cache_status {
 8960:     my ($target_domain,$target_user) = @_;
 8961:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8962:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8963:         # We know already the user has no data
 8964:         return 1;
 8965:     } else {
 8966:         return 0;
 8967:     }
 8968: }
 8969: 
 8970: sub EXT_cache_set {
 8971:     my ($target_domain,$target_user) = @_;
 8972:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8973:     #&appenv({$cachename => time});
 8974: }
 8975: 
 8976: # --------------------------------------------------------- Value of a Variable
 8977: sub EXT {
 8978: 
 8979:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8980:     unless ($varname) { return ''; }
 8981:     #get real user name/domain, courseid and symb
 8982:     my $courseid;
 8983:     my $publicuser;
 8984:     if ($symbparm) {
 8985: 	$symbparm=&get_symb_from_alias($symbparm);
 8986:     }
 8987:     if (!($uname && $udom)) {
 8988:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8989:       if (!$symbparm) {	$symbparm=$cursymb; }
 8990:     } else {
 8991: 	$courseid=$env{'request.course.id'};
 8992:     }
 8993:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8994:     my $rest;
 8995:     if (defined($therest[0])) {
 8996:        $rest=join('.',@therest);
 8997:     } else {
 8998:        $rest='';
 8999:     }
 9000: 
 9001:     my $qualifierrest=$qualifier;
 9002:     if ($rest) { $qualifierrest.='.'.$rest; }
 9003:     my $spacequalifierrest=$space;
 9004:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9005:     if ($realm eq 'user') {
 9006: # --------------------------------------------------------------- user.resource
 9007: 	if ($space eq 'resource') {
 9008: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9009: 		  || defined($Apache::lonhomework::parsing_a_task))
 9010: 		 &&
 9011: 		 ($symbparm eq &symbread()) ) {	
 9012: 		# if we are in the middle of processing the resource the
 9013: 		# get the value we are planning on committing
 9014:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9015:                     return $Apache::lonhomework::results{$qualifierrest};
 9016:                 } else {
 9017:                     return $Apache::lonhomework::history{$qualifierrest};
 9018:                 }
 9019: 	    } else {
 9020: 		my %restored;
 9021: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9022: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9023: 		} else {
 9024: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9025: 		}
 9026: 		return $restored{$qualifierrest};
 9027: 	    }
 9028: # ----------------------------------------------------------------- user.access
 9029:         } elsif ($space eq 'access') {
 9030: 	    # FIXME - not supporting calls for a specific user
 9031:             return &allowed($qualifier,$rest);
 9032: # ------------------------------------------ user.preferences, user.environment
 9033:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9034: 	    if (($uname eq $env{'user.name'}) &&
 9035: 		($udom eq $env{'user.domain'})) {
 9036: 		return $env{join('.',('environment',$qualifierrest))};
 9037: 	    } else {
 9038: 		my %returnhash;
 9039: 		if (!$publicuser) {
 9040: 		    %returnhash=&userenvironment($udom,$uname,
 9041: 						 $qualifierrest);
 9042: 		}
 9043: 		return $returnhash{$qualifierrest};
 9044: 	    }
 9045: # ----------------------------------------------------------------- user.course
 9046:         } elsif ($space eq 'course') {
 9047: 	    # FIXME - not supporting calls for a specific user
 9048:             return $env{join('.',('request.course',$qualifier))};
 9049: # ------------------------------------------------------------------- user.role
 9050:         } elsif ($space eq 'role') {
 9051: 	    # FIXME - not supporting calls for a specific user
 9052:             my ($role,$where)=split(/\./,$env{'request.role'});
 9053:             if ($qualifier eq 'value') {
 9054: 		return $role;
 9055:             } elsif ($qualifier eq 'extent') {
 9056:                 return $where;
 9057:             }
 9058: # ----------------------------------------------------------------- user.domain
 9059:         } elsif ($space eq 'domain') {
 9060:             return $udom;
 9061: # ------------------------------------------------------------------- user.name
 9062:         } elsif ($space eq 'name') {
 9063:             return $uname;
 9064: # ---------------------------------------------------- Any other user namespace
 9065:         } else {
 9066: 	    my %reply;
 9067: 	    if (!$publicuser) {
 9068: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9069: 	    }
 9070: 	    return $reply{$qualifierrest};
 9071:         }
 9072:     } elsif ($realm eq 'query') {
 9073: # ---------------------------------------------- pull stuff out of query string
 9074:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9075: 						[$spacequalifierrest]);
 9076: 	return $env{'form.'.$spacequalifierrest}; 
 9077:    } elsif ($realm eq 'request') {
 9078: # ------------------------------------------------------------- request.browser
 9079:         if ($space eq 'browser') {
 9080:             return $env{'browser.'.$qualifier};
 9081: # ------------------------------------------------------------ request.filename
 9082:         } else {
 9083:             return $env{'request.'.$spacequalifierrest};
 9084:         }
 9085:     } elsif ($realm eq 'course') {
 9086: # ---------------------------------------------------------- course.description
 9087:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9088:     } elsif ($realm eq 'resource') {
 9089: 
 9090: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9091: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9092: 	}
 9093: 
 9094: 	if ($space eq 'title') {
 9095: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9096: 	    return &gettitle($symbparm);
 9097: 	}
 9098: 	
 9099: 	if ($space eq 'map') {
 9100: 	    my ($map) = &decode_symb($symbparm);
 9101: 	    return &symbread($map);
 9102: 	}
 9103: 	if ($space eq 'filename') {
 9104: 	    if ($symbparm) {
 9105: 		return &clutter((&decode_symb($symbparm))[2]);
 9106: 	    }
 9107: 	    return &hreflocation('',$env{'request.filename'});
 9108: 	}
 9109: 
 9110: 	my ($section, $group, @groups);
 9111: 	my ($courselevelm,$courselevel);
 9112: 	if ($symbparm && defined($courseid) && 
 9113: 	    $courseid eq $env{'request.course.id'}) {
 9114: 
 9115: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9116: 
 9117: # ----------------------------------------------------- Cascading lookup scheme
 9118: 	    my $symbp=$symbparm;
 9119: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9120: 
 9121: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9122: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9123: 
 9124: 	    if (($env{'user.name'} eq $uname) &&
 9125: 		($env{'user.domain'} eq $udom)) {
 9126: 		$section=$env{'request.course.sec'};
 9127:                 @groups = split(/:/,$env{'request.course.groups'});  
 9128:                 @groups=&sort_course_groups($courseid,@groups); 
 9129: 	    } else {
 9130: 		if (! defined($usection)) {
 9131: 		    $section=&getsection($udom,$uname,$courseid);
 9132: 		} else {
 9133: 		    $section = $usection;
 9134: 		}
 9135:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9136: 	    }
 9137: 
 9138: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9139: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9140: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9141: 
 9142: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9143: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9144: 	    $courselevelm=$courseid.'.'.$mapparm;
 9145: 
 9146: # ----------------------------------------------------------- first, check user
 9147: 
 9148: 	    my $userreply=&resdata($uname,$udom,'user',
 9149: 				       ([$courselevelr,'resource'],
 9150: 					[$courselevelm,'map'     ],
 9151: 					[$courselevel, 'course'  ]));
 9152: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9153: 
 9154: # ------------------------------------------------ second, check some of course
 9155:             my $coursereply;
 9156:             if (@groups > 0) {
 9157:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9158:                                        $mapparm,$spacequalifierrest);
 9159:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9160:             }
 9161: 
 9162: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9163: 				  $env{'course.'.$courseid.'.domain'},
 9164: 				  'course',
 9165: 				  ([$seclevelr,   'resource'],
 9166: 				   [$seclevelm,   'map'     ],
 9167: 				   [$seclevel,    'course'  ],
 9168: 				   [$courselevelr,'resource']));
 9169: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9170: 
 9171: # ------------------------------------------------------ third, check map parms
 9172: 	    my %parmhash=();
 9173: 	    my $thisparm='';
 9174: 	    if (tie(%parmhash,'GDBM_File',
 9175: 		    $env{'request.course.fn'}.'_parms.db',
 9176: 		    &GDBM_READER(),0640)) {
 9177: 		$thisparm=$parmhash{$symbparm};
 9178: 		untie(%parmhash);
 9179: 	    }
 9180: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9181: 	}
 9182: # ------------------------------------------ fourth, look in resource metadata
 9183: 
 9184: 	$spacequalifierrest=~s/\./\_/;
 9185: 	my $filename;
 9186: 	if (!$symbparm) { $symbparm=&symbread(); }
 9187: 	if ($symbparm) {
 9188: 	    $filename=(&decode_symb($symbparm))[2];
 9189: 	} else {
 9190: 	    $filename=$env{'request.filename'};
 9191: 	}
 9192: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9193: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9194: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9195: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9196: 
 9197: # ---------------------------------------------- fourth, look in rest of course
 9198: 	if ($symbparm && defined($courseid) && 
 9199: 	    $courseid eq $env{'request.course.id'}) {
 9200: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9201: 				     $env{'course.'.$courseid.'.domain'},
 9202: 				     'course',
 9203: 				     ([$courselevelm,'map'   ],
 9204: 				      [$courselevel, 'course']));
 9205: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9206: 	}
 9207: # ------------------------------------------------------------------ Cascade up
 9208: 	unless ($space eq '0') {
 9209: 	    my @parts=split(/_/,$space);
 9210: 	    my $id=pop(@parts);
 9211: 	    my $part=join('_',@parts);
 9212: 	    if ($part eq '') { $part='0'; }
 9213: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9214: 				 $symbparm,$udom,$uname,$section,1);
 9215: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9216: 	}
 9217: 	if ($recurse) { return undef; }
 9218: 	my $pack_def=&packages_tab_default($filename,$varname);
 9219: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9220: # ---------------------------------------------------- Any other user namespace
 9221:     } elsif ($realm eq 'environment') {
 9222: # ----------------------------------------------------------------- environment
 9223: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9224: 	    return $env{'environment.'.$spacequalifierrest};
 9225: 	} else {
 9226: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9227: 		return '';
 9228: 	    }
 9229: 	    my %returnhash=&userenvironment($udom,$uname,
 9230: 					    $spacequalifierrest);
 9231: 	    return $returnhash{$spacequalifierrest};
 9232: 	}
 9233:     } elsif ($realm eq 'system') {
 9234: # ----------------------------------------------------------------- system.time
 9235: 	if ($space eq 'time') {
 9236: 	    return time;
 9237:         }
 9238:     } elsif ($realm eq 'server') {
 9239: # ----------------------------------------------------------------- system.time
 9240: 	if ($space eq 'name') {
 9241: 	    return $ENV{'SERVER_NAME'};
 9242:         }
 9243:     }
 9244:     return '';
 9245: }
 9246: 
 9247: sub get_reply {
 9248:     my ($reply_value) = @_;
 9249:     if (ref($reply_value) eq 'ARRAY') {
 9250:         if (wantarray) {
 9251: 	    return @$reply_value;
 9252:         }
 9253:         return $reply_value->[0];
 9254:     } else {
 9255:         return $reply_value;
 9256:     }
 9257: }
 9258: 
 9259: sub check_group_parms {
 9260:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9261:     my @groupitems = ();
 9262:     my $resultitem;
 9263:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9264:     foreach my $group (@{$groups}) {
 9265:         foreach my $level (@levels) {
 9266:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9267:              push(@groupitems,[$item,$level->[1]]);
 9268:         }
 9269:     }
 9270:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9271:                             $env{'course.'.$courseid.'.domain'},
 9272:                                      'course',@groupitems);
 9273:     return $coursereply;
 9274: }
 9275: 
 9276: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9277:     my ($courseid,@groups) = @_;
 9278:     @groups = sort(@groups);
 9279:     return @groups;
 9280: }
 9281: 
 9282: sub packages_tab_default {
 9283:     my ($uri,$varname)=@_;
 9284:     my (undef,$part,$name)=split(/\./,$varname);
 9285: 
 9286:     my (@extension,@specifics,$do_default);
 9287:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9288: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9289: 	if ($pack_type eq 'default') {
 9290: 	    $do_default=1;
 9291: 	} elsif ($pack_type eq 'extension') {
 9292: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9293: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9294: 	    # only look at packages defaults for packages that this id is
 9295: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9296: 	}
 9297:     }
 9298:     # first look for a package that matches the requested part id
 9299:     foreach my $package (@specifics) {
 9300: 	my (undef,$pack_type,$pack_part)=@{$package};
 9301: 	next if ($pack_part ne $part);
 9302: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9303: 	    return $packagetab{"$pack_type&$name&default"};
 9304: 	}
 9305:     }
 9306:     # look for any possible matching non extension_ package
 9307:     foreach my $package (@specifics) {
 9308: 	my (undef,$pack_type,$pack_part)=@{$package};
 9309: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9310: 	    return $packagetab{"$pack_type&$name&default"};
 9311: 	}
 9312: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9313: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9314: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9315: 	}
 9316:     }
 9317:     # look for any posible extension_ match
 9318:     foreach my $package (@extension) {
 9319: 	my ($package,$pack_type)=@{$package};
 9320: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9321: 	    return $packagetab{"$pack_type&$name&default"};
 9322: 	}
 9323: 	if (defined($packagetab{$package."&$name&default"})) {
 9324: 	    return $packagetab{$package."&$name&default"};
 9325: 	}
 9326:     }
 9327:     # look for a global default setting
 9328:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9329: 	return $packagetab{"default&$name&default"};
 9330:     }
 9331:     return undef;
 9332: }
 9333: 
 9334: sub add_prefix_and_part {
 9335:     my ($prefix,$part)=@_;
 9336:     my $keyroot;
 9337:     if (defined($prefix) && $prefix !~ /^__/) {
 9338: 	# prefix that has a part already
 9339: 	$keyroot=$prefix;
 9340:     } elsif (defined($prefix)) {
 9341: 	# prefix that is missing a part
 9342: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9343:     } else {
 9344: 	# no prefix at all
 9345: 	if (defined($part)) { $keyroot='_'.$part; }
 9346:     }
 9347:     return $keyroot;
 9348: }
 9349: 
 9350: # ---------------------------------------------------------------- Get metadata
 9351: 
 9352: my %metaentry;
 9353: my %importedpartids;
 9354: sub metadata {
 9355:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9356:     $uri=&declutter($uri);
 9357:     # if it is a non metadata possible uri return quickly
 9358:     if (($uri eq '') || 
 9359: 	(($uri =~ m|^/*adm/|) && 
 9360: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9361:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9362: 	return undef;
 9363:     }
 9364:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9365: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9366: 	return undef;
 9367:     }
 9368:     my $filename=$uri;
 9369:     $uri=~s/\.meta$//;
 9370: #
 9371: # Is the metadata already cached?
 9372: # Look at timestamp of caching
 9373: # Everything is cached by the main uri, libraries are never directly cached
 9374: #
 9375:     if (!defined($liburi)) {
 9376: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9377: 	if (defined($cached)) { return $result->{':'.$what}; }
 9378:     }
 9379:     {
 9380: # Imported parts would go here
 9381:         my %importedids=();
 9382:         my @origfileimportpartids=();
 9383:         my $importedparts=0;
 9384: #
 9385: # Is this a recursive call for a library?
 9386: #
 9387: #	if (! exists($metacache{$uri})) {
 9388: #	    $metacache{$uri}={};
 9389: #	}
 9390: 	my $cachetime = 60*60;
 9391:         if ($liburi) {
 9392: 	    $liburi=&declutter($liburi);
 9393:             $filename=$liburi;
 9394:         } else {
 9395: 	    &devalidate_cache_new('meta',$uri);
 9396: 	    undef(%metaentry);
 9397: 	}
 9398:         my %metathesekeys=();
 9399:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9400: 	my $metastring;
 9401: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9402: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9403: 	    $metastring = 
 9404: 		&Apache::lonnet::ssi_body($which,
 9405: 					  ('grade_target' => 'meta'));
 9406: 	    $cachetime = 1; # only want this cached in the child not long term
 9407: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9408:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9409: 	    my $file=&filelocation('',&clutter($filename));
 9410: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9411: 	    $metastring=&getfile($file);
 9412: 	}
 9413:         my $parser=HTML::LCParser->new(\$metastring);
 9414:         my $token;
 9415:         undef %metathesekeys;
 9416:         while ($token=$parser->get_token) {
 9417: 	    if ($token->[0] eq 'S') {
 9418: 		if (defined($token->[2]->{'package'})) {
 9419: #
 9420: # This is a package - get package info
 9421: #
 9422: 		    my $package=$token->[2]->{'package'};
 9423: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9424: 		    if (defined($token->[2]->{'id'})) { 
 9425: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9426: 		    }
 9427: 		    if ($metaentry{':packages'}) {
 9428: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9429: 		    } else {
 9430: 			$metaentry{':packages'}=$package.$keyroot;
 9431: 		    }
 9432: 		    foreach my $pack_entry (keys(%packagetab)) {
 9433: 			my $part=$keyroot;
 9434: 			$part=~s/^\_//;
 9435: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9436: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9437: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9438: 			    # ignore package.tab specified default values
 9439:                             # here &package_tab_default() will fetch those
 9440: 			    if ($subp eq 'default') { next; }
 9441: 			    my $value=$packagetab{$pack_entry};
 9442: 			    my $unikey;
 9443: 			    if ($pack =~ /_0$/) {
 9444: 				$unikey='parameter_0_'.$name;
 9445: 				$part=0;
 9446: 			    } else {
 9447: 				$unikey='parameter'.$keyroot.'_'.$name;
 9448: 			    }
 9449: 			    if ($subp eq 'display') {
 9450: 				$value.=' [Part: '.$part.']';
 9451: 			    }
 9452: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9453: 			    $metathesekeys{$unikey}=1;
 9454: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9455: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9456: 			    }
 9457: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9458: 				$metaentry{':'.$unikey}=
 9459: 				    $metaentry{':'.$unikey.'.default'};
 9460: 			    }
 9461: 			}
 9462: 		    }
 9463: 		} else {
 9464: #
 9465: # This is not a package - some other kind of start tag
 9466: #
 9467: 		    my $entry=$token->[1];
 9468: 		    my $unikey='';
 9469: 
 9470: 		    if ($entry eq 'import') {
 9471: #
 9472: # Importing a library here
 9473: #
 9474:                         my $location=$parser->get_text('/import');
 9475:                         my $dir=$filename;
 9476:                         $dir=~s|[^/]*$||;
 9477:                         $location=&filelocation($dir,$location);
 9478:                        
 9479:                         my $importmode=$token->[2]->{'importmode'};
 9480:                         if ($importmode eq 'problem') {
 9481: # Import as problem/response
 9482:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9483:                         } elsif ($importmode eq 'part') {
 9484: # Import as part(s)
 9485:                            $importedparts=1;
 9486: # We need to get the original file and the imported file to get the part order correct
 9487: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9488: # Load and inspect original file
 9489:                            if ($#origfileimportpartids<0) {
 9490:                               undef(%importedpartids);
 9491:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9492:                               my $origfile=&getfile($origfilelocation);
 9493:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9494:                            }
 9495: 
 9496: # Load and inspect imported file
 9497:                            my $impfile=&getfile($location);
 9498:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9499:                            if ($#impfilepartids>=0) {
 9500: # This problem had parts
 9501:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9502:                            } else {
 9503: # Importing by turning a single problem into a problem part
 9504: # It gets the import-tags ID as part-ID
 9505:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9506:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9507:                            }
 9508:                         } else {
 9509: # Normal import
 9510:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9511:                            if (defined($token->[2]->{'id'})) {
 9512:                               $unikey.='_'.$token->[2]->{'id'};
 9513:                            }
 9514:                         }
 9515: 
 9516: 			if ($depthcount<20) {
 9517: 			    my $metadata = 
 9518: 				&metadata($uri,'keys', $location,$unikey,
 9519: 					  $depthcount+1);
 9520: 			    foreach my $meta (split(',',$metadata)) {
 9521: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9522: 				$metathesekeys{$meta}=1;
 9523: 			    }
 9524: 			
 9525:                         }
 9526: 		    } else {
 9527: #
 9528: # Not importing, some other kind of non-package, non-library start tag
 9529: # 
 9530:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9531:                         if (defined($token->[2]->{'id'})) {
 9532:                             $unikey.='_'.$token->[2]->{'id'};
 9533:                         }
 9534: 			if (defined($token->[2]->{'name'})) { 
 9535: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9536: 			}
 9537: 			$metathesekeys{$unikey}=1;
 9538: 			foreach my $param (@{$token->[3]}) {
 9539: 			    $metaentry{':'.$unikey.'.'.$param} =
 9540: 				$token->[2]->{$param};
 9541: 			}
 9542: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9543: 			my $default=$metaentry{':'.$unikey.'.default'};
 9544: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9545: 		 # only ws inside the tag, and not in default, so use default
 9546: 		 # as value
 9547: 			    $metaentry{':'.$unikey}=$default;
 9548: 			} elsif ( $internaltext =~ /\S/ ) {
 9549: 		  # something interesting inside the tag
 9550: 			    $metaentry{':'.$unikey}=$internaltext;
 9551: 			} else {
 9552: 		  # no interesting values, don't set a default
 9553: 			}
 9554: # end of not-a-package not-a-library import
 9555: 		    }
 9556: # end of not-a-package start tag
 9557: 		}
 9558: # the next is the end of "start tag"
 9559: 	    }
 9560: 	}
 9561: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9562: 	$extension = lc($extension);
 9563: 	if ($extension eq 'htm') { $extension='html'; }
 9564: 
 9565: 	foreach my $key (keys(%packagetab)) {
 9566: 	    #no specific packages #how's our extension
 9567: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9568: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9569: 					 \%metathesekeys);
 9570: 	}
 9571: 
 9572: 	if (!exists($metaentry{':packages'})
 9573: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9574: 	    foreach my $key (keys(%packagetab)) {
 9575: 		#no specific packages well let's get default then
 9576: 		if ($key!~/^default&/) { next; }
 9577: 		&metadata_create_package_def($uri,$key,'default',
 9578: 					     \%metathesekeys);
 9579: 	    }
 9580: 	}
 9581: # are there custom rights to evaluate
 9582: 	if ($metaentry{':copyright'} eq 'custom') {
 9583: 
 9584:     #
 9585:     # Importing a rights file here
 9586:     #
 9587: 	    unless ($depthcount) {
 9588: 		my $location=$metaentry{':customdistributionfile'};
 9589: 		my $dir=$filename;
 9590: 		$dir=~s|[^/]*$||;
 9591: 		$location=&filelocation($dir,$location);
 9592: 		my $rights_metadata =
 9593: 		    &metadata($uri,'keys',$location,'_rights',
 9594: 			      $depthcount+1);
 9595: 		foreach my $rights (split(',',$rights_metadata)) {
 9596: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9597: 		    $metathesekeys{$rights}=1;
 9598: 		}
 9599: 	    }
 9600: 	}
 9601: 	# uniqifiy package listing
 9602: 	my %seen;
 9603: 	my @uniq_packages =
 9604: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9605: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9606: 
 9607:         if ($importedparts) {
 9608: # We had imported parts and need to rebuild partorder
 9609:            $metaentry{':partorder'}='';
 9610:            $metathesekeys{'partorder'}=1;
 9611:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9612:                if ($origfileimportpartids[$index] eq 'part') {
 9613: # original part, part of the problem
 9614:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9615:                } else {
 9616: # we have imported parts at this position
 9617:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9618:                }
 9619:            }
 9620:            $metaentry{':partorder'}=~s/^\,//;
 9621:         }
 9622: 
 9623: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9624: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9625: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9626: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9627: # this is the end of "was not already recently cached
 9628:     }
 9629:     return $metaentry{':'.$what};
 9630: }
 9631: 
 9632: sub metadata_create_package_def {
 9633:     my ($uri,$key,$package,$metathesekeys)=@_;
 9634:     my ($pack,$name,$subp)=split(/\&/,$key);
 9635:     if ($subp eq 'default') { next; }
 9636:     
 9637:     if (defined($metaentry{':packages'})) {
 9638: 	$metaentry{':packages'}.=','.$package;
 9639:     } else {
 9640: 	$metaentry{':packages'}=$package;
 9641:     }
 9642:     my $value=$packagetab{$key};
 9643:     my $unikey;
 9644:     $unikey='parameter_0_'.$name;
 9645:     $metaentry{':'.$unikey.'.part'}=0;
 9646:     $$metathesekeys{$unikey}=1;
 9647:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9648: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9649:     }
 9650:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9651: 	$metaentry{':'.$unikey}=
 9652: 	    $metaentry{':'.$unikey.'.default'};
 9653:     }
 9654: }
 9655: 
 9656: sub metadata_generate_part0 {
 9657:     my ($metadata,$metacache,$uri) = @_;
 9658:     my %allnames;
 9659:     foreach my $metakey (keys(%$metadata)) {
 9660: 	if ($metakey=~/^parameter\_(.*)/) {
 9661: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9662: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9663: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9664: 	    $allnames{$name}=$part;
 9665: 	  }
 9666: 	}
 9667:     }
 9668:     foreach my $name (keys(%allnames)) {
 9669:       $$metadata{"parameter_0_$name"}=1;
 9670:       my $key=":parameter_0_$name";
 9671:       $$metacache{"$key.part"}='0';
 9672:       $$metacache{"$key.name"}=$name;
 9673:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9674: 					   $allnames{$name}.'_'.$name.
 9675: 					   '.type'};
 9676:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9677: 			     '.display'};
 9678:       my $expr='[Part: '.$allnames{$name}.']';
 9679:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9680:       $$metacache{"$key.display"}=$olddis;
 9681:     }
 9682: }
 9683: 
 9684: # ------------------------------------------------------ Devalidate title cache
 9685: 
 9686: sub devalidate_title_cache {
 9687:     my ($url)=@_;
 9688:     if (!$env{'request.course.id'}) { return; }
 9689:     my $symb=&symbread($url);
 9690:     if (!$symb) { return; }
 9691:     my $key=$env{'request.course.id'}."\0".$symb;
 9692:     &devalidate_cache_new('title',$key);
 9693: }
 9694: 
 9695: # ------------------------------------------------- Get the title of a course
 9696: 
 9697: sub current_course_title {
 9698:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9699: }
 9700: # ------------------------------------------------- Get the title of a resource
 9701: 
 9702: sub gettitle {
 9703:     my $urlsymb=shift;
 9704:     my $symb=&symbread($urlsymb);
 9705:     if ($symb) {
 9706: 	my $key=$env{'request.course.id'}."\0".$symb;
 9707: 	my ($result,$cached)=&is_cached_new('title',$key);
 9708: 	if (defined($cached)) { 
 9709: 	    return $result;
 9710: 	}
 9711: 	my ($map,$resid,$url)=&decode_symb($symb);
 9712: 	my $title='';
 9713: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9714: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9715: 	} else {
 9716: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9717: 		    &GDBM_READER(),0640)) {
 9718: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9719: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9720: 		untie(%bighash);
 9721: 	    }
 9722: 	}
 9723: 	$title=~s/\&colon\;/\:/gs;
 9724: 	if ($title) {
 9725: # Remember both $symb and $title for dynamic metadata
 9726:             $accesshash{$symb.'___crstitle'}=$title;
 9727:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9728: # Cache this title and then return it
 9729: 	    return &do_cache_new('title',$key,$title,600);
 9730: 	}
 9731: 	$urlsymb=$url;
 9732:     }
 9733:     my $title=&metadata($urlsymb,'title');
 9734:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9735:     return $title;
 9736: }
 9737: 
 9738: sub get_slot {
 9739:     my ($which,$cnum,$cdom)=@_;
 9740:     if (!$cnum || !$cdom) {
 9741: 	(undef,my $courseid)=&whichuser();
 9742: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9743: 	$cnum=$env{'course.'.$courseid.'.num'};
 9744:     }
 9745:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9746:     my %slotinfo;
 9747:     if (exists($remembered{$key})) {
 9748: 	$slotinfo{$which} = $remembered{$key};
 9749:     } else {
 9750: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9751: 	&Apache::lonhomework::showhash(%slotinfo);
 9752: 	my ($tmp)=keys(%slotinfo);
 9753: 	if ($tmp=~/^error:/) { return (); }
 9754: 	$remembered{$key} = $slotinfo{$which};
 9755:     }
 9756:     if (ref($slotinfo{$which}) eq 'HASH') {
 9757: 	return %{$slotinfo{$which}};
 9758:     }
 9759:     return $slotinfo{$which};
 9760: }
 9761: 
 9762: sub get_reservable_slots {
 9763:     my ($cnum,$cdom,$uname,$udom) = @_;
 9764:     my $now = time;
 9765:     my $reservable_info;
 9766:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9767:     if (exists($remembered{$key})) {
 9768:         $reservable_info = $remembered{$key};
 9769:     } else {
 9770:         my %resv;
 9771:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9772:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9773:         $reservable_info = \%resv;
 9774:         $remembered{$key} = $reservable_info;
 9775:     }
 9776:     return $reservable_info;
 9777: }
 9778: 
 9779: sub get_course_slots {
 9780:     my ($cnum,$cdom) = @_;
 9781:     my $hashid=$cnum.':'.$cdom;
 9782:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9783:     if (defined($cached)) {
 9784:         if (ref($result) eq 'HASH') {
 9785:             return %{$result};
 9786:         }
 9787:     } else {
 9788:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9789:         my ($tmp) = keys(%slots);
 9790:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9791:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9792:             return %slots;
 9793:         }
 9794:     }
 9795:     return;
 9796: }
 9797: 
 9798: sub devalidate_slots_cache {
 9799:     my ($cnum,$cdom)=@_;
 9800:     my $hashid=$cnum.':'.$cdom;
 9801:     &devalidate_cache_new('allslots',$hashid);
 9802: }
 9803: 
 9804: # ------------------------------------------------- Update symbolic store links
 9805: 
 9806: sub symblist {
 9807:     my ($mapname,%newhash)=@_;
 9808:     $mapname=&deversion(&declutter($mapname));
 9809:     my %hash;
 9810:     if (($env{'request.course.fn'}) && (%newhash)) {
 9811:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9812:                       &GDBM_WRCREAT(),0640)) {
 9813: 	    foreach my $url (keys(%newhash)) {
 9814: 		next if ($url eq 'last_known'
 9815: 			 && $env{'form.no_update_last_known'});
 9816: 		$hash{declutter($url)}=&encode_symb($mapname,
 9817: 						    $newhash{$url}->[1],
 9818: 						    $newhash{$url}->[0]);
 9819:             }
 9820:             if (untie(%hash)) {
 9821: 		return 'ok';
 9822:             }
 9823:         }
 9824:     }
 9825:     return 'error';
 9826: }
 9827: 
 9828: # --------------------------------------------------------------- Verify a symb
 9829: 
 9830: sub symbverify {
 9831:     my ($symb,$thisurl)=@_;
 9832:     my $thisfn=$thisurl;
 9833:     $thisfn=&declutter($thisfn);
 9834: # direct jump to resource in page or to a sequence - will construct own symbs
 9835:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9836: # check URL part
 9837:     my ($map,$resid,$url)=&decode_symb($symb);
 9838: 
 9839:     unless ($url eq $thisfn) { return 0; }
 9840: 
 9841:     $symb=&symbclean($symb);
 9842:     $thisurl=&deversion($thisurl);
 9843:     $thisfn=&deversion($thisfn);
 9844: 
 9845:     my %bighash;
 9846:     my $okay=0;
 9847: 
 9848:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9849:                             &GDBM_READER(),0640)) {
 9850:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9851:             $thisurl =~ s/\?.+$//;
 9852:         }
 9853:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9854:         unless ($ids) {
 9855:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9856:             $ids=$bighash{$idkey};
 9857:         }
 9858:         if ($ids) {
 9859: # ------------------------------------------------------------------- Has ID(s)
 9860: 	    foreach my $id (split(/\,/,$ids)) {
 9861: 	       my ($mapid,$resid)=split(/\./,$id);
 9862:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9863:                    $symb =~ s/\?.+$//;
 9864:                }
 9865:                if (
 9866:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9867:    eq $symb) { 
 9868: 		   if (($env{'request.role.adv'}) ||
 9869: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9870:                        ($thisurl eq '/adm/navmaps')) {
 9871: 		       $okay=1; 
 9872: 		   }
 9873: 	       }
 9874: 	   }
 9875:         }
 9876: 	untie(%bighash);
 9877:     }
 9878:     return $okay;
 9879: }
 9880: 
 9881: # --------------------------------------------------------------- Clean-up symb
 9882: 
 9883: sub symbclean {
 9884:     my $symb=shift;
 9885:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9886: # remove version from map
 9887:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9888: 
 9889: # remove version from URL
 9890:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9891: 
 9892: # remove wrapper
 9893: 
 9894:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9895:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9896:     return $symb;
 9897: }
 9898: 
 9899: # ---------------------------------------------- Split symb to find map and url
 9900: 
 9901: sub encode_symb {
 9902:     my ($map,$resid,$url)=@_;
 9903:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9904: }
 9905: 
 9906: sub decode_symb {
 9907:     my $symb=shift;
 9908:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9909:     my ($map,$resid,$url)=split(/___/,$symb);
 9910:     return (&fixversion($map),$resid,&fixversion($url));
 9911: }
 9912: 
 9913: sub fixversion {
 9914:     my $fn=shift;
 9915:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9916:     my %bighash;
 9917:     my $uri=&clutter($fn);
 9918:     my $key=$env{'request.course.id'}.'_'.$uri;
 9919: # is this cached?
 9920:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9921:     if (defined($cached)) { return $result; }
 9922: # unfortunately not cached, or expired
 9923:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9924: 	    &GDBM_READER(),0640)) {
 9925:  	if ($bighash{'version_'.$uri}) {
 9926:  	    my $version=$bighash{'version_'.$uri};
 9927:  	    unless (($version eq 'mostrecent') || 
 9928: 		    ($version==&getversion($uri))) {
 9929:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9930:  	    }
 9931:  	}
 9932:  	untie %bighash;
 9933:     }
 9934:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9935: }
 9936: 
 9937: sub deversion {
 9938:     my $url=shift;
 9939:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9940:     return $url;
 9941: }
 9942: 
 9943: # ------------------------------------------------------ Return symb list entry
 9944: 
 9945: sub symbread {
 9946:     my ($thisfn,$donotrecurse)=@_;
 9947:     my $cache_str='request.symbread.cached.'.$thisfn;
 9948:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9949: # no filename provided? try from environment
 9950:     unless ($thisfn) {
 9951:         if ($env{'request.symb'}) {
 9952: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9953: 	}
 9954: 	$thisfn=$env{'request.filename'};
 9955:     }
 9956:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9957: # is that filename actually a symb? Verify, clean, and return
 9958:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9959: 	if (&symbverify($thisfn,$1)) {
 9960: 	    return $env{$cache_str}=&symbclean($thisfn);
 9961: 	}
 9962:     }
 9963:     $thisfn=declutter($thisfn);
 9964:     my %hash;
 9965:     my %bighash;
 9966:     my $syval='';
 9967:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9968:         my $targetfn = $thisfn;
 9969:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9970:             $targetfn = 'adm/wrapper/'.$thisfn;
 9971:         }
 9972: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9973: 	    $targetfn=$1;
 9974: 	}
 9975:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9976:                       &GDBM_READER(),0640)) {
 9977: 	    $syval=$hash{$targetfn};
 9978:             untie(%hash);
 9979:         }
 9980: # ---------------------------------------------------------- There was an entry
 9981:         if ($syval) {
 9982: 	    #unless ($syval=~/\_\d+$/) {
 9983: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9984: 		    #&appenv({'request.ambiguous' => $thisfn});
 9985: 		    #return $env{$cache_str}='';
 9986: 		#}    
 9987: 		#$syval.=$1;
 9988: 	    #}
 9989:         } else {
 9990: # ------------------------------------------------------- Was not in symb table
 9991:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9992:                             &GDBM_READER(),0640)) {
 9993: # ---------------------------------------------- Get ID(s) for current resource
 9994:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9995:               unless ($ids) { 
 9996:                  $ids=$bighash{'ids_/'.$thisfn};
 9997:               }
 9998:               unless ($ids) {
 9999: # alias?
10000: 		  $ids=$bighash{'mapalias_'.$thisfn};
10001:               }
10002:               if ($ids) {
10003: # ------------------------------------------------------------------- Has ID(s)
10004:                  my @possibilities=split(/\,/,$ids);
10005:                  if ($#possibilities==0) {
10006: # ----------------------------------------------- There is only one possibility
10007: 		     my ($mapid,$resid)=split(/\./,$ids);
10008: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10009: 						    $resid,$thisfn);
10010:                  } elsif (!$donotrecurse) {
10011: # ------------------------------------------ There is more than one possibility
10012:                      my $realpossible=0;
10013:                      foreach my $id (@possibilities) {
10014: 			 my $file=$bighash{'src_'.$id};
10015:                          if (&allowed('bre',$file)) {
10016:          		    my ($mapid,$resid)=split(/\./,$id);
10017:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10018: 				$realpossible++;
10019:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10020: 						    $resid,$thisfn);
10021:                             }
10022: 			 }
10023:                      }
10024: 		     if ($realpossible!=1) { $syval=''; }
10025:                  } else {
10026:                      $syval='';
10027:                  }
10028: 	      }
10029:               untie(%bighash)
10030:            }
10031:         }
10032:         if ($syval) {
10033: 	    return $env{$cache_str}=$syval;
10034:         }
10035:     }
10036:     &appenv({'request.ambiguous' => $thisfn});
10037:     return $env{$cache_str}='';
10038: }
10039: 
10040: # ---------------------------------------------------------- Return random seed
10041: 
10042: sub numval {
10043:     my $txt=shift;
10044:     $txt=~tr/A-J/0-9/;
10045:     $txt=~tr/a-j/0-9/;
10046:     $txt=~tr/K-T/0-9/;
10047:     $txt=~tr/k-t/0-9/;
10048:     $txt=~tr/U-Z/0-5/;
10049:     $txt=~tr/u-z/0-5/;
10050:     $txt=~s/\D//g;
10051:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10052:     return int($txt);
10053: }
10054: 
10055: sub numval2 {
10056:     my $txt=shift;
10057:     $txt=~tr/A-J/0-9/;
10058:     $txt=~tr/a-j/0-9/;
10059:     $txt=~tr/K-T/0-9/;
10060:     $txt=~tr/k-t/0-9/;
10061:     $txt=~tr/U-Z/0-5/;
10062:     $txt=~tr/u-z/0-5/;
10063:     $txt=~s/\D//g;
10064:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10065:     my $total;
10066:     foreach my $val (@txts) { $total+=$val; }
10067:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10068:     return int($total);
10069: }
10070: 
10071: sub numval3 {
10072:     use integer;
10073:     my $txt=shift;
10074:     $txt=~tr/A-J/0-9/;
10075:     $txt=~tr/a-j/0-9/;
10076:     $txt=~tr/K-T/0-9/;
10077:     $txt=~tr/k-t/0-9/;
10078:     $txt=~tr/U-Z/0-5/;
10079:     $txt=~tr/u-z/0-5/;
10080:     $txt=~s/\D//g;
10081:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10082:     my $total;
10083:     foreach my $val (@txts) { $total+=$val; }
10084:     if ($_64bit) { $total=(($total<<32)>>32); }
10085:     return $total;
10086: }
10087: 
10088: sub digest {
10089:     my ($data)=@_;
10090:     my $digest=&Digest::MD5::md5($data);
10091:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10092:     my ($e,$f);
10093:     {
10094:         use integer;
10095:         $e=($a+$b);
10096:         $f=($c+$d);
10097:         if ($_64bit) {
10098:             $e=(($e<<32)>>32);
10099:             $f=(($f<<32)>>32);
10100:         }
10101:     }
10102:     if (wantarray) {
10103: 	return ($e,$f);
10104:     } else {
10105: 	my $g;
10106: 	{
10107: 	    use integer;
10108: 	    $g=($e+$f);
10109: 	    if ($_64bit) {
10110: 		$g=(($g<<32)>>32);
10111: 	    }
10112: 	}
10113: 	return $g;
10114:     }
10115: }
10116: 
10117: sub latest_rnd_algorithm_id {
10118:     return '64bit5';
10119: }
10120: 
10121: sub get_rand_alg {
10122:     my ($courseid)=@_;
10123:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10124:     if ($courseid) {
10125: 	return $env{"course.$courseid.rndseed"};
10126:     }
10127:     return &latest_rnd_algorithm_id();
10128: }
10129: 
10130: sub validCODE {
10131:     my ($CODE)=@_;
10132:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10133:     return 0;
10134: }
10135: 
10136: sub getCODE {
10137:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10138:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10139: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10140: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10141: 	return $Apache::lonhomework::history{'resource.CODE'};
10142:     }
10143:     return undef;
10144: }
10145: #
10146: #  Determines the random seed for a specific context:
10147: #
10148: # parameters:
10149: #   symb      - in course context the symb for the seed.
10150: #   course_id - The course id of the form domain_coursenum.
10151: #   domain    - Domain for the user.
10152: #   course    - Course for the user.
10153: #   cenv      - environment of the course.
10154: #
10155: # NOTE:
10156: #   All parameters are picked out of the environment if missing
10157: #   or not defined.
10158: #   If a symb cannot be determined the current time is used instead.
10159: #
10160: #  For a given well defined symb, courside, domain, username,
10161: #  and course environment, the seed is reproducible.
10162: #
10163: sub rndseed {
10164:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10165:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10166:     if (!defined($symb)) {
10167: 	unless ($symb=$wsymb) { return time; }
10168:     }
10169:     if (!defined $courseid) { 
10170: 	$courseid=$wcourseid; 
10171:     }
10172:     if (!defined $domain) { $domain=$wdomain; }
10173:     if (!defined $username) { $username=$wusername }
10174: 
10175:     my $which;
10176:     if (defined($cenv->{'rndseed'})) {
10177: 	$which = $cenv->{'rndseed'};
10178:     } else {
10179: 	$which =&get_rand_alg($courseid);
10180:     }
10181:     if (defined(&getCODE())) {
10182: 
10183: 	if ($which eq '64bit5') {
10184: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10185: 	} elsif ($which eq '64bit4') {
10186: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10187: 	} else {
10188: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10189: 	}
10190:     } elsif ($which eq '64bit5') {
10191: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10192:     } elsif ($which eq '64bit4') {
10193: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10194:     } elsif ($which eq '64bit3') {
10195: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10196:     } elsif ($which eq '64bit2') {
10197: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10198:     } elsif ($which eq '64bit') {
10199: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10200:     }
10201:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10202: }
10203: 
10204: sub rndseed_32bit {
10205:     my ($symb,$courseid,$domain,$username)=@_;
10206:     {
10207: 	use integer;
10208: 	my $symbchck=unpack("%32C*",$symb) << 27;
10209: 	my $symbseed=numval($symb) << 22;
10210: 	my $namechck=unpack("%32C*",$username) << 17;
10211: 	my $nameseed=numval($username) << 12;
10212: 	my $domainseed=unpack("%32C*",$domain) << 7;
10213: 	my $courseseed=unpack("%32C*",$courseid);
10214: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10215: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10216: 	#&logthis("rndseed :$num:$symb");
10217: 	if ($_64bit) { $num=(($num<<32)>>32); }
10218: 	return $num;
10219:     }
10220: }
10221: 
10222: sub rndseed_64bit {
10223:     my ($symb,$courseid,$domain,$username)=@_;
10224:     {
10225: 	use integer;
10226: 	my $symbchck=unpack("%32S*",$symb) << 21;
10227: 	my $symbseed=numval($symb) << 10;
10228: 	my $namechck=unpack("%32S*",$username);
10229: 	
10230: 	my $nameseed=numval($username) << 21;
10231: 	my $domainseed=unpack("%32S*",$domain) << 10;
10232: 	my $courseseed=unpack("%32S*",$courseid);
10233: 	
10234: 	my $num1=$symbchck+$symbseed+$namechck;
10235: 	my $num2=$nameseed+$domainseed+$courseseed;
10236: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10237: 	#&logthis("rndseed :$num:$symb");
10238: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10239: 	return "$num1,$num2";
10240:     }
10241: }
10242: 
10243: sub rndseed_64bit2 {
10244:     my ($symb,$courseid,$domain,$username)=@_;
10245:     {
10246: 	use integer;
10247: 	# strings need to be an even # of cahracters long, it it is odd the
10248:         # last characters gets thrown away
10249: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10250: 	my $symbseed=numval($symb) << 10;
10251: 	my $namechck=unpack("%32S*",$username.' ');
10252: 	
10253: 	my $nameseed=numval($username) << 21;
10254: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10255: 	my $courseseed=unpack("%32S*",$courseid.' ');
10256: 	
10257: 	my $num1=$symbchck+$symbseed+$namechck;
10258: 	my $num2=$nameseed+$domainseed+$courseseed;
10259: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10260: 	#&logthis("rndseed :$num:$symb");
10261: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10262: 	return "$num1,$num2";
10263:     }
10264: }
10265: 
10266: sub rndseed_64bit3 {
10267:     my ($symb,$courseid,$domain,$username)=@_;
10268:     {
10269: 	use integer;
10270: 	# strings need to be an even # of cahracters long, it it is odd the
10271:         # last characters gets thrown away
10272: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10273: 	my $symbseed=numval2($symb) << 10;
10274: 	my $namechck=unpack("%32S*",$username.' ');
10275: 	
10276: 	my $nameseed=numval2($username) << 21;
10277: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10278: 	my $courseseed=unpack("%32S*",$courseid.' ');
10279: 	
10280: 	my $num1=$symbchck+$symbseed+$namechck;
10281: 	my $num2=$nameseed+$domainseed+$courseseed;
10282: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10283: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10284: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10285: 	
10286: 	return "$num1:$num2";
10287:     }
10288: }
10289: 
10290: sub rndseed_64bit4 {
10291:     my ($symb,$courseid,$domain,$username)=@_;
10292:     {
10293: 	use integer;
10294: 	# strings need to be an even # of cahracters long, it it is odd the
10295:         # last characters gets thrown away
10296: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10297: 	my $symbseed=numval3($symb) << 10;
10298: 	my $namechck=unpack("%32S*",$username.' ');
10299: 	
10300: 	my $nameseed=numval3($username) << 21;
10301: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10302: 	my $courseseed=unpack("%32S*",$courseid.' ');
10303: 	
10304: 	my $num1=$symbchck+$symbseed+$namechck;
10305: 	my $num2=$nameseed+$domainseed+$courseseed;
10306: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10307: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10308: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10309: 	
10310: 	return "$num1:$num2";
10311:     }
10312: }
10313: 
10314: sub rndseed_64bit5 {
10315:     my ($symb,$courseid,$domain,$username)=@_;
10316:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10317:     return "$num1:$num2";
10318: }
10319: 
10320: sub rndseed_CODE_64bit {
10321:     my ($symb,$courseid,$domain,$username)=@_;
10322:     {
10323: 	use integer;
10324: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10325: 	my $symbseed=numval2($symb);
10326: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10327: 	my $CODEseed=numval(&getCODE());
10328: 	my $courseseed=unpack("%32S*",$courseid.' ');
10329: 	my $num1=$symbseed+$CODEchck;
10330: 	my $num2=$CODEseed+$courseseed+$symbchck;
10331: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10332: 	#&logthis("rndseed :$num1:$num2:$symb");
10333: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10334: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10335: 	return "$num1:$num2";
10336:     }
10337: }
10338: 
10339: sub rndseed_CODE_64bit4 {
10340:     my ($symb,$courseid,$domain,$username)=@_;
10341:     {
10342: 	use integer;
10343: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10344: 	my $symbseed=numval3($symb);
10345: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10346: 	my $CODEseed=numval3(&getCODE());
10347: 	my $courseseed=unpack("%32S*",$courseid.' ');
10348: 	my $num1=$symbseed+$CODEchck;
10349: 	my $num2=$CODEseed+$courseseed+$symbchck;
10350: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10351: 	#&logthis("rndseed :$num1:$num2:$symb");
10352: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10353: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10354: 	return "$num1:$num2";
10355:     }
10356: }
10357: 
10358: sub rndseed_CODE_64bit5 {
10359:     my ($symb,$courseid,$domain,$username)=@_;
10360:     my $code = &getCODE();
10361:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10362:     return "$num1:$num2";
10363: }
10364: 
10365: sub setup_random_from_rndseed {
10366:     my ($rndseed)=@_;
10367:     if ($rndseed =~/([,:])/) {
10368: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10369: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10370:     } else {
10371: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10372:     }
10373: }
10374: 
10375: sub latest_receipt_algorithm_id {
10376:     return 'receipt3';
10377: }
10378: 
10379: sub recunique {
10380:     my $fucourseid=shift;
10381:     my $unique;
10382:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10383: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10384: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10385:     } else {
10386: 	$unique=$perlvar{'lonReceipt'};
10387:     }
10388:     return unpack("%32C*",$unique);
10389: }
10390: 
10391: sub recprefix {
10392:     my $fucourseid=shift;
10393:     my $prefix;
10394:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10395: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10396: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10397:     } else {
10398: 	$prefix=$perlvar{'lonHostID'};
10399:     }
10400:     return unpack("%32C*",$prefix);
10401: }
10402: 
10403: sub ireceipt {
10404:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10405: 
10406:     my $return =&recprefix($fucourseid).'-';
10407: 
10408:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10409: 	$env{'request.state'} eq 'construct') {
10410: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10411: 	return $return;
10412:     }
10413: 
10414:     my $cuname=unpack("%32C*",$funame);
10415:     my $cudom=unpack("%32C*",$fudom);
10416:     my $cucourseid=unpack("%32C*",$fucourseid);
10417:     my $cusymb=unpack("%32C*",$fusymb);
10418:     my $cunique=&recunique($fucourseid);
10419:     my $cpart=unpack("%32S*",$part);
10420:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10421: 
10422: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10423: 			       
10424: 	$return.= ($cunique%$cuname+
10425: 		   $cunique%$cudom+
10426: 		   $cusymb%$cuname+
10427: 		   $cusymb%$cudom+
10428: 		   $cucourseid%$cuname+
10429: 		   $cucourseid%$cudom+
10430: 		   $cpart%$cuname+
10431: 		   $cpart%$cudom);
10432:     } else {
10433: 	$return.= ($cunique%$cuname+
10434: 		   $cunique%$cudom+
10435: 		   $cusymb%$cuname+
10436: 		   $cusymb%$cudom+
10437: 		   $cucourseid%$cuname+
10438: 		   $cucourseid%$cudom);
10439:     }
10440:     return $return;
10441: }
10442: 
10443: sub receipt {
10444:     my ($part)=@_;
10445:     my ($symb,$courseid,$domain,$name) = &whichuser();
10446:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10447: }
10448: 
10449: sub whichuser {
10450:     my ($passedsymb)=@_;
10451:     my ($symb,$courseid,$domain,$name,$publicuser);
10452:     if (defined($env{'form.grade_symb'})) {
10453: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10454: 	my $allowed=&allowed('vgr',$tmp_courseid);
10455: 	if (!$allowed &&
10456: 	    exists($env{'request.course.sec'}) &&
10457: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10458: 	    $allowed=&allowed('vgr',$tmp_courseid.
10459: 			      '/'.$env{'request.course.sec'});
10460: 	}
10461: 	if ($allowed) {
10462: 	    ($symb)=&get_env_multiple('form.grade_symb');
10463: 	    $courseid=$tmp_courseid;
10464: 	    ($domain)=&get_env_multiple('form.grade_domain');
10465: 	    ($name)=&get_env_multiple('form.grade_username');
10466: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10467: 	}
10468:     }
10469:     if (!$passedsymb) {
10470: 	$symb=&symbread();
10471:     } else {
10472: 	$symb=$passedsymb;
10473:     }
10474:     $courseid=$env{'request.course.id'};
10475:     $domain=$env{'user.domain'};
10476:     $name=$env{'user.name'};
10477:     if ($name eq 'public' && $domain eq 'public') {
10478: 	if (!defined($env{'form.username'})) {
10479: 	    $env{'form.username'}.=time.rand(10000000);
10480: 	}
10481: 	$name.=$env{'form.username'};
10482:     }
10483:     return ($symb,$courseid,$domain,$name,$publicuser);
10484: 
10485: }
10486: 
10487: # ------------------------------------------------------------ Serves up a file
10488: # returns either the contents of the file or 
10489: # -1 if the file doesn't exist
10490: #
10491: # if the target is a file that was uploaded via DOCS, 
10492: # a check will be made to see if a current copy exists on the local server,
10493: # if it does this will be served, otherwise a copy will be retrieved from
10494: # the home server for the course and stored in /home/httpd/html/userfiles on
10495: # the local server.   
10496: 
10497: sub getfile {
10498:     my ($file) = @_;
10499:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10500:     &repcopy($file);
10501:     return &readfile($file);
10502: }
10503: 
10504: sub repcopy_userfile {
10505:     my ($file)=@_;
10506:     my $londocroot = $perlvar{'lonDocRoot'};
10507:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10508:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10509:     my ($cdom,$cnum,$filename) = 
10510: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10511:     my $uri="/uploaded/$cdom/$cnum/$filename";
10512:     if (-e "$file") {
10513: # we already have a local copy, check it out
10514: 	my @fileinfo = stat($file);
10515: 	my $rtncode;
10516: 	my $info;
10517: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10518: 	if ($lwpresp ne 'ok') {
10519: # there is no such file anymore, even though we had a local copy
10520: 	    if ($rtncode eq '404') {
10521: 		unlink($file);
10522: 	    }
10523: 	    return -1;
10524: 	}
10525: 	if ($info < $fileinfo[9]) {
10526: # nice, the file we have is up-to-date, just say okay
10527: 	    return 'ok';
10528: 	} else {
10529: # the file is outdated, get rid of it
10530: 	    unlink($file);
10531: 	}
10532:     }
10533: # one way or the other, at this point, we don't have the file
10534: # construct the correct path for the file
10535:     my @parts = ($cdom,$cnum); 
10536:     if ($filename =~ m|^(.+)/[^/]+$|) {
10537: 	push @parts, split(/\//,$1);
10538:     }
10539:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10540:     foreach my $part (@parts) {
10541: 	$path .= '/'.$part;
10542: 	if (!-e $path) {
10543: 	    mkdir($path,0770);
10544: 	}
10545:     }
10546: # now the path exists for sure
10547: # get a user agent
10548:     my $ua=new LWP::UserAgent;
10549:     my $transferfile=$file.'.in.transfer';
10550: # FIXME: this should flock
10551:     if (-e $transferfile) { return 'ok'; }
10552:     my $request;
10553:     $uri=~s/^\///;
10554:     my $homeserver = &homeserver($cnum,$cdom);
10555:     my $protocol = $protocol{$homeserver};
10556:     $protocol = 'http' if ($protocol ne 'https');
10557:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10558:     my $response=$ua->request($request,$transferfile);
10559: # did it work?
10560:     if ($response->is_error()) {
10561: 	unlink($transferfile);
10562: 	&logthis("Userfile repcopy failed for $uri");
10563: 	return -1;
10564:     }
10565: # worked, rename the transfer file
10566:     rename($transferfile,$file);
10567:     return 'ok';
10568: }
10569: 
10570: sub tokenwrapper {
10571:     my $uri=shift;
10572:     $uri=~s|^https?\://([^/]+)||;
10573:     $uri=~s|^/||;
10574:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10575:     my $token=$1;
10576:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10577:     if ($udom && $uname && $file) {
10578: 	$file=~s|(\?\.*)*$||;
10579:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10580:         my $homeserver = &homeserver($uname,$udom);
10581:         my $protocol = $protocol{$homeserver};
10582:         $protocol = 'http' if ($protocol ne 'https');
10583:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10584:                (($uri=~/\?/)?'&':'?').'token='.$token.
10585:                                '&tokenissued='.$perlvar{'lonHostID'};
10586:     } else {
10587:         return '/adm/notfound.html';
10588:     }
10589: }
10590: 
10591: # call with reqtype HEAD: get last modification time
10592: # call with reqtype GET: get the file contents
10593: # Do not call this with reqtype GET for large files! It loads everything into memory
10594: #
10595: sub getuploaded {
10596:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10597:     $uri=~s/^\///;
10598:     my $homeserver = &homeserver($cnum,$cdom);
10599:     my $protocol = $protocol{$homeserver};
10600:     $protocol = 'http' if ($protocol ne 'https');
10601:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10602:     my $ua=new LWP::UserAgent;
10603:     my $request=new HTTP::Request($reqtype,$uri);
10604:     my $response=$ua->request($request);
10605:     $$rtncode = $response->code;
10606:     if (! $response->is_success()) {
10607: 	return 'failed';
10608:     }      
10609:     if ($reqtype eq 'HEAD') {
10610: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10611:     } elsif ($reqtype eq 'GET') {
10612: 	$$info = $response->content;
10613:     }
10614:     return 'ok';
10615: }
10616: 
10617: sub readfile {
10618:     my $file = shift;
10619:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10620:     my $fh;
10621:     open($fh,"<$file");
10622:     my $a='';
10623:     while (my $line = <$fh>) { $a .= $line; }
10624:     return $a;
10625: }
10626: 
10627: sub filelocation {
10628:     my ($dir,$file) = @_;
10629:     my $location;
10630:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10631: 
10632:     if ($file =~ m-^/adm/-) {
10633: 	$file=~s-^/adm/wrapper/-/-;
10634: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10635:     }
10636: 
10637:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10638:         $location = $file;
10639:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10640:         my ($udom,$uname,$filename)=
10641:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10642:         my $home=&homeserver($uname,$udom);
10643:         my $is_me=0;
10644:         my @ids=&current_machine_ids();
10645:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10646:         if ($is_me) {
10647:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10648:         } else {
10649:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10650:   	      $udom.'/'.$uname.'/'.$filename;
10651:         }
10652:     } elsif ($file =~ m-^/adm/-) {
10653: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10654:     } else {
10655:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10656:         $file=~s:^/(res|priv)/:/:;
10657:         my $space=$1;
10658:         if ( !( $file =~ m:^/:) ) {
10659:             $location = $dir. '/'.$file;
10660:         } else {
10661:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10662:         }
10663:     }
10664:     $location=~s://+:/:g; # remove duplicate /
10665:     while ($location=~m{/\.\./}) {
10666: 	if ($location =~ m{/[^/]+/\.\./}) {
10667: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10668: 	} else {
10669: 	    $location=~ s{/\.\./}{/}g;
10670: 	}
10671:     } #remove dir/..
10672:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10673:     return $location;
10674: }
10675: 
10676: sub hreflocation {
10677:     my ($dir,$file)=@_;
10678:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10679: 	$file=filelocation($dir,$file);
10680:     } elsif ($file=~m-^/adm/-) {
10681: 	$file=~s-^/adm/wrapper/-/-;
10682: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10683:     }
10684:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10685: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10686:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10687: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10688: 	        {/uploaded/$1/$2/}x;
10689:     }
10690:     if ($file=~ m{^/userfiles/}) {
10691: 	$file =~ s{^/userfiles/}{/uploaded/};
10692:     }
10693:     return $file;
10694: }
10695: 
10696: 
10697: 
10698: 
10699: 
10700: sub current_machine_domains {
10701:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10702: }
10703: 
10704: sub machine_domains {
10705:     my ($hostname) = @_;
10706:     my @domains;
10707:     my %hostname = &all_hostnames();
10708:     while( my($id, $name) = each(%hostname)) {
10709: #	&logthis("-$id-$name-$hostname-");
10710: 	if ($hostname eq $name) {
10711: 	    push(@domains,&host_domain($id));
10712: 	}
10713:     }
10714:     return @domains;
10715: }
10716: 
10717: sub current_machine_ids {
10718:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10719: }
10720: 
10721: sub machine_ids {
10722:     my ($hostname) = @_;
10723:     $hostname ||= &hostname($perlvar{'lonHostID'});
10724:     my @ids;
10725:     my %name_to_host = &all_names();
10726:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10727: 	return @{ $name_to_host{$hostname} };
10728:     }
10729:     return;
10730: }
10731: 
10732: sub additional_machine_domains {
10733:     my @domains;
10734:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10735:     while( my $line = <$fh>) {
10736:         $line =~ s/\s//g;
10737:         push(@domains,$line);
10738:     }
10739:     return @domains;
10740: }
10741: 
10742: sub default_login_domain {
10743:     my $domain = $perlvar{'lonDefDomain'};
10744:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10745:     foreach my $posdom (&current_machine_domains(),
10746:                         &additional_machine_domains()) {
10747:         if (lc($posdom) eq lc($testdomain)) {
10748:             $domain=$posdom;
10749:             last;
10750:         }
10751:     }
10752:     return $domain;
10753: }
10754: 
10755: # ------------------------------------------------------------- Declutters URLs
10756: 
10757: sub declutter {
10758:     my $thisfn=shift;
10759:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10760:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10761:     $thisfn=~s/^\///;
10762:     $thisfn=~s|^adm/wrapper/||;
10763:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10764:     $thisfn=~s/^res\///;
10765:     $thisfn=~s/^priv\///;
10766:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10767:         $thisfn=~s/\?.+$//;
10768:     }
10769:     return $thisfn;
10770: }
10771: 
10772: # ------------------------------------------------------------- Clutter up URLs
10773: 
10774: sub clutter {
10775:     my $thisfn='/'.&declutter(shift);
10776:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10777: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10778:        $thisfn='/res'.$thisfn; 
10779:     }
10780:     if ($thisfn !~m|^/adm|) {
10781: 	if ($thisfn =~ m|^/ext/|) {
10782: 	    $thisfn='/adm/wrapper'.$thisfn;
10783: 	} else {
10784: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10785: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10786: 	    if ($embstyle eq 'ssi'
10787: 		|| ($embstyle eq 'hdn')
10788: 		|| ($embstyle eq 'rat')
10789: 		|| ($embstyle eq 'prv')
10790: 		|| ($embstyle eq 'ign')) {
10791: 		#do nothing with these
10792: 	    } elsif (($embstyle eq 'img') 
10793: 		|| ($embstyle eq 'emb')
10794: 		|| ($embstyle eq 'wrp')) {
10795: 		$thisfn='/adm/wrapper'.$thisfn;
10796: 	    } elsif ($embstyle eq 'unk'
10797: 		     && $thisfn!~/\.(sequence|page)$/) {
10798: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10799: 	    } else {
10800: #		&logthis("Got a blank emb style");
10801: 	    }
10802: 	}
10803:     }
10804:     return $thisfn;
10805: }
10806: 
10807: sub clutter_with_no_wrapper {
10808:     my $uri = &clutter(shift);
10809:     if ($uri =~ m-^/adm/-) {
10810: 	$uri =~ s-^/adm/wrapper/-/-;
10811: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10812:     }
10813:     return $uri;
10814: }
10815: 
10816: sub freeze_escape {
10817:     my ($value)=@_;
10818:     if (ref($value)) {
10819: 	$value=&nfreeze($value);
10820: 	return '__FROZEN__'.&escape($value);
10821:     }
10822:     return &escape($value);
10823: }
10824: 
10825: 
10826: sub thaw_unescape {
10827:     my ($value)=@_;
10828:     if ($value =~ /^__FROZEN__/) {
10829: 	substr($value,0,10,undef);
10830: 	$value=&unescape($value);
10831: 	return &thaw($value);
10832:     }
10833:     return &unescape($value);
10834: }
10835: 
10836: sub correct_line_ends {
10837:     my ($result)=@_;
10838:     $$result =~s/\r\n/\n/mg;
10839:     $$result =~s/\r/\n/mg;
10840: }
10841: # ================================================================ Main Program
10842: 
10843: sub goodbye {
10844:    &logthis("Starting Shut down");
10845: #not converted to using infrastruture and probably shouldn't be
10846:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10847: #converted
10848: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10849:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10850: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10851: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10852: #1.1 only
10853: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10854: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10855: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10856: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10857:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10858:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10859:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10860:    &flushcourselogs();
10861:    &logthis("Shutting down");
10862: }
10863: 
10864: sub get_dns {
10865:     my ($url,$func,$ignore_cache) = @_;
10866:     if (!$ignore_cache) {
10867: 	my ($content,$cached)=
10868: 	    &Apache::lonnet::is_cached_new('dns',$url);
10869: 	if ($cached) {
10870: 	    &$func($content);
10871: 	    return;
10872: 	}
10873:     }
10874: 
10875:     my %alldns;
10876:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10877:     foreach my $dns (<$config>) {
10878: 	next if ($dns !~ /^\^(\S*)/x);
10879:         my $line = $1;
10880:         my ($host,$protocol) = split(/:/,$line);
10881:         if ($protocol ne 'https') {
10882:             $protocol = 'http';
10883:         }
10884: 	$alldns{$host} = $protocol;
10885:     }
10886:     while (%alldns) {
10887: 	my ($dns) = keys(%alldns);
10888: 	my $ua=new LWP::UserAgent;
10889:         $ua->timeout(30);
10890: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10891: 	my $response=$ua->request($request);
10892:         delete($alldns{$dns});
10893: 	next if ($response->is_error());
10894: 	my @content = split("\n",$response->content);
10895: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10896: 	&$func(\@content);
10897: 	return;
10898:     }
10899:     close($config);
10900:     my $which = (split('/',$url))[3];
10901:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10902:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10903:     my @content = <$config>;
10904:     &$func(\@content);
10905:     return;
10906: }
10907: # ------------------------------------------------------------ Read domain file
10908: {
10909:     my $loaded;
10910:     my %domain;
10911: 
10912:     sub parse_domain_tab {
10913: 	my ($lines) = @_;
10914: 	foreach my $line (@$lines) {
10915: 	    next if ($line =~ /^(\#|\s*$ )/x);
10916: 
10917: 	    chomp($line);
10918: 	    my ($name,@elements) = split(/:/,$line,9);
10919: 	    my %this_domain;
10920: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10921: 			       'lang_def', 'city', 'longi', 'lati',
10922: 			       'primary') {
10923: 		$this_domain{$field} = shift(@elements);
10924: 	    }
10925: 	    $domain{$name} = \%this_domain;
10926: 	}
10927:     }
10928: 
10929:     sub reset_domain_info {
10930: 	undef($loaded);
10931: 	undef(%domain);
10932:     }
10933: 
10934:     sub load_domain_tab {
10935: 	my ($ignore_cache) = @_;
10936: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10937: 	my $fh;
10938: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10939: 	    my @lines = <$fh>;
10940: 	    &parse_domain_tab(\@lines);
10941: 	}
10942: 	close($fh);
10943: 	$loaded = 1;
10944:     }
10945: 
10946:     sub domain {
10947: 	&load_domain_tab() if (!$loaded);
10948: 
10949: 	my ($name,$what) = @_;
10950: 	return if ( !exists($domain{$name}) );
10951: 
10952: 	if (!$what) {
10953: 	    return $domain{$name}{'description'};
10954: 	}
10955: 	return $domain{$name}{$what};
10956:     }
10957: 
10958:     sub domain_info {
10959:         &load_domain_tab() if (!$loaded);
10960:         return %domain;
10961:     }
10962: 
10963: }
10964: 
10965: 
10966: # ------------------------------------------------------------- Read hosts file
10967: {
10968:     my %hostname;
10969:     my %hostdom;
10970:     my %libserv;
10971:     my $loaded;
10972:     my %name_to_host;
10973:     my %internetdom;
10974:     my %LC_dns_serv;
10975: 
10976:     sub parse_hosts_tab {
10977: 	my ($file) = @_;
10978: 	foreach my $configline (@$file) {
10979: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10980:             chomp($configline);
10981: 	    if ($configline =~ /^\^/) {
10982:                 if ($configline =~ /^\^([\w.\-]+)/) {
10983:                     $LC_dns_serv{$1} = 1;
10984:                 }
10985:                 next;
10986:             }
10987: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10988: 	    $name=~s/\s//g;
10989: 	    if ($id && $domain && $role && $name) {
10990: 		$hostname{$id}=$name;
10991: 		push(@{$name_to_host{$name}}, $id);
10992: 		$hostdom{$id}=$domain;
10993: 		if ($role eq 'library') { $libserv{$id}=$name; }
10994:                 if (defined($protocol)) {
10995:                     if ($protocol eq 'https') {
10996:                         $protocol{$id} = $protocol;
10997:                     } else {
10998:                         $protocol{$id} = 'http'; 
10999:                     }
11000:                 } else {
11001:                     $protocol{$id} = 'http';
11002:                 }
11003:                 if (defined($intdom)) {
11004:                     $internetdom{$id} = $intdom;
11005:                 }
11006: 	    }
11007: 	}
11008:     }
11009:     
11010:     sub reset_hosts_info {
11011: 	&purge_remembered();
11012: 	&reset_domain_info();
11013: 	&reset_hosts_ip_info();
11014: 	undef(%name_to_host);
11015: 	undef(%hostname);
11016: 	undef(%hostdom);
11017: 	undef(%libserv);
11018: 	undef($loaded);
11019:     }
11020: 
11021:     sub load_hosts_tab {
11022: 	my ($ignore_cache) = @_;
11023: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11024: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11025: 	my @config = <$config>;
11026: 	&parse_hosts_tab(\@config);
11027: 	close($config);
11028: 	$loaded=1;
11029:     }
11030: 
11031:     sub hostname {
11032: 	&load_hosts_tab() if (!$loaded);
11033: 
11034: 	my ($lonid) = @_;
11035: 	return $hostname{$lonid};
11036:     }
11037: 
11038:     sub all_hostnames {
11039: 	&load_hosts_tab() if (!$loaded);
11040: 
11041: 	return %hostname;
11042:     }
11043: 
11044:     sub all_names {
11045: 	&load_hosts_tab() if (!$loaded);
11046: 
11047: 	return %name_to_host;
11048:     }
11049: 
11050:     sub all_host_domain {
11051:         &load_hosts_tab() if (!$loaded);
11052:         return %hostdom;
11053:     }
11054: 
11055:     sub is_library {
11056: 	&load_hosts_tab() if (!$loaded);
11057: 
11058: 	return exists($libserv{$_[0]});
11059:     }
11060: 
11061:     sub all_library {
11062: 	&load_hosts_tab() if (!$loaded);
11063: 
11064: 	return %libserv;
11065:     }
11066: 
11067:     sub unique_library {
11068: 	#2x reverse removes all hostnames that appear more than once
11069:         my %unique = reverse &all_library();
11070:         return reverse %unique;
11071:     }
11072: 
11073:     sub get_servers {
11074: 	&load_hosts_tab() if (!$loaded);
11075: 
11076: 	my ($domain,$type) = @_;
11077: 	my %possible_hosts = ($type eq 'library') ? %libserv
11078: 	                                          : %hostname;
11079: 	my %result;
11080: 	if (ref($domain) eq 'ARRAY') {
11081: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11082: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11083: 		    $result{$host} = $hostname;
11084: 		}
11085: 	    }
11086: 	} else {
11087: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11088: 		if ($hostdom{$host} eq $domain) {
11089: 		    $result{$host} = $hostname;
11090: 		}
11091: 	    }
11092: 	}
11093: 	return %result;
11094:     }
11095: 
11096:     sub get_unique_servers {
11097:         my %unique = reverse &get_servers(@_);
11098: 	return reverse %unique;
11099:     }
11100: 
11101:     sub host_domain {
11102: 	&load_hosts_tab() if (!$loaded);
11103: 
11104: 	my ($lonid) = @_;
11105: 	return $hostdom{$lonid};
11106:     }
11107: 
11108:     sub all_domains {
11109: 	&load_hosts_tab() if (!$loaded);
11110: 
11111: 	my %seen;
11112: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11113: 	return @uniq;
11114:     }
11115: 
11116:     sub internet_dom {
11117:         &load_hosts_tab() if (!$loaded);
11118: 
11119:         my ($lonid) = @_;
11120:         return $internetdom{$lonid};
11121:     }
11122: 
11123:     sub is_LC_dns {
11124:         &load_hosts_tab() if (!$loaded);
11125: 
11126:         my ($hostname) = @_;
11127:         return exists($LC_dns_serv{$hostname});
11128:     }
11129: 
11130: }
11131: 
11132: { 
11133:     my %iphost;
11134:     my %name_to_ip;
11135:     my %lonid_to_ip;
11136: 
11137:     sub get_hosts_from_ip {
11138: 	my ($ip) = @_;
11139: 	my %iphosts = &get_iphost();
11140: 	if (ref($iphosts{$ip})) {
11141: 	    return @{$iphosts{$ip}};
11142: 	}
11143: 	return;
11144:     }
11145:     
11146:     sub reset_hosts_ip_info {
11147: 	undef(%iphost);
11148: 	undef(%name_to_ip);
11149: 	undef(%lonid_to_ip);
11150:     }
11151: 
11152:     sub get_host_ip {
11153: 	my ($lonid) = @_;
11154: 	if (exists($lonid_to_ip{$lonid})) {
11155: 	    return $lonid_to_ip{$lonid};
11156: 	}
11157: 	my $name=&hostname($lonid);
11158:    	my $ip = gethostbyname($name);
11159: 	return if (!$ip || length($ip) ne 4);
11160: 	$ip=inet_ntoa($ip);
11161: 	$name_to_ip{$name}   = $ip;
11162: 	$lonid_to_ip{$lonid} = $ip;
11163: 	return $ip;
11164:     }
11165:     
11166:     sub get_iphost {
11167: 	my ($ignore_cache) = @_;
11168: 
11169: 	if (!$ignore_cache) {
11170: 	    if (%iphost) {
11171: 		return %iphost;
11172: 	    }
11173: 	    my ($ip_info,$cached)=
11174: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11175: 	    if ($cached) {
11176: 		%iphost      = %{$ip_info->[0]};
11177: 		%name_to_ip  = %{$ip_info->[1]};
11178: 		%lonid_to_ip = %{$ip_info->[2]};
11179: 		return %iphost;
11180: 	    }
11181: 	}
11182: 
11183: 	# get yesterday's info for fallback
11184: 	my %old_name_to_ip;
11185: 	my ($ip_info,$cached)=
11186: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11187: 	if ($cached) {
11188: 	    %old_name_to_ip = %{$ip_info->[1]};
11189: 	}
11190: 
11191: 	my %name_to_host = &all_names();
11192: 	foreach my $name (keys(%name_to_host)) {
11193: 	    my $ip;
11194: 	    if (!exists($name_to_ip{$name})) {
11195: 		$ip = gethostbyname($name);
11196: 		if (!$ip || length($ip) ne 4) {
11197: 		    if (defined($old_name_to_ip{$name})) {
11198: 			$ip = $old_name_to_ip{$name};
11199: 			&logthis("Can't find $name defaulting to old $ip");
11200: 		    } else {
11201: 			&logthis("Name $name no IP found");
11202: 			next;
11203: 		    }
11204: 		} else {
11205: 		    $ip=inet_ntoa($ip);
11206: 		}
11207: 		$name_to_ip{$name} = $ip;
11208: 	    } else {
11209: 		$ip = $name_to_ip{$name};
11210: 	    }
11211: 	    foreach my $id (@{ $name_to_host{$name} }) {
11212: 		$lonid_to_ip{$id} = $ip;
11213: 	    }
11214: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11215: 	}
11216: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11217: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11218: 				      48*60*60);
11219: 
11220: 	return %iphost;
11221:     }
11222: 
11223:     #
11224:     #  Given a DNS returns the loncapa host name for that DNS 
11225:     # 
11226:     sub host_from_dns {
11227:         my ($dns) = @_;
11228:         my @hosts;
11229:         my $ip;
11230: 
11231:         if (exists($name_to_ip{$dns})) {
11232:             $ip = $name_to_ip{$dns};
11233:         }
11234:         if (!$ip) {
11235:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11236:             if (length($ip) == 4) { 
11237: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11238:             }
11239:         }
11240:         if ($ip) {
11241: 	    @hosts = get_hosts_from_ip($ip);
11242: 	    return $hosts[0];
11243:         }
11244:         return undef;
11245:     }
11246: 
11247:     sub get_internet_names {
11248:         my ($lonid) = @_;
11249:         return if ($lonid eq '');
11250:         my ($idnref,$cached)=
11251:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11252:         if ($cached) {
11253:             return $idnref;
11254:         }
11255:         my $ip = &get_host_ip($lonid);
11256:         my @hosts = &get_hosts_from_ip($ip);
11257:         my %iphost = &get_iphost();
11258:         my (@idns,%seen);
11259:         foreach my $id (@hosts) {
11260:             my $dom = &host_domain($id);
11261:             my $prim_id = &domain($dom,'primary');
11262:             my $prim_ip = &get_host_ip($prim_id);
11263:             next if ($seen{$prim_ip});
11264:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11265:                 foreach my $id (@{$iphost{$prim_ip}}) {
11266:                     my $intdom = &internet_dom($id);
11267:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11268:                         push(@idns,$intdom);
11269:                     }
11270:                 }
11271:             }
11272:             $seen{$prim_ip} = 1;
11273:         }
11274:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11275:     }
11276: 
11277: }
11278: 
11279: sub all_loncaparevs {
11280:     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);
11281: }
11282: 
11283: BEGIN {
11284: 
11285: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11286:     unless ($readit) {
11287: {
11288:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11289:     %perlvar = (%perlvar,%{$configvars});
11290: }
11291: 
11292: 
11293: # ------------------------------------------------------ Read spare server file
11294: {
11295:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11296: 
11297:     while (my $configline=<$config>) {
11298:        chomp($configline);
11299:        if ($configline) {
11300: 	   my ($host,$type) = split(':',$configline,2);
11301: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11302: 	   push(@{ $spareid{$type} }, $host);
11303:        }
11304:     }
11305:     close($config);
11306: }
11307: # ------------------------------------------------------------ Read permissions
11308: {
11309:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11310: 
11311:     while (my $configline=<$config>) {
11312: 	chomp($configline);
11313: 	if ($configline) {
11314: 	    my ($role,$perm)=split(/ /,$configline);
11315: 	    if ($perm ne '') { $pr{$role}=$perm; }
11316: 	}
11317:     }
11318:     close($config);
11319: }
11320: 
11321: # -------------------------------------------- Read plain texts for permissions
11322: {
11323:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11324: 
11325:     while (my $configline=<$config>) {
11326: 	chomp($configline);
11327: 	if ($configline) {
11328: 	    my ($short,@plain)=split(/:/,$configline);
11329:             %{$prp{$short}} = ();
11330: 	    if (@plain > 0) {
11331:                 $prp{$short}{'std'} = $plain[0];
11332:                 for (my $i=1; $i<@plain; $i++) {
11333:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11334:                 }
11335:             }
11336: 	}
11337:     }
11338:     close($config);
11339: }
11340: 
11341: # ---------------------------------------------------------- Read package table
11342: {
11343:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11344: 
11345:     while (my $configline=<$config>) {
11346: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11347: 	chomp($configline);
11348: 	my ($short,$plain)=split(/:/,$configline);
11349: 	my ($pack,$name)=split(/\&/,$short);
11350: 	if ($plain ne '') {
11351: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11352: 	    $packagetab{$short}=$plain; 
11353: 	}
11354:     }
11355:     close($config);
11356: }
11357: 
11358: # ---------------------------------------------------------- Read loncaparev table
11359: {
11360:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11361:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11362:             while (my $configline=<$config>) {
11363:                 chomp($configline);
11364:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11365:                 $loncaparevs{$hostid}=$loncaparev;
11366:             }
11367:             close($config);
11368:         }
11369:     }
11370: }
11371: 
11372: # ---------------------------------------------------------- Read serverhostID table
11373: {
11374:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11375:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11376:             while (my $configline=<$config>) {
11377:                 chomp($configline);
11378:                 my ($name,$id)=split(/:/,$configline);
11379:                 $serverhomeIDs{$name}=$id;
11380:             }
11381:             close($config);
11382:         }
11383:     }
11384: }
11385: 
11386: {
11387:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11388:     if (-e $file) {
11389:         my $parser = HTML::LCParser->new($file);
11390:         while (my $token = $parser->get_token()) {
11391:             if ($token->[0] eq 'S') {
11392:                 my $item = $token->[1];
11393:                 my $name = $token->[2]{'name'};
11394:                 my $value = $token->[2]{'value'};
11395:                 if ($item ne '' && $name ne '' && $value ne '') {
11396:                     my $release = $parser->get_text();
11397:                     $release =~ s/(^\s*|\s*$ )//gx;
11398:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11399:                 }
11400:             }
11401:         }
11402:     }
11403: }
11404: 
11405: # ---------------------------------------------------------- Read managers table
11406: {
11407:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11408:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11409:             while (my $configline=<$config>) {
11410:                 chomp($configline);
11411:                 next if ($configline =~ /^\#/);
11412:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11413:                     $managerstab{$configline} = 1;
11414:                 }
11415:             }
11416:             close($config);
11417:         }
11418:     }
11419: }
11420: 
11421: # ------------- set up temporary directory
11422: {
11423:     $tmpdir = LONCAPA::tempdir();
11424: 
11425: }
11426: 
11427: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11428: 				'compress_threshold'=> 20_000,
11429:  			        });
11430: 
11431: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11432: $dumpcount=0;
11433: $locknum=0;
11434: 
11435: &logtouch();
11436: &logthis('<font color="yellow">INFO: Read configuration</font>');
11437: $readit=1;
11438:     {
11439: 	use integer;
11440: 	my $test=(2**32)+1;
11441: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11442: 	&logthis(" Detected 64bit platform ($_64bit)");
11443:     }
11444: }
11445: }
11446: 
11447: 1;
11448: __END__
11449: 
11450: =pod
11451: 
11452: =head1 NAME
11453: 
11454: Apache::lonnet - Subroutines to ask questions about things in the network.
11455: 
11456: =head1 SYNOPSIS
11457: 
11458: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11459: 
11460:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11461: 
11462: Common parameters:
11463: 
11464: =over 4
11465: 
11466: =item *
11467: 
11468: $uname : an internal username (if $cname expecting a course Id specifically)
11469: 
11470: =item *
11471: 
11472: $udom : a domain (if $cdom expecting a course's domain specifically)
11473: 
11474: =item *
11475: 
11476: $symb : a resource instance identifier
11477: 
11478: =item *
11479: 
11480: $namespace : the name of a .db file that contains the data needed or
11481: being set.
11482: 
11483: =back
11484: 
11485: =head1 OVERVIEW
11486: 
11487: lonnet provides subroutines which interact with the
11488: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11489: about classes, users, and resources.
11490: 
11491: For many of these objects you can also use this to store data about
11492: them or modify them in various ways.
11493: 
11494: =head2 Symbs
11495: 
11496: To identify a specific instance of a resource, LON-CAPA uses symbols
11497: or "symbs"X<symb>. These identifiers are built from the URL of the
11498: map, the resource number of the resource in the map, and the URL of
11499: the resource itself. The latter is somewhat redundant, but might help
11500: if maps change.
11501: 
11502: An example is
11503: 
11504:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11505: 
11506: The respective map entry is
11507: 
11508:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11509:   title="Problem 2">
11510:  </resource>
11511: 
11512: Symbs are used by the random number generator, as well as to store and
11513: restore data specific to a certain instance of for example a problem.
11514: 
11515: =head2 Storing And Retrieving Data
11516: 
11517: X<store()>X<cstore()>X<restore()>Three of the most important functions
11518: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11519: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11520: is is the non-critical message twin of cstore. These functions are for
11521: handlers to store a perl hash to a user's permanent data space in an
11522: easy manner, and to retrieve it again on another call. It is expected
11523: that a handler would use this once at the beginning to retrieve data,
11524: and then again once at the end to send only the new data back.
11525: 
11526: The data is stored in the user's data directory on the user's
11527: homeserver under the ID of the course.
11528: 
11529: The hash that is returned by restore will have all of the previous
11530: value for all of the elements of the hash.
11531: 
11532: Example:
11533: 
11534:  #creating a hash
11535:  my %hash;
11536:  $hash{'foo'}='bar';
11537: 
11538:  #storing it
11539:  &Apache::lonnet::cstore(\%hash);
11540: 
11541:  #changing a value
11542:  $hash{'foo'}='notbar';
11543: 
11544:  #adding a new value
11545:  $hash{'bar'}='foo';
11546:  &Apache::lonnet::cstore(\%hash);
11547: 
11548:  #retrieving the hash
11549:  my %history=&Apache::lonnet::restore();
11550: 
11551:  #print the hash
11552:  foreach my $key (sort(keys(%history))) {
11553:    print("\%history{$key} = $history{$key}");
11554:  }
11555: 
11556: Will print out:
11557: 
11558:  %history{1:foo} = bar
11559:  %history{1:keys} = foo:timestamp
11560:  %history{1:timestamp} = 990455579
11561:  %history{2:bar} = foo
11562:  %history{2:foo} = notbar
11563:  %history{2:keys} = foo:bar:timestamp
11564:  %history{2:timestamp} = 990455580
11565:  %history{bar} = foo
11566:  %history{foo} = notbar
11567:  %history{timestamp} = 990455580
11568:  %history{version} = 2
11569: 
11570: Note that the special hash entries C<keys>, C<version> and
11571: C<timestamp> were added to the hash. C<version> will be equal to the
11572: total number of versions of the data that have been stored. The
11573: C<timestamp> attribute will be the UNIX time the hash was
11574: stored. C<keys> is available in every historical section to list which
11575: keys were added or changed at a specific historical revision of a
11576: hash.
11577: 
11578: B<Warning>: do not store the hash that restore returns directly. This
11579: will cause a mess since it will restore the historical keys as if the
11580: were new keys. I.E. 1:foo will become 1:1:foo etc.
11581: 
11582: Calling convention:
11583: 
11584:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11585:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11586: 
11587: For more detailed information, see lonnet specific documentation.
11588: 
11589: =head1 RETURN MESSAGES
11590: 
11591: =over 4
11592: 
11593: =item * B<con_lost>: unable to contact remote host
11594: 
11595: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11596: when the connection is brought back up
11597: 
11598: =item * B<con_failed>: unable to contact remote host and unable to save message
11599: for later delivery
11600: 
11601: =item * B<error:>: an error a occurred, a description of the error follows the :
11602: 
11603: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11604: that was requested
11605: 
11606: =back
11607: 
11608: =head1 PUBLIC SUBROUTINES
11609: 
11610: =head2 Session Environment Functions
11611: 
11612: =over 4
11613: 
11614: =item * 
11615: X<appenv()>
11616: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11617: the user envirnoment file, and will be restored for each access this
11618: user makes during this session, also modifies the %env for the current
11619: process. Optional rolesarrayref - if defined contains a reference to an array
11620: of roles which are exempt from the restriction on modifying user.role entries 
11621: in the user's environment.db and in %env.    
11622: 
11623: =item *
11624: X<delenv()>
11625: B<delenv($delthis,$regexp)>: removes all items from the session
11626: environment file that begin with $delthis. If the 
11627: optional second arg - $regexp - is true, $delthis is treated as a 
11628: regular expression, otherwise \Q$delthis\E is used. 
11629: The values are also deleted from the current processes %env.
11630: 
11631: =item * get_env_multiple($name) 
11632: 
11633: gets $name from the %env hash, it seemlessly handles the cases where multiple
11634: values may be defined and end up as an array ref.
11635: 
11636: returns an array of values
11637: 
11638: =back
11639: 
11640: =head2 User Information
11641: 
11642: =over 4
11643: 
11644: =item *
11645: X<queryauthenticate()>
11646: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11647: authentication scheme
11648: 
11649: =item *
11650: X<authenticate()>
11651: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11652: authenticate user from domain's lib servers (first use the current
11653: one). C<$upass> should be the users password.
11654: $checkdefauth is optional (value is 1 if a check should be made to
11655:    authenticate user using default authentication method, and allow
11656:    account creation if username does not have account in the domain).
11657: $clientcancheckhost is optional (value is 1 if checking whether the
11658:    server can host will occur on the client side in lonauth.pm).   
11659: 
11660: =item *
11661: X<homeserver()>
11662: B<homeserver($uname,$udom)>: find the server which has
11663: the user's directory and files (there must be only one), this caches
11664: the answer, and also caches if there is a borken connection.
11665: 
11666: =item *
11667: X<idget()>
11668: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11669: (IDs are a unique resource in a domain, there must be only 1 ID per
11670: username, and only 1 username per ID in a specific domain) (returns
11671: hash: id=>name,id=>name)
11672: 
11673: =item *
11674: X<idrget()>
11675: B<idrget($udom,@unames)>: find the IDs behind a list of
11676: usernames (returns hash: name=>id,name=>id)
11677: 
11678: =item *
11679: X<idput()>
11680: B<idput($udom,%ids)>: store away a list of names and associated IDs
11681: 
11682: =item *
11683: X<rolesinit()>
11684: B<rolesinit($udom,$username)>: get user privileges.
11685: returns user role, first access and timer interval hashes
11686: 
11687: =item *
11688: X<privileged()>
11689: B<privileged($username,$domain)>: returns a true if user has a
11690: privileged and active role (i.e. su or dc), false otherwise.
11691: 
11692: =item *
11693: X<getsection()>
11694: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11695: course $cname, return section name/number or '' for "not in course"
11696: and '-1' for "no section"
11697: 
11698: =item *
11699: X<userenvironment()>
11700: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11701: passed in @what from the requested user's environment, returns a hash
11702: 
11703: =item * 
11704: X<userlog_query()>
11705: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11706: activity.log file. %filters defines filters applied when parsing the
11707: log file. These can be start or end timestamps, or the type of action
11708: - log to look for Login or Logout events, check for Checkin or
11709: Checkout, role for role selection. The response is in the form
11710: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11711: escaped strings of the action recorded in the activity.log file.
11712: 
11713: =back
11714: 
11715: =head2 User Roles
11716: 
11717: =over 4
11718: 
11719: =item *
11720: 
11721: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11722:  F: full access
11723:  U,I,K: authentication modes (cxx only)
11724:  '': forbidden
11725:  1: user needs to choose course
11726:  2: browse allowed
11727:  A: passphrase authentication needed
11728: 
11729: =item *
11730: 
11731: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11732: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11733: and course level
11734: 
11735: =item *
11736: 
11737: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11738: (rolesplain.tab); plain text explanation of a user role term.
11739: $type is Course (default) or Community.
11740: If $forcedefault evaluates to true, text returned will be default 
11741: text for $type. Otherwise, if this is a course, the text returned 
11742: will be a custom name for the role (if defined in the course's 
11743: environment).  If no custom name is defined the default is returned.
11744:    
11745: =item *
11746: 
11747: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11748: All arguments are optional. Returns a hash of a roles, either for
11749: co-author/assistant author roles for a user's Construction Space
11750: (default), or if $context is 'userroles', roles for the user himself,
11751: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11752: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11753: For each key, value is set to colon-separated start and end times for
11754: the role.  If no username and domain are specified, will default to
11755: current user/domain. Types, roles, and roledoms are references to arrays
11756: of role statuses (active, future or previous), roles 
11757: (e.g., cc,in, st etc.) and domains of the roles which can be used
11758: to restrict the list of roles reported. If no array ref is 
11759: provided for types, will default to return only active roles.
11760: 
11761: =back
11762: 
11763: =head2 User Modification
11764: 
11765: =over 4
11766: 
11767: =item *
11768: 
11769: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11770: user for the level given by URL.  Optional start and end dates (leave empty
11771: string or zero for "no date")
11772: 
11773: =item *
11774: 
11775: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11776: change a users, password, possible return values are: ok,
11777: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11778: refused
11779: 
11780: =item *
11781: 
11782: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11783: 
11784: =item *
11785: 
11786: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11787:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11788: 
11789: will update user information (firstname,middlename,lastname,generation,
11790: permanentemail), and if forceid is true, student/employee ID also.
11791: A user's institutional affiliation(s) can also be updated.
11792: User information fields will not be overwritten with empty entries 
11793: unless the field is included in the $candelete array reference.
11794: This array is included when a single user is modified via "Manage Users",
11795: or when Autoupdate.pl is run by cron in a domain.
11796: 
11797: =item *
11798: 
11799: modifystudent
11800: 
11801: modify a student's enrollment and identification information.
11802: The course id is resolved based on the current users environment.  
11803: This means the envoking user must be a course coordinator or otherwise
11804: associated with a course.
11805: 
11806: This call is essentially a wrapper for lonnet::modifyuser and
11807: lonnet::modify_student_enrollment
11808: 
11809: Inputs: 
11810: 
11811: =over 4
11812: 
11813: =item B<$udom> Student's loncapa domain
11814: 
11815: =item B<$uname> Student's loncapa login name
11816: 
11817: =item B<$uid> Student/Employee ID
11818: 
11819: =item B<$umode> Student's authentication mode
11820: 
11821: =item B<$upass> Student's password
11822: 
11823: =item B<$first> Student's first name
11824: 
11825: =item B<$middle> Student's middle name
11826: 
11827: =item B<$last> Student's last name
11828: 
11829: =item B<$gene> Student's generation
11830: 
11831: =item B<$usec> Student's section in course
11832: 
11833: =item B<$end> Unix time of the roles expiration
11834: 
11835: =item B<$start> Unix time of the roles start date
11836: 
11837: =item B<$forceid> If defined, allow $uid to be changed
11838: 
11839: =item B<$desiredhome> server to use as home server for student
11840: 
11841: =item B<$email> Student's permanent e-mail address
11842: 
11843: =item B<$type> Type of enrollment (auto or manual)
11844: 
11845: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11846: 
11847: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11848: 
11849: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11850: 
11851: =item B<$context> role change context (shown in User Management Logs display in a course)
11852: 
11853: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11854: 
11855: =back
11856: 
11857: =item *
11858: 
11859: modify_student_enrollment
11860: 
11861: Change a students enrollment status in a class.  The environment variable
11862: 'role.request.course' must be defined for this function to proceed.
11863: 
11864: Inputs:
11865: 
11866: =over 4
11867: 
11868: =item $udom, students domain
11869: 
11870: =item $uname, students name
11871: 
11872: =item $uid, students user id
11873: 
11874: =item $first, students first name
11875: 
11876: =item $middle
11877: 
11878: =item $last
11879: 
11880: =item $gene
11881: 
11882: =item $usec
11883: 
11884: =item $end
11885: 
11886: =item $start
11887: 
11888: =item $type
11889: 
11890: =item $locktype
11891: 
11892: =item $cid
11893: 
11894: =item $selfenroll
11895: 
11896: =item $context
11897: 
11898: =back
11899: 
11900: 
11901: =item *
11902: 
11903: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11904: custom role; give a custom role to a user for the level given by URL.  Specify
11905: name and domain of role author, and role name
11906: 
11907: =item *
11908: 
11909: revokerole($udom,$uname,$url,$role) : revoke a role for url
11910: 
11911: =item *
11912: 
11913: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11914: 
11915: =back
11916: 
11917: =head2 Course Infomation
11918: 
11919: =over 4
11920: 
11921: =item *
11922: 
11923: coursedescription($courseid,$options) : returns a hash of information about the
11924: specified course id, including all environment settings for the
11925: course, the description of the course will be in the hash under the
11926: key 'description'
11927: 
11928: $options is an optional parameter that if supplied is a hash reference that controls
11929: what how this function works.  It has the following key/values:
11930: 
11931: =over 4
11932: 
11933: =item freshen_cache
11934: 
11935: If defined, and the environment cache for the course is valid, it is 
11936: returned in the returned hash.
11937: 
11938: =item one_time
11939: 
11940: If defined, the last cache time is set to _now_
11941: 
11942: =item user
11943: 
11944: If defined, the supplied username is used instead of the current user.
11945: 
11946: 
11947: =back
11948: 
11949: =item *
11950: 
11951: resdata($name,$domain,$type,@which) : request for current parameter
11952: setting for a specific $type, where $type is either 'course' or 'user',
11953: @what should be a list of parameters to ask about. This routine caches
11954: answers for 5 minutes.
11955: 
11956: =item *
11957: 
11958: get_courseresdata($courseid, $domain) : dump the entire course resource
11959: data base, returning a hash that is keyed by the resource name and has
11960: values that are the resource value.  I believe that the timestamps and
11961: versions are also returned.
11962: 
11963: 
11964: =back
11965: 
11966: =head2 Course Modification
11967: 
11968: =over 4
11969: 
11970: =item *
11971: 
11972: writecoursepref($courseid,%prefs) : write preferences (environment
11973: database) for a course
11974: 
11975: =item *
11976: 
11977: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11978: 
11979: =item *
11980: 
11981: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11982: 
11983: =item *
11984: 
11985: is_course($courseid), is_course($cdom, $cnum)
11986: 
11987: Accepts either a combined $courseid (in the form of domain_courseid) or the
11988: two component version $cdom, $cnum. It checks if the specified course exists.
11989: 
11990: Returns:
11991:     undef if the course doesn't exist, otherwise
11992:     in scalar context the combined courseid.
11993:     in list context the two components of the course identifier, domain and 
11994:     courseid.    
11995: 
11996: =back
11997: 
11998: =head2 Resource Subroutines
11999: 
12000: =over 4
12001: 
12002: =item *
12003: 
12004: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12005: 
12006: =item *
12007: 
12008: repcopy($filename) : subscribes to the requested file, and attempts to
12009: replicate from the owning library server, Might return
12010: 'unavailable', 'not_found', 'forbidden', 'ok', or
12011: 'bad_request', also attempts to grab the metadata for the
12012: resource. Expects the local filesystem pathname
12013: (/home/httpd/html/res/....)
12014: 
12015: =back
12016: 
12017: =head2 Resource Information
12018: 
12019: =over 4
12020: 
12021: =item *
12022: 
12023: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12024: a vairety of different possible values, $varname should be a request
12025: string, and the other parameters can be used to specify who and what
12026: one is asking about.
12027: 
12028: Possible values for $varname are environment.lastname (or other item
12029: from the envirnment hash), user.name (or someother aspect about the
12030: user), resource.0.maxtries (or some other part and parameter of a
12031: resource)
12032: 
12033: =item *
12034: 
12035: directcondval($number) : get current value of a condition; reads from a state
12036: string
12037: 
12038: =item *
12039: 
12040: condval($condidx) : value of condition index based on state
12041: 
12042: =item *
12043: 
12044: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12045: resource's metadata, $what should be either a specific key, or either
12046: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12047: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12048: 
12049: this function automatically caches all requests
12050: 
12051: =item *
12052: 
12053: metadata_query($query,$custom,$customshow) : make a metadata query against the
12054: network of library servers; returns file handle of where SQL and regex results
12055: will be stored for query
12056: 
12057: =item *
12058: 
12059: symbread($filename) : return symbolic list entry (filename argument optional);
12060: returns the data handle
12061: 
12062: =item *
12063: 
12064: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12065: a possible symb for the URL in $thisfn, and if is an encryypted
12066: resource that the user accessed using /enc/ returns a 1 on success, 0
12067: on failure, user must be in a course, as it assumes the existance of
12068: the course initial hash, and uses $env('request.course.id'}
12069: 
12070: 
12071: =item *
12072: 
12073: symbclean($symb) : removes versions numbers from a symb, returns the
12074: cleaned symb
12075: 
12076: =item *
12077: 
12078: is_on_map($uri) : checks if the $uri is somewhere on the current
12079: course map, user must be in a course for it to work.
12080: 
12081: =item *
12082: 
12083: numval($salt) : return random seed value (addend for rndseed)
12084: 
12085: =item *
12086: 
12087: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12088: a random seed, all arguments are optional, if they aren't sent it uses the
12089: environment to derive them. Note: if symb isn't sent and it can't get one
12090: from &symbread it will use the current time as its return value
12091: 
12092: =item *
12093: 
12094: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12095: unfakeable, receipt
12096: 
12097: =item *
12098: 
12099: receipt() : API to ireceipt working off of env values; given out to users
12100: 
12101: =item *
12102: 
12103: countacc($url) : count the number of accesses to a given URL
12104: 
12105: =item *
12106: 
12107: 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
12108: 
12109: =item *
12110: 
12111: 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)
12112: 
12113: =item *
12114: 
12115: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12116: 
12117: =item *
12118: 
12119: devalidate($symb) : devalidate temporary spreadsheet calculations,
12120: forcing spreadsheet to reevaluate the resource scores next time.
12121: 
12122: =back
12123: 
12124: =head2 Storing/Retreiving Data
12125: 
12126: =over 4
12127: 
12128: =item *
12129: 
12130: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12131: for this url; hashref needs to be given and should be a \%hashname; the
12132: remaining args aren't required and if they aren't passed or are '' they will
12133: be derived from the env
12134: 
12135: =item *
12136: 
12137: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12138: uses critical subroutine
12139: 
12140: =item *
12141: 
12142: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12143: all args are optional
12144: 
12145: =item *
12146: 
12147: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12148: dumps the complete (or key matching regexp) namespace into a hash
12149: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12150: normally &store()ed into
12151: 
12152: $range should be either an integer '100' (give me the first 100
12153:                                            matching records)
12154:               or be  two integers sperated by a - with no spaces
12155:                  '30-50' (give me the 30th through the 50th matching
12156:                           records)
12157: 
12158: 
12159: =item *
12160: 
12161: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12162: replaces a &store() version of data with a replacement set of data
12163: for a particular resource in a namespace passed in the $storehash hash 
12164: reference
12165: 
12166: =item *
12167: 
12168: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12169: works very similar to store/cstore, but all data is stored in a
12170: temporary location and can be reset using tmpreset, $storehash should
12171: be a hash reference, returns nothing on success
12172: 
12173: =item *
12174: 
12175: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12176: similar to restore, but all data is stored in a temporary location and
12177: can be reset using tmpreset. Returns a hash of values on success,
12178: error string otherwise.
12179: 
12180: =item *
12181: 
12182: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12183: deltes all keys for $symb form the temporary storage hash.
12184: 
12185: =item *
12186: 
12187: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12188: reference filled in from namesp ($udom and $uname are optional)
12189: 
12190: =item *
12191: 
12192: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12193: namesp ($udom and $uname are optional)
12194: 
12195: =item *
12196: 
12197: dump($namespace,$udom,$uname,$regexp,$range) : 
12198: dumps the complete (or key matching regexp) namespace into a hash
12199: ($udom, $uname, $regexp, $range are optional)
12200: 
12201: $range should be either an integer '100' (give me the first 100
12202:                                            matching records)
12203:               or be  two integers sperated by a - with no spaces
12204:                  '30-50' (give me the 30th through the 50th matching
12205:                           records)
12206: =item *
12207: 
12208: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12209: $store can be a scalar, an array reference, or if the amount to be 
12210: incremented is > 1, a hash reference.
12211: 
12212: ($udom and $uname are optional)
12213: 
12214: =item *
12215: 
12216: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12217: ($udom and $uname are optional)
12218: 
12219: =item *
12220: 
12221: cput($namespace,$storehash,$udom,$uname) : critical put
12222: ($udom and $uname are optional)
12223: 
12224: =item *
12225: 
12226: newput($namespace,$storehash,$udom,$uname) :
12227: 
12228: Attempts to store the items in the $storehash, but only if they don't
12229: currently exist, if this succeeds you can be certain that you have 
12230: successfully created a new key value pair in the $namespace db.
12231: 
12232: 
12233: Args:
12234:  $namespace: name of database to store values to
12235:  $storehash: hashref to store to the db
12236:  $udom: (optional) domain of user containing the db
12237:  $uname: (optional) name of user caontaining the db
12238: 
12239: Returns:
12240:  'ok' -> succeeded in storing all keys of $storehash
12241:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12242:                         least <key> already existed in the db (other
12243:                         requested keys may also already exist)
12244:  'error: <msg>' -> unable to tie the DB or other error occurred
12245:  'con_lost' -> unable to contact request server
12246:  'refused' -> action was not allowed by remote machine
12247: 
12248: 
12249: =item *
12250: 
12251: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12252: reference filled in from namesp (encrypts the return communication)
12253: ($udom and $uname are optional)
12254: 
12255: =item *
12256: 
12257: log($udom,$name,$home,$message) : write to permanent log for user; use
12258: critical subroutine
12259: 
12260: =item *
12261: 
12262: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12263: array reference filled in from namespace found in domain level on either
12264: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12265: 
12266: =item *
12267: 
12268: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12269: domain level either on specified domain server ($uhome) or primary domain 
12270: server ($udom and $uhome are optional)
12271: 
12272: =item * 
12273: 
12274: get_domain_defaults($target_domain) : returns hash with defaults for
12275: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12276: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12277: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12278: Values are retrieved from cache (if current), or from domain's configuration.db
12279: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12280: or lonTabs/domain.tab. 
12281: 
12282: %domdefaults = &get_auth_defaults($target_domain);
12283: 
12284: =back
12285: 
12286: =head2 Network Status Functions
12287: 
12288: =over 4
12289: 
12290: =item *
12291: 
12292: dirlist() : return directory list based on URI (first arg).
12293: 
12294: Inputs: 1 required, 5 optional.
12295: 
12296: =over
12297: 
12298: =item 
12299: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12300: 
12301: =item
12302: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12303: 
12304: =item
12305: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12306: 
12307: =item
12308: $getpropath - boolean: 1 if prepend path using &propath(). 
12309: 
12310: =item
12311: $getuserdir - boolean: 1 if prepend path for "userfiles".
12312: 
12313: =item 
12314: $alternateRoot - path to prepend in place of path from $uri.
12315: 
12316: =back
12317: 
12318: Returns: Array of up to two items.
12319: 
12320: =over
12321: 
12322: a reference to an array of files/subdirectories
12323: 
12324: =over
12325: 
12326: Each element in the array of files/subdirectories is a & separated list of
12327: item name and the result of running stat on the item.  If dirlist was requested
12328: for a file instead of a directory, the item name will be ''. For a directory 
12329: listing, if the item is a metadata file, the element will end &N&M 
12330: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12331: default copyright set (1).  
12332: 
12333: =back
12334: 
12335: a scalar containing error condition (if encountered).
12336: 
12337: =over
12338: 
12339: =item 
12340: no_host (no homeserver identified for $username:$domain).
12341: 
12342: =item 
12343: no_such_host (server contacted for listing not identified as valid host).
12344: 
12345: =item 
12346: con_lost (connection to remote server failed).
12347: 
12348: =item 
12349: refused (invalid $username:$domain received on lond side).
12350: 
12351: =item 
12352: no_such_dir (directory at specified path on lond side does not exist). 
12353: 
12354: =item 
12355: empty (directory at specified path on lond side is empty).
12356: 
12357: =over
12358: 
12359: This is currently not encountered because the &ls3, &ls2, 
12360: &ls (_handler) routines on the lond side do not filter out
12361: . and .. from a directory listing. 
12362: 
12363: =back
12364: 
12365: =back
12366: 
12367: =back
12368: 
12369: =item *
12370: 
12371: spareserver() : find server with least workload from spare.tab
12372: 
12373: 
12374: =item *
12375: 
12376: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12377: if there is no corresponding loncapa host.
12378: 
12379: =back
12380: 
12381: 
12382: =head2 Apache Request
12383: 
12384: =over 4
12385: 
12386: =item *
12387: 
12388: ssi($url,%hash) : server side include, does a complete request cycle on url to
12389: localhost, posts hash
12390: 
12391: =back
12392: 
12393: =head2 Data to String to Data
12394: 
12395: =over 4
12396: 
12397: =item *
12398: 
12399: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12400: and '&' separators, supports elements that are arrayrefs and hashrefs
12401: 
12402: =item *
12403: 
12404: hashref2str($hashref) : convert a hashref into a string complete with
12405: escaping and '=' and '&' separators, supports elements that are
12406: arrayrefs and hashrefs
12407: 
12408: =item *
12409: 
12410: arrayref2str($arrayref) : convert an arrayref into a string complete
12411: with escaping and '&' separators, supports elements that are arrayrefs
12412: and hashrefs
12413: 
12414: =item *
12415: 
12416: str2hash($string) : convert string to hash using unescaping and
12417: splitting on '=' and '&', supports elements that are arrayrefs and
12418: hashrefs
12419: 
12420: =item *
12421: 
12422: str2array($string) : convert string to hash using unescaping and
12423: splitting on '&', supports elements that are arrayrefs and hashrefs
12424: 
12425: =back
12426: 
12427: =head2 Logging Routines
12428: 
12429: 
12430: These routines allow one to make log messages in the lonnet.log and
12431: lonnet.perm logfiles.
12432: 
12433: =over 4
12434: 
12435: =item *
12436: 
12437: logtouch() : make sure the logfile, lonnet.log, exists
12438: 
12439: =item *
12440: 
12441: logthis() : append message to the normal lonnet.log file, it gets
12442: preiodically rolled over and deleted.
12443: 
12444: =item *
12445: 
12446: logperm() : append a permanent message to lonnet.perm.log, this log
12447: file never gets deleted by any automated portion of the system, only
12448: messages of critical importance should go in here.
12449: 
12450: 
12451: =back
12452: 
12453: =head2 General File Helper Routines
12454: 
12455: =over 4
12456: 
12457: =item *
12458: 
12459: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12460: (a) files in /uploaded
12461:   (i) If a local copy of the file exists - 
12462:       compares modification date of local copy with last-modified date for 
12463:       definitive version stored on home server for course. If local copy is 
12464:       stale, requests a new version from the home server and stores it. 
12465:       If the original has been removed from the home server, then local copy 
12466:       is unlinked.
12467:   (ii) If local copy does not exist -
12468:       requests the file from the home server and stores it. 
12469:   
12470:   If $caller is 'uploadrep':  
12471:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12472:     for request for files originally uploaded via DOCS. 
12473:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12474:   
12475:   Otherwise:
12476:      This indicates a call from the content generation phase of the request.
12477:      -  returns the entire contents of the file or -1.
12478:      
12479: (b) files in /res
12480:    - returns the entire contents of a file or -1; 
12481:    it properly subscribes to and replicates the file if neccessary.
12482: 
12483: 
12484: =item *
12485: 
12486: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12487:                   reference
12488: 
12489: returns either a stat() list of data about the file or an empty list
12490: if the file doesn't exist or couldn't find out about it (connection
12491: problems or user unknown)
12492: 
12493: =item *
12494: 
12495: filelocation($dir,$file) : returns file system location of a file
12496: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12497: directory that relative $file lookups are to looked in ($dir of /a/dir
12498: and a file of ../bob will become /a/bob)
12499: 
12500: =item *
12501: 
12502: hreflocation($dir,$file) : returns file system location or a URL; same as
12503: filelocation except for hrefs
12504: 
12505: =item *
12506: 
12507: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12508: 
12509: =back
12510: 
12511: =head2 Usererfile file routines (/uploaded*)
12512: 
12513: =over 4
12514: 
12515: =item *
12516: 
12517: userfileupload(): main rotine for putting a file in a user or course's
12518:                   filespace, arguments are,
12519: 
12520:  formname - required - this is the name of the element in $env where the
12521:            filename, and the contents of the file to create/modifed exist
12522:            the filename is in $env{'form.'.$formname.'.filename'} and the
12523:            contents of the file is located in $env{'form.'.$formname}
12524:  context - if coursedoc, store the file in the course of the active role
12525:              of the current user; 
12526:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12527:            if 'canceloverwrite': delete file in tmp/overwrites directory
12528:  subdir - required - subdirectory to put the file in under ../userfiles/
12529:          if undefined, it will be placed in "unknown"
12530: 
12531:  (This routine calls clean_filename() to remove any dangerous
12532:  characters from the filename, and then calls finuserfileupload() to
12533:  complete the transaction)
12534: 
12535:  returns either the url of the uploaded file (/uploaded/....) if successful
12536:  and /adm/notfound.html if unsuccessful
12537: 
12538: =item *
12539: 
12540: clean_filename(): routine for cleaing a filename up for storage in
12541:                  userfile space, argument is:
12542: 
12543:  filename - proposed filename
12544: 
12545: returns: the new clean filename
12546: 
12547: =item *
12548: 
12549: finishuserfileupload(): routine that creates and sends the file to
12550: userspace, probably shouldn't be called directly
12551: 
12552:   docuname: username or courseid of destination for the file
12553:   docudom: domain of user/course of destination for the file
12554:   formname: same as for userfileupload()
12555:   fname: filename (including subdirectories) for the file
12556:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12557:   allfiles: reference to hash used to store objects found by parser
12558:   codebase: reference to hash used for codebases of java objects found by parser
12559:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12560:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12561:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12562:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12563:   context: if 'overwrite', will move the uploaded file from its temporary location to
12564:             userfiles to facilitate overwriting a previously uploaded file with same name.
12565:   mimetype: reference to scalar to accommodate mime type determined
12566:             from File::MMagic if $parser = parse.
12567: 
12568:  returns either the url of the uploaded file (/uploaded/....) if successful
12569:  and /adm/notfound.html if unsuccessful (or an error message if context 
12570:  was 'overwrite').
12571:  
12572: 
12573: =item *
12574: 
12575: renameuserfile(): renames an existing userfile to a new name
12576: 
12577:   Args:
12578:    docuname: username or courseid of destination for the file
12579:    docudom: domain of user/course of destination for the file
12580:    old: current file name (including any subdirs under userfiles)
12581:    new: desired file name (including any subdirs under userfiles)
12582: 
12583: =item *
12584: 
12585: mkdiruserfile(): creates a directory is a userfiles dir
12586: 
12587:   Args:
12588:    docuname: username or courseid of destination for the file
12589:    docudom: domain of user/course of destination for the file
12590:    dir: dir to create (including any subdirs under userfiles)
12591: 
12592: =item *
12593: 
12594: removeuserfile(): removes a file that exists in userfiles
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:    fname: filname to delete (including any subdirs under userfiles)
12600: 
12601: =item *
12602: 
12603: removeuploadedurl(): convience function for removeuserfile()
12604: 
12605:   Args:
12606:    url:  a full /uploaded/... url to delete
12607: 
12608: =item * 
12609: 
12610: get_portfile_permissions():
12611:   Args:
12612:     domain: domain of user or course contain the portfolio files
12613:     user: name of user or num of course contain the portfolio files
12614:   Returns:
12615:     hashref of a dump of the proper file_permissions.db
12616:    
12617: 
12618: =item * 
12619: 
12620: get_access_controls():
12621: 
12622: Args:
12623:   current_permissions: the hash ref returned from get_portfile_permissions()
12624:   group: (optional) the group you want the files associated with
12625:   file: (optional) the file you want access info on
12626: 
12627: Returns:
12628:     a hash (keys are file names) of hashes containing
12629:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12630:         values are XML containing access control settings (see below) 
12631: 
12632: Internal notes:
12633: 
12634:  access controls are stored in file_permissions.db as key=value pairs.
12635:     key -> path to file/file_name\0uniqueID:scope_end_start
12636:         where scope -> public,guest,course,group,domains or users.
12637:               end -> UNIX time for end of access (0 -> no end date)
12638:               start -> UNIX time for start of access
12639: 
12640:     value -> XML description of access control
12641:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12642:             <start></start>
12643:             <end></end>
12644: 
12645:             <password></password>  for scope type = guest
12646: 
12647:             <domain></domain>     for scope type = course or group
12648:             <number></number>
12649:             <roles id="">
12650:              <role></role>
12651:              <access></access>
12652:              <section></section>
12653:              <group></group>
12654:             </roles>
12655: 
12656:             <dom></dom>         for scope type = domains
12657: 
12658:             <users>             for scope type = users
12659:              <user>
12660:               <uname></uname>
12661:               <udom></udom>
12662:              </user>
12663:             </users>
12664:            </scope> 
12665:               
12666:  Access data is also aggregated for each file in an additional key=value pair:
12667:  key -> path to file/file_name\0accesscontrol 
12668:  value -> reference to hash
12669:           hash contains key = value pairs
12670:           where key = uniqueID:scope_end_start
12671:                 value = UNIX time record was last updated
12672: 
12673:           Used to improve speed of look-ups of access controls for each file.  
12674:  
12675:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12676: 
12677: modify_access_controls():
12678: 
12679: Modifies access controls for a portfolio file
12680: Args
12681: 1. file name
12682: 2. reference to hash of required changes,
12683: 3. domain
12684: 4. username
12685:   where domain,username are the domain of the portfolio owner 
12686:   (either a user or a course) 
12687: 
12688: Returns:
12689: 1. result of additions or updates ('ok' or 'error', with error message). 
12690: 2. result of deletions ('ok' or 'error', with error message).
12691: 3. reference to hash of any new or updated access controls.
12692: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12693:    key = integer (inbound ID)
12694:    value = uniqueID  
12695: 
12696: =back
12697: 
12698: =head2 HTTP Helper Routines
12699: 
12700: =over 4
12701: 
12702: =item *
12703: 
12704: escape() : unpack non-word characters into CGI-compatible hex codes
12705: 
12706: =item *
12707: 
12708: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12709: 
12710: =back
12711: 
12712: =head1 PRIVATE SUBROUTINES
12713: 
12714: =head2 Underlying communication routines (Shouldn't call)
12715: 
12716: =over 4
12717: 
12718: =item *
12719: 
12720: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12721: 
12722: =item *
12723: 
12724: reply() : uses subreply to send a message to remote machine, logs all failures
12725: 
12726: =item *
12727: 
12728: critical() : passes a critical message to another server; if cannot
12729: get through then place message in connection buffer directory and
12730: returns con_delayed, if incapable of saving message, returns
12731: con_failed
12732: 
12733: =item *
12734: 
12735: reconlonc() : tries to reconnect lonc client processes.
12736: 
12737: =back
12738: 
12739: =head2 Resource Access Logging
12740: 
12741: =over 4
12742: 
12743: =item *
12744: 
12745: flushcourselogs() : flush (save) buffer logs and access logs
12746: 
12747: =item *
12748: 
12749: courselog($what) : save message for course in hash
12750: 
12751: =item *
12752: 
12753: courseacclog($what) : save message for course using &courselog().  Perform
12754: special processing for specific resource types (problems, exams, quizzes, etc).
12755: 
12756: =item *
12757: 
12758: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12759: as a PerlChildExitHandler
12760: 
12761: =back
12762: 
12763: =head2 Other
12764: 
12765: =over 4
12766: 
12767: =item *
12768: 
12769: symblist($mapname,%newhash) : update symbolic storage links
12770: 
12771: =back
12772: 
12773: =cut
12774: 

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