File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.909: download - view: text, annotated - select for diffs
Fri Aug 31 12:33:29 2007 UTC (16 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Institutional directory search now reported as unavailable in the case where a DC has enabled directory searching via "Modify domain configuration" but either:
 (a) localenroll::get_userinfo() has not been customized, or
 (b) an error ioccurred when querying the institutional directory.

lonsql
- &do_inst_dir_search() returns 'unavailable' if the response from localenroll::get_userinfo() is not 'ok'

lonnet.pm
- &inst_directory_query() now returns a scalar and a hash.
  - scalar is the outcome of the query: 'unavailable', 'ok' or ''.
  - hash contains the search results (if any matches)

loncreateuser.pm
- Report to user that institutional directory search is unavailable if response from &lonnet::inst_directory_query() is not 'ok'.

localenroll.pm
- documentation updated
- &get_userinfo() returns 'unavailable' by default

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.909 2007/08/31 12:33:29 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Date;
   35: # use Date::Parse;
   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   37:             $_64bit %env);
   38: 
   39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   42:     %courseownerbuf, %coursetypebuf);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use Fcntl qw(:flock);
   48: use Storable qw(thaw nfreeze);
   49: use Time::HiRes qw( gettimeofday tv_interval );
   50: use Cache::Memcached;
   51: use Digest::MD5;
   52: use Math::Random;
   53: use LONCAPA qw(:DEFAULT :match);
   54: use LONCAPA::Configuration;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: {
   89:     my $logid;
   90:     sub instructor_log {
   91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   92: 	$logid++;
   93: 	my $id=time().'00000'.$$.'00000'.$logid;
   94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   95: 				    { $id => {
   96: 					'exe_uname' => $env{'user.name'},
   97: 					'exe_udom'  => $env{'user.domain'},
   98: 					'exe_time'  => time(),
   99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  100: 					'delflag'   => $delflag,
  101: 					'logentry'  => $storehash,
  102: 					'uname'     => $uname,
  103: 					'udom'      => $udom,
  104: 				    }
  105: 				  },
  106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  108: 				    );
  109:     }
  110: }
  111: 
  112: sub logtouch {
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     unless (-e "$execdir/logs/lonnet.log") {	
  115: 	open(my $fh,">>$execdir/logs/lonnet.log");
  116: 	close $fh;
  117:     }
  118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  120: }
  121: 
  122: sub logthis {
  123:     my $message=shift;
  124:     my $execdir=$perlvar{'lonDaemons'};
  125:     my $now=time;
  126:     my $local=localtime($now);
  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  128: 	print $fh "$local ($$): $message\n";
  129: 	close($fh);
  130:     }
  131:     return 1;
  132: }
  133: 
  134: sub logperm {
  135:     my $message=shift;
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     my $now=time;
  138:     my $local=localtime($now);
  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  140: 	print $fh "$now:$message:$local\n";
  141: 	close($fh);
  142:     }
  143:     return 1;
  144: }
  145: 
  146: sub create_connection {
  147:     my ($hostname,$lonid) = @_;
  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  149: 				     Type    => SOCK_STREAM,
  150: 				     Timeout => 10);
  151:     return 0 if (!$client);
  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  153:     my $result = <$client>;
  154:     chomp($result);
  155:     return 1 if ($result eq 'done');
  156:     return 0;
  157: }
  158: 
  159: 
  160: # -------------------------------------------------- Non-critical communication
  161: sub subreply {
  162:     my ($cmd,$server)=@_;
  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  164:     #
  165:     #  With loncnew process trimming, there's a timing hole between lonc server
  166:     #  process exit and the master server picking up the listen on the AF_UNIX
  167:     #  socket.  In that time interval, a lock file will exist:
  168: 
  169:     my $lockfile=$peerfile.".lock";
  170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  171: 	sleep(1);
  172:     }
  173:     # At this point, either a loncnew parent is listening or an old lonc
  174:     # or loncnew child is listening so we can connect or everything's dead.
  175:     #
  176:     #   We'll give the connection a few tries before abandoning it.  If
  177:     #   connection is not possible, we'll con_lost back to the client.
  178:     #   
  179:     my $client;
  180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  182: 				      Type    => SOCK_STREAM,
  183: 				      Timeout => 10);
  184: 	if ($client) {
  185: 	    last;		# Connected!
  186: 	} else {
  187: 	    &create_connection(&hostname($server),$server);
  188: 	}
  189:         sleep(1);		# Try again later if failed connection.
  190:     }
  191:     my $answer;
  192:     if ($client) {
  193: 	print $client "sethost:$server:$cmd\n";
  194: 	$answer=<$client>;
  195: 	if (!$answer) { $answer="con_lost"; }
  196: 	chomp($answer);
  197:     } else {
  198: 	$answer = 'con_lost';	# Failed connection.
  199:     }
  200:     return $answer;
  201: }
  202: 
  203: sub reply {
  204:     my ($cmd,$server)=@_;
  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  206:     my $answer=subreply($cmd,$server);
  207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  208:        &logthis("<font color=\"blue\">WARNING:".
  209:                 " $cmd to $server returned $answer</font>");
  210:     }
  211:     return $answer;
  212: }
  213: 
  214: # ----------------------------------------------------------- Send USR1 to lonc
  215: 
  216: sub reconlonc {
  217:     my ($lonid) = @_;
  218:     my $hostname = &hostname($lonid);
  219:     if ($lonid) {
  220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  221: 	if ($hostname && -e $peerfile) {
  222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  224: 					     Type    => SOCK_STREAM,
  225: 					     Timeout => 10);
  226: 	    if ($client) {
  227: 		print $client ("reset_retries\n");
  228: 		my $answer=<$client>;
  229: 		#reset just this one.
  230: 	    }
  231: 	}
  232: 	return;
  233:     }
  234: 
  235:     &logthis("Trying to reconnect lonc");
  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  237:     if (open(my $fh,"<$loncfile")) {
  238: 	my $loncpid=<$fh>;
  239:         chomp($loncpid);
  240:         if (kill 0 => $loncpid) {
  241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  242:             kill USR1 => $loncpid;
  243:             sleep 1;
  244:          } else {
  245: 	    &logthis(
  246:                "<font color=\"blue\">WARNING:".
  247:                " lonc at pid $loncpid not responding, giving up</font>");
  248:         }
  249:     } else {
  250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  251:     }
  252: }
  253: 
  254: # ------------------------------------------------------ Critical communication
  255: 
  256: sub critical {
  257:     my ($cmd,$server)=@_;
  258:     unless (&hostname($server)) {
  259:         &logthis("<font color=\"blue\">WARNING:".
  260:                " Critical message to unknown server ($server)</font>");
  261:         return 'no_such_host';
  262:     }
  263:     my $answer=reply($cmd,$server);
  264:     if ($answer eq 'con_lost') {
  265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  266: 	my $answer=reply($cmd,$server);
  267:         if ($answer eq 'con_lost') {
  268:             my $now=time;
  269:             my $middlename=$cmd;
  270:             $middlename=substr($middlename,0,16);
  271:             $middlename=~s/\W//g;
  272:             my $dfilename=
  273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  274:             $dumpcount++;
  275:             {
  276: 		my $dfh;
  277: 		if (open($dfh,">$dfilename")) {
  278: 		    print $dfh "$cmd\n"; 
  279: 		    close($dfh);
  280: 		}
  281:             }
  282:             sleep 2;
  283:             my $wcmd='';
  284:             {
  285: 		my $dfh;
  286: 		if (open($dfh,"<$dfilename")) {
  287: 		    $wcmd=<$dfh>; 
  288: 		    close($dfh);
  289: 		}
  290:             }
  291:             chomp($wcmd);
  292:             if ($wcmd eq $cmd) {
  293: 		&logthis("<font color=\"blue\">WARNING: ".
  294:                          "Connection buffer $dfilename: $cmd</font>");
  295:                 &logperm("D:$server:$cmd");
  296: 	        return 'con_delayed';
  297:             } else {
  298:                 &logthis("<font color=\"red\">CRITICAL:"
  299:                         ." Critical connection failed: $server $cmd</font>");
  300:                 &logperm("F:$server:$cmd");
  301:                 return 'con_failed';
  302:             }
  303:         }
  304:     }
  305:     return $answer;
  306: }
  307: 
  308: # ------------------------------------------- check if return value is an error
  309: 
  310: sub error {
  311:     my ($result) = @_;
  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  313: 	if ($2 == 2) { return undef; }
  314: 	return $1;
  315:     }
  316:     return undef;
  317: }
  318: 
  319: sub convert_and_load_session_env {
  320:     my ($lonidsdir,$handle)=@_;
  321:     my @profile;
  322:     {
  323: 	open(my $idf,"$lonidsdir/$handle.id");
  324: 	flock($idf,LOCK_SH);
  325: 	@profile=<$idf>;
  326: 	close($idf);
  327:     }
  328:     my %temp_env;
  329:     foreach my $line (@profile) {
  330: 	if ($line !~ m/=/) {
  331: 	    return 0;
  332: 	}
  333: 	chomp($line);
  334: 	my ($envname,$envvalue)=split(/=/,$line,2);
  335: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  336:     }
  337:     unlink("$lonidsdir/$handle.id");
  338:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  339: 	    0640)) {
  340: 	%disk_env = %temp_env;
  341: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  342: 	untie(%disk_env);
  343:     }
  344:     return 1;
  345: }
  346: 
  347: # ------------------------------------------- Transfer profile into environment
  348: my $env_loaded;
  349: sub transfer_profile_to_env {
  350:     my ($lonidsdir,$handle,$force_transfer) = @_;
  351:     if (!$force_transfer && $env_loaded) { return; } 
  352: 
  353:     if (!defined($lonidsdir)) {
  354: 	$lonidsdir = $perlvar{'lonIDsDir'};
  355:     }
  356:     if (!defined($handle)) {
  357:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  358:     }
  359: 
  360:     my $convert;
  361:     {
  362:     	open(my $idf,"$lonidsdir/$handle.id");
  363: 	flock($idf,LOCK_SH);
  364: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  365: 		&GDBM_READER(),0640)) {
  366: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  367: 	    untie(%disk_env);
  368: 	} else {
  369: 	    $convert = 1;
  370: 	}
  371:     }
  372:     if ($convert) {
  373: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  374: 	    &logthis("Failed to load session, or convert session.");
  375: 	}
  376:     }
  377: 
  378:     my %remove;
  379:     while ( my $envname = each(%env) ) {
  380:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  381:             if ($time < time-300) {
  382:                 $remove{$key}++;
  383:             }
  384:         }
  385:     }
  386: 
  387:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  388:     $env_loaded=1;
  389:     foreach my $expired_key (keys(%remove)) {
  390:         &delenv($expired_key);
  391:     }
  392: }
  393: 
  394: sub timed_flock {
  395:     my ($file,$lock_type) = @_;
  396:     my $failed=0;
  397:     eval {
  398: 	local $SIG{__DIE__}='DEFAULT';
  399: 	local $SIG{ALRM}=sub {
  400: 	    $failed=1;
  401: 	    die("failed lock");
  402: 	};
  403: 	alarm(13);
  404: 	flock($file,$lock_type);
  405: 	alarm(0);
  406:     };
  407:     if ($failed) {
  408: 	return undef;
  409:     } else {
  410: 	return 1;
  411:     }
  412: }
  413: 
  414: # ---------------------------------------------------------- Append Environment
  415: 
  416: sub appenv {
  417:     my %newenv=@_;
  418:     foreach my $key (keys(%newenv)) {
  419: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  420:             &logthis("<font color=\"blue\">WARNING: ".
  421:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  422:                 .'</font>');
  423: 	    delete($newenv{$key});
  424:         } else {
  425:             $env{$key}=$newenv{$key};
  426:         }
  427:     }
  428:     open(my $env_file,$env{'user.environment'});
  429:     if (&timed_flock($env_file,LOCK_EX)
  430: 	&&
  431: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  432: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  433: 	while (my ($key,$value) = each(%newenv)) {
  434: 	    $disk_env{$key} = $value;
  435: 	}
  436: 	untie(%disk_env);
  437:     }
  438:     return 'ok';
  439: }
  440: # ----------------------------------------------------- Delete from Environment
  441: 
  442: sub delenv {
  443:     my $delthis=shift;
  444:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  445:         &logthis("<font color=\"blue\">WARNING: ".
  446:                 "Attempt to delete from environment ".$delthis);
  447:         return 'error';
  448:     }
  449:     open(my $env_file,$env{'user.environment'});
  450:     if (&timed_flock($env_file,LOCK_EX)
  451: 	&&
  452: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  453: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  454: 	foreach my $key (keys(%disk_env)) {
  455: 	    if ($key=~/^$delthis/) { 
  456:                 delete($env{$key});
  457:                 delete($disk_env{$key});
  458:             }
  459: 	}
  460: 	untie(%disk_env);
  461:     }
  462:     return 'ok';
  463: }
  464: 
  465: sub get_env_multiple {
  466:     my ($name) = @_;
  467:     my @values;
  468:     if (defined($env{$name})) {
  469:         # exists is it an array
  470:         if (ref($env{$name})) {
  471:             @values=@{ $env{$name} };
  472:         } else {
  473:             $values[0]=$env{$name};
  474:         }
  475:     }
  476:     return(@values);
  477: }
  478: 
  479: # ------------------------------------------ Find out current server userload
  480: # there is a copy in lond
  481: sub userload {
  482:     my $numusers=0;
  483:     {
  484: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  485: 	my $filename;
  486: 	my $curtime=time;
  487: 	while ($filename=readdir(LONIDS)) {
  488: 	    if ($filename eq '.' || $filename eq '..') {next;}
  489: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  490: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  491: 	}
  492: 	closedir(LONIDS);
  493:     }
  494:     my $userloadpercent=0;
  495:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  496:     if ($maxuserload) {
  497: 	$userloadpercent=100*$numusers/$maxuserload;
  498:     }
  499:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  500:     return $userloadpercent;
  501: }
  502: 
  503: # ------------------------------------------ Fight off request when overloaded
  504: 
  505: sub overloaderror {
  506:     my ($r,$checkserver)=@_;
  507:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  508:     my $loadavg;
  509:     if ($checkserver eq $perlvar{'lonHostID'}) {
  510:        open(my $loadfile,'/proc/loadavg');
  511:        $loadavg=<$loadfile>;
  512:        $loadavg =~ s/\s.*//g;
  513:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  514:        close($loadfile);
  515:     } else {
  516:        $loadavg=&reply('load',$checkserver);
  517:     }
  518:     my $overload=$loadavg-100;
  519:     if ($overload>0) {
  520: 	$r->err_headers_out->{'Retry-After'}=$overload;
  521:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  522:         return 413;
  523:     }    
  524:     return '';
  525: }
  526: 
  527: # ------------------------------ Find server with least workload from spare.tab
  528: 
  529: sub spareserver {
  530:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  531:     my $spare_server;
  532:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  533:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  534:                                                      :  $userloadpercent;
  535:     
  536:     foreach my $try_server (@{ $spareid{'primary'} }) {
  537: 	($spare_server, $lowest_load) =
  538: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  539:     }
  540: 
  541:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  542: 
  543:     if (!$found_server) {
  544: 	foreach my $try_server (@{ $spareid{'default'} }) {
  545: 	    ($spare_server, $lowest_load) =
  546: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  547: 	}
  548:     }
  549: 
  550:     if (!$want_server_name) {
  551: 	$spare_server="http://".&hostname($spare_server);
  552:     }
  553:     return $spare_server;
  554: }
  555: 
  556: sub compare_server_load {
  557:     my ($try_server, $spare_server, $lowest_load) = @_;
  558: 
  559:     my $loadans     = &reply('load',    $try_server);
  560:     my $userloadans = &reply('userload',$try_server);
  561: 
  562:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  563: 	next; #didn't get a number from the server
  564:     }
  565: 
  566:     my $load;
  567:     if ($loadans =~ /\d/) {
  568: 	if ($userloadans =~ /\d/) {
  569: 	    #both are numbers, pick the bigger one
  570: 	    $load = ($loadans > $userloadans) ? $loadans 
  571: 		                              : $userloadans;
  572: 	} else {
  573: 	    $load = $loadans;
  574: 	}
  575:     } else {
  576: 	$load = $userloadans;
  577:     }
  578: 
  579:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  580: 	$spare_server = $try_server;
  581: 	$lowest_load  = $load;
  582:     }
  583:     return ($spare_server,$lowest_load);
  584: }
  585: # --------------------------------------------- Try to change a user's password
  586: 
  587: sub changepass {
  588:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  589:     $currentpass = &escape($currentpass);
  590:     $newpass     = &escape($newpass);
  591:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  592: 		       $server);
  593:     if (! $answer) {
  594: 	&logthis("No reply on password change request to $server ".
  595: 		 "by $uname in domain $udom.");
  596:     } elsif ($answer =~ "^ok") {
  597:         &logthis("$uname in $udom successfully changed their password ".
  598: 		 "on $server.");
  599:     } elsif ($answer =~ "^pwchange_failure") {
  600: 	&logthis("$uname in $udom was unable to change their password ".
  601: 		 "on $server.  The action was blocked by either lcpasswd ".
  602: 		 "or pwchange");
  603:     } elsif ($answer =~ "^non_authorized") {
  604:         &logthis("$uname in $udom did not get their password correct when ".
  605: 		 "attempting to change it on $server.");
  606:     } elsif ($answer =~ "^auth_mode_error") {
  607:         &logthis("$uname in $udom attempted to change their password despite ".
  608: 		 "not being locally or internally authenticated on $server.");
  609:     } elsif ($answer =~ "^unknown_user") {
  610:         &logthis("$uname in $udom attempted to change their password ".
  611: 		 "on $server but were unable to because $server is not ".
  612: 		 "their home server.");
  613:     } elsif ($answer =~ "^refused") {
  614: 	&logthis("$server refused to change $uname in $udom password because ".
  615: 		 "it was sent an unencrypted request to change the password.");
  616:     }
  617:     return $answer;
  618: }
  619: 
  620: # ----------------------- Try to determine user's current authentication scheme
  621: 
  622: sub queryauthenticate {
  623:     my ($uname,$udom)=@_;
  624:     my $uhome=&homeserver($uname,$udom);
  625:     if (!$uhome) {
  626: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  627: 	return 'no_host';
  628:     }
  629:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  630:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  631: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  632:     }
  633:     return $answer;
  634: }
  635: 
  636: # --------- Try to authenticate user from domain's lib servers (first this one)
  637: 
  638: sub authenticate {
  639:     my ($uname,$upass,$udom)=@_;
  640:     $upass=&escape($upass);
  641:     $uname= &LONCAPA::clean_username($uname);
  642:     my $uhome=&homeserver($uname,$udom,1);
  643:     if ((!$uhome) || ($uhome eq 'no_host')) {
  644: # Maybe the machine was offline and only re-appeared again recently?
  645:         &reconlonc();
  646: # One more
  647: 	my $uhome=&homeserver($uname,$udom,1);
  648: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  649: 	    &logthis("User $uname at $udom is unknown in authenticate");
  650: 	}
  651: 	return 'no_host';
  652:     }
  653:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  654:     if ($answer eq 'authorized') {
  655: 	&logthis("User $uname at $udom authorized by $uhome"); 
  656: 	return $uhome; 
  657:     }
  658:     if ($answer eq 'non_authorized') {
  659: 	&logthis("User $uname at $udom rejected by $uhome");
  660: 	return 'no_host'; 
  661:     }
  662:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  663:     return 'no_host';
  664: }
  665: 
  666: # ---------------------- Find the homebase for a user from domain's lib servers
  667: 
  668: my %homecache;
  669: sub homeserver {
  670:     my ($uname,$udom,$ignoreBadCache)=@_;
  671:     my $index="$uname:$udom";
  672: 
  673:     if (exists($homecache{$index})) { return $homecache{$index}; }
  674: 
  675:     my %servers = &get_servers($udom,'library');
  676:     foreach my $tryserver (keys(%servers)) {
  677:         next if ($ignoreBadCache ne 'true' && 
  678: 		 exists($badServerCache{$tryserver}));
  679: 
  680: 	my $answer=reply("home:$udom:$uname",$tryserver);
  681: 	if ($answer eq 'found') {
  682: 	    delete($badServerCache{$tryserver}); 
  683: 	    return $homecache{$index}=$tryserver;
  684: 	} elsif ($answer eq 'no_host') {
  685: 	    $badServerCache{$tryserver}=1;
  686: 	}
  687:     }    
  688:     return 'no_host';
  689: }
  690: 
  691: # ------------------------------------- Find the usernames behind a list of IDs
  692: 
  693: sub idget {
  694:     my ($udom,@ids)=@_;
  695:     my %returnhash=();
  696:     
  697:     my %servers = &get_servers($udom,'library');
  698:     foreach my $tryserver (keys(%servers)) {
  699: 	my $idlist=join('&',@ids);
  700: 	$idlist=~tr/A-Z/a-z/; 
  701: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  702: 	my @answer=();
  703: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  704: 	    @answer=split(/\&/,$reply);
  705: 	}                    ;
  706: 	my $i;
  707: 	for ($i=0;$i<=$#ids;$i++) {
  708: 	    if ($answer[$i]) {
  709: 		$returnhash{$ids[$i]}=$answer[$i];
  710: 	    } 
  711: 	}
  712:     } 
  713:     return %returnhash;
  714: }
  715: 
  716: # ------------------------------------- Find the IDs behind a list of usernames
  717: 
  718: sub idrget {
  719:     my ($udom,@unames)=@_;
  720:     my %returnhash=();
  721:     foreach my $uname (@unames) {
  722:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  723:     }
  724:     return %returnhash;
  725: }
  726: 
  727: # ------------------------------- Store away a list of names and associated IDs
  728: 
  729: sub idput {
  730:     my ($udom,%ids)=@_;
  731:     my %servers=();
  732:     foreach my $uname (keys(%ids)) {
  733: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  734:         my $uhom=&homeserver($uname,$udom);
  735:         if ($uhom ne 'no_host') {
  736:             my $id=&escape($ids{$uname});
  737:             $id=~tr/A-Z/a-z/;
  738:             my $esc_unam=&escape($uname);
  739: 	    if ($servers{$uhom}) {
  740: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  741:             } else {
  742:                 $servers{$uhom}=$id.'='.$esc_unam;
  743:             }
  744:         }
  745:     }
  746:     foreach my $server (keys(%servers)) {
  747:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  748:     }
  749: }
  750: 
  751: # ------------------------------------------- get items from domain db files   
  752: 
  753: sub get_dom {
  754:     my ($namespace,$storearr,$udom,$uhome)=@_;
  755:     my $items='';
  756:     foreach my $item (@$storearr) {
  757:         $items.=&escape($item).'&';
  758:     }
  759:     $items=~s/\&$//;
  760:     if (!$udom) {
  761:         $udom=$env{'user.domain'};
  762:         if (defined(&domain($udom,'primary'))) {
  763:             $uhome=&domain($udom,'primary');
  764:         } else {
  765:             undef($uhome);
  766:         }
  767:     } else {
  768:         if (!$uhome) {
  769:             if (defined(&domain($udom,'primary'))) {
  770:                 $uhome=&domain($udom,'primary');
  771:             }
  772:         }
  773:     }
  774:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  775:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  776:         my %returnhash;
  777:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  778:             return %returnhash;
  779:         }
  780:         my @pairs=split(/\&/,$rep);
  781:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  782:             return @pairs;
  783:         }
  784:         my $i=0;
  785:         foreach my $item (@$storearr) {
  786:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  787:             $i++;
  788:         }
  789:         return %returnhash;
  790:     } else {
  791:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  792:     }
  793: }
  794: 
  795: # -------------------------------------------- put items in domain db files 
  796: 
  797: sub put_dom {
  798:     my ($namespace,$storehash,$udom,$uhome)=@_;
  799:     if (!$udom) {
  800:         $udom=$env{'user.domain'};
  801:         if (defined(&domain($udom,'primary'))) {
  802:             $uhome=&domain($udom,'primary');
  803:         } else {
  804:             undef($uhome);
  805:         }
  806:     } else {
  807:         if (!$uhome) {
  808:             if (defined(&domain($udom,'primary'))) {
  809:                 $uhome=&domain($udom,'primary');
  810:             }
  811:         }
  812:     } 
  813:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  814:         my $items='';
  815:         foreach my $item (keys(%$storehash)) {
  816:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  817:         }
  818:         $items=~s/\&$//;
  819:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  820:     } else {
  821:         &logthis("put_dom failed - no homeserver and/or domain");
  822:     }
  823: }
  824: 
  825: sub retrieve_inst_usertypes {
  826:     my ($udom) = @_;
  827:     my (%returnhash,@order);
  828:     if (defined(&domain($udom,'primary'))) {
  829:         my $uhome=&domain($udom,'primary');
  830:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  831:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  832:         my @pairs=split(/\&/,$hashitems);
  833:         foreach my $item (@pairs) {
  834:             my ($key,$value)=split(/=/,$item,2);
  835:             $key = &unescape($key);
  836:             next if ($key =~ /^error: 2 /);
  837:             $returnhash{$key}=&thaw_unescape($value);
  838:         }
  839:         my @esc_order = split(/\&/,$orderitems);
  840:         foreach my $item (@esc_order) {
  841:             push(@order,&unescape($item));
  842:         }
  843:     } else {
  844:         &logthis("get_dom failed - no primary domain server for $udom");
  845:     }
  846:     return (\%returnhash,\@order);
  847: }
  848: 
  849: sub is_domainimage {
  850:     my ($url) = @_;
  851:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  852:         if (&domain($1) ne '') {
  853:             return '1';
  854:         }
  855:     }
  856:     return;
  857: }
  858: 
  859: sub inst_directory_query {
  860:     my ($srch) = @_;
  861:     my $udom = $srch->{'srchdomain'};
  862:     my %results;
  863:     my $homeserver = &domain($udom,'primary');
  864:     my $outcome;
  865:     if ($homeserver ne '') {
  866: 	my $queryid=&reply("querysend:instdirsearch:".
  867: 			   &escape($srch->{'srchby'}).':'.
  868: 			   &escape($srch->{'srchterm'}).':'.
  869: 			   &escape($srch->{'srchtype'}),$homeserver);
  870: 	my $host=&hostname($homeserver);
  871: 	if ($queryid !~/^\Q$host\E\_/) {
  872: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  873: 	    return;
  874: 	}
  875: 	my $response = &get_query_reply($queryid);
  876: 	my $maxtries = 5;
  877: 	my $tries = 1;
  878: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  879: 	    $response = &get_query_reply($queryid);
  880: 	    $tries ++;
  881: 	}
  882: 
  883:         if (!&error($response) && $response ne 'refused') {
  884:             if ($response eq 'unavailable') {
  885:                 $outcome = $response;
  886:             } else {
  887:                 $outcome = 'ok';
  888:                 my @matches = split(/\n/,$response);
  889:                 foreach my $match (@matches) {
  890:                     my ($key,$value) = split(/=/,$match);
  891:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  892:                 }
  893:             }
  894:         }
  895:     }
  896:     return ($outcome,%results);
  897: }
  898: 
  899: sub usersearch {
  900:     my ($srch) = @_;
  901:     my $dom = $srch->{'srchdomain'};
  902:     my %results;
  903:     my %libserv = &all_library();
  904:     my $query = 'usersearch';
  905:     foreach my $tryserver (keys(%libserv)) {
  906:         if (&host_domain($tryserver) eq $dom) {
  907:             my $host=&hostname($tryserver);
  908:             my $queryid=
  909:                 &reply("querysend:".&escape($query).':'.&escape($dom).':'.
  910:                        &escape($srch->{'srchby'}).'%%'.
  911:                        &escape($srch->{'srchtype'}).':'.
  912:                        &escape($srch->{'srchterm'}),$tryserver);
  913:             if ($queryid !~/^\Q$host\E\_/) {
  914:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  915:                 next;
  916:             }
  917:             my $reply = &get_query_reply($queryid);
  918:             my $maxtries = 1;
  919:             my $tries = 1;
  920:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
  921:                 $reply = &get_query_reply($queryid);
  922:                 $tries ++;
  923:             }
  924:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
  925:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
  926:             } else {
  927:                 my @matches = split(/&/,$reply);
  928:                 foreach my $match (@matches) {
  929:                     my @items = split(/:/,$match);
  930:                     my ($uname,$udom,%userhash);
  931:                     foreach my $entry (@items) {
  932:                         my ($key,$value) = split(/=/,$entry);
  933:                         $key = &unescape($key);
  934:                         $value = &unescape($value);
  935:                         $userhash{$key} = $value;
  936:                         if ($key eq 'username') {
  937:                             $uname = $value;
  938:                         } elsif ($key eq 'domain') {
  939:                             $udom = $value;
  940:                         } 
  941:                     }
  942:                     $results{$uname.':'.$udom} = \%userhash;
  943:                 }
  944:             }
  945:         }
  946:     }
  947:     return %results;
  948: }
  949: 
  950: # --------------------------------------------------- Assign a key to a student
  951: 
  952: sub assign_access_key {
  953: #
  954: # a valid key looks like uname:udom#comments
  955: # comments are being appended
  956: #
  957:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  958:     $kdom=
  959:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  960:     $knum=
  961:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  962:     $cdom=
  963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  964:     $cnum=
  965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  966:     $udom=$env{'user.name'} unless (defined($udom));
  967:     $uname=$env{'user.domain'} unless (defined($uname));
  968:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  969:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  970:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  971:                                                   # assigned to this person
  972:                                                   # - this should not happen,
  973:                                                   # unless something went wrong
  974:                                                   # the first time around
  975: # ready to assign
  976:         $logentry=$1.'; '.$logentry;
  977:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  978:                                                  $kdom,$knum) eq 'ok') {
  979: # key now belongs to user
  980: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  981:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  982:                 &appenv('environment.'.$envkey => $ckey);
  983:                 return 'ok';
  984:             } else {
  985:                 return 
  986:   'error: Count not permanently assign key, will need to be re-entered later.';
  987: 	    }
  988:         } else {
  989:             return 'error: Could not assign key, try again later.';
  990:         }
  991:     } elsif (!$existing{$ckey}) {
  992: # the key does not exist
  993: 	return 'error: The key does not exist';
  994:     } else {
  995: # the key is somebody else's
  996: 	return 'error: The key is already in use';
  997:     }
  998: }
  999: 
 1000: # ------------------------------------------ put an additional comment on a key
 1001: 
 1002: sub comment_access_key {
 1003: #
 1004: # a valid key looks like uname:udom#comments
 1005: # comments are being appended
 1006: #
 1007:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1008:     $cdom=
 1009:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1010:     $cnum=
 1011:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1012:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1013:     if ($existing{$ckey}) {
 1014:         $existing{$ckey}.='; '.$logentry;
 1015: # ready to assign
 1016:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1017:                                                  $cdom,$cnum) eq 'ok') {
 1018: 	    return 'ok';
 1019:         } else {
 1020: 	    return 'error: Count not store comment.';
 1021:         }
 1022:     } else {
 1023: # the key does not exist
 1024: 	return 'error: The key does not exist';
 1025:     }
 1026: }
 1027: 
 1028: # ------------------------------------------------------ Generate a set of keys
 1029: 
 1030: sub generate_access_keys {
 1031:     my ($number,$cdom,$cnum,$logentry)=@_;
 1032:     $cdom=
 1033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1034:     $cnum=
 1035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1036:     unless (&allowed('mky',$cdom)) { return 0; }
 1037:     unless (($cdom) && ($cnum)) { return 0; }
 1038:     if ($number>10000) { return 0; }
 1039:     sleep(2); # make sure don't get same seed twice
 1040:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1041:     my $total=0;
 1042:     for (my $i=1;$i<=$number;$i++) {
 1043:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1044:                   sprintf("%lx",int(100000*rand)).'-'.
 1045:                   sprintf("%lx",int(100000*rand));
 1046:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1047:        $newkey=~s/0/h/g; # and also 0 and O
 1048:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1049:        if ($existing{$newkey}) {
 1050:            $i--;
 1051:        } else {
 1052: 	  if (&put('accesskeys',
 1053:               { $newkey => '# generated '.localtime().
 1054:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1055:                            '; '.$logentry },
 1056: 		   $cdom,$cnum) eq 'ok') {
 1057:               $total++;
 1058: 	  }
 1059:        }
 1060:     }
 1061:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1062:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1063:     return $total;
 1064: }
 1065: 
 1066: # ------------------------------------------------------- Validate an accesskey
 1067: 
 1068: sub validate_access_key {
 1069:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1070:     $cdom=
 1071:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1072:     $cnum=
 1073:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1074:     $udom=$env{'user.domain'} unless (defined($udom));
 1075:     $uname=$env{'user.name'} unless (defined($uname));
 1076:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1077:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1078: }
 1079: 
 1080: # ------------------------------------- Find the section of student in a course
 1081: sub devalidate_getsection_cache {
 1082:     my ($udom,$unam,$courseid)=@_;
 1083:     my $hashid="$udom:$unam:$courseid";
 1084:     &devalidate_cache_new('getsection',$hashid);
 1085: }
 1086: 
 1087: sub courseid_to_courseurl {
 1088:     my ($courseid) = @_;
 1089:     #already url style courseid
 1090:     return $courseid if ($courseid =~ m{^/});
 1091: 
 1092:     if (exists($env{'course.'.$courseid.'.num'})) {
 1093: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1094: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1095: 	return "/$cdom/$cnum";
 1096:     }
 1097: 
 1098:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1099:     if (exists($courseinfo{'num'})) {
 1100: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1101:     }
 1102: 
 1103:     return undef;
 1104: }
 1105: 
 1106: sub getsection {
 1107:     my ($udom,$unam,$courseid)=@_;
 1108:     my $cachetime=1800;
 1109: 
 1110:     my $hashid="$udom:$unam:$courseid";
 1111:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1112:     if (defined($cached)) { return $result; }
 1113: 
 1114:     my %Pending; 
 1115:     my %Expired;
 1116:     #
 1117:     # Each role can either have not started yet (pending), be active, 
 1118:     #    or have expired.
 1119:     #
 1120:     # If there is an active role, we are done.
 1121:     #
 1122:     # If there is more than one role which has not started yet, 
 1123:     #     choose the one which will start sooner
 1124:     # If there is one role which has not started yet, return it.
 1125:     #
 1126:     # If there is more than one expired role, choose the one which ended last.
 1127:     # If there is a role which has expired, return it.
 1128:     #
 1129:     $courseid = &courseid_to_courseurl($courseid);
 1130:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1131:     foreach my $key (keys(%roleshash)) {
 1132:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1133:         my $section=$1;
 1134:         if ($key eq $courseid.'_st') { $section=''; }
 1135:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1136:         my $now=time;
 1137:         if (defined($end) && $end && ($now > $end)) {
 1138:             $Expired{$end}=$section;
 1139:             next;
 1140:         }
 1141:         if (defined($start) && $start && ($now < $start)) {
 1142:             $Pending{$start}=$section;
 1143:             next;
 1144:         }
 1145:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1146:     }
 1147:     #
 1148:     # Presumedly there will be few matching roles from the above
 1149:     # loop and the sorting time will be negligible.
 1150:     if (scalar(keys(%Pending))) {
 1151:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1152:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1153:     } 
 1154:     if (scalar(keys(%Expired))) {
 1155:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1156:         my $time = pop(@sorted);
 1157:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1158:     }
 1159:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1160: }
 1161: 
 1162: sub save_cache {
 1163:     &purge_remembered();
 1164:     #&Apache::loncommon::validate_page();
 1165:     undef(%env);
 1166:     undef($env_loaded);
 1167: }
 1168: 
 1169: my $to_remember=-1;
 1170: my %remembered;
 1171: my %accessed;
 1172: my $kicks=0;
 1173: my $hits=0;
 1174: sub make_key {
 1175:     my ($name,$id) = @_;
 1176:     if (length($id) > 65 
 1177: 	&& length(&escape($id)) > 200) {
 1178: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1179:     }
 1180:     return &escape($name.':'.$id);
 1181: }
 1182: 
 1183: sub devalidate_cache_new {
 1184:     my ($name,$id,$debug) = @_;
 1185:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1186:     $id=&make_key($name,$id);
 1187:     $memcache->delete($id);
 1188:     delete($remembered{$id});
 1189:     delete($accessed{$id});
 1190: }
 1191: 
 1192: sub is_cached_new {
 1193:     my ($name,$id,$debug) = @_;
 1194:     $id=&make_key($name,$id);
 1195:     if (exists($remembered{$id})) {
 1196: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1197: 	$accessed{$id}=[&gettimeofday()];
 1198: 	$hits++;
 1199: 	return ($remembered{$id},1);
 1200:     }
 1201:     my $value = $memcache->get($id);
 1202:     if (!(defined($value))) {
 1203: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1204: 	return (undef,undef);
 1205:     }
 1206:     if ($value eq '__undef__') {
 1207: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1208: 	$value=undef;
 1209:     }
 1210:     &make_room($id,$value,$debug);
 1211:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1212:     return ($value,1);
 1213: }
 1214: 
 1215: sub do_cache_new {
 1216:     my ($name,$id,$value,$time,$debug) = @_;
 1217:     $id=&make_key($name,$id);
 1218:     my $setvalue=$value;
 1219:     if (!defined($setvalue)) {
 1220: 	$setvalue='__undef__';
 1221:     }
 1222:     if (!defined($time) ) {
 1223: 	$time=600;
 1224:     }
 1225:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1226:     if (!($memcache->set($id,$setvalue,$time))) {
 1227: 	&logthis("caching of id -> $id  failed");
 1228:     }
 1229:     # need to make a copy of $value
 1230:     #&make_room($id,$value,$debug);
 1231:     return $value;
 1232: }
 1233: 
 1234: sub make_room {
 1235:     my ($id,$value,$debug)=@_;
 1236:     $remembered{$id}=$value;
 1237:     if ($to_remember<0) { return; }
 1238:     $accessed{$id}=[&gettimeofday()];
 1239:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1240:     my $to_kick;
 1241:     my $max_time=0;
 1242:     foreach my $other (keys(%accessed)) {
 1243: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1244: 	    $to_kick=$other;
 1245: 	    $max_time=&tv_interval($accessed{$other});
 1246: 	}
 1247:     }
 1248:     delete($remembered{$to_kick});
 1249:     delete($accessed{$to_kick});
 1250:     $kicks++;
 1251:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1252:     return;
 1253: }
 1254: 
 1255: sub purge_remembered {
 1256:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1257:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1258:     undef(%remembered);
 1259:     undef(%accessed);
 1260: }
 1261: # ------------------------------------- Read an entry from a user's environment
 1262: 
 1263: sub userenvironment {
 1264:     my ($udom,$unam,@what)=@_;
 1265:     my %returnhash=();
 1266:     my @answer=split(/\&/,
 1267:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1268:                       &homeserver($unam,$udom)));
 1269:     my $i;
 1270:     for ($i=0;$i<=$#what;$i++) {
 1271: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1272:     }
 1273:     return %returnhash;
 1274: }
 1275: 
 1276: # ---------------------------------------------------------- Get a studentphoto
 1277: sub studentphoto {
 1278:     my ($udom,$unam,$ext) = @_;
 1279:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1280:     if (defined($env{'request.course.id'})) {
 1281:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1282:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1283:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1284:             } else {
 1285:                 my ($result,$perm_reqd)=
 1286: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1287:                 if ($result eq 'ok') {
 1288:                     if (!($perm_reqd eq 'yes')) {
 1289:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1290:                     }
 1291:                 }
 1292:             }
 1293:         }
 1294:     } else {
 1295:         my ($result,$perm_reqd) = 
 1296: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1297:         if ($result eq 'ok') {
 1298:             if (!($perm_reqd eq 'yes')) {
 1299:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1300:             }
 1301:         }
 1302:     }
 1303:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1304: }
 1305: 
 1306: sub retrievestudentphoto {
 1307:     my ($udom,$unam,$ext,$type) = @_;
 1308:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1309:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1310:     if ($ret eq 'ok') {
 1311:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1312:         if ($type eq 'thumbnail') {
 1313:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1314:         }
 1315:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1316:         return $tokenurl;
 1317:     } else {
 1318:         if ($type eq 'thumbnail') {
 1319:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1320:         } else { 
 1321:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1322:         }
 1323:     }
 1324: }
 1325: 
 1326: # -------------------------------------------------------------------- New chat
 1327: 
 1328: sub chatsend {
 1329:     my ($newentry,$anon,$group)=@_;
 1330:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1331:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1332:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1333:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1334: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1335: 		   &escape($newentry)).':'.$group,$chome);
 1336: }
 1337: 
 1338: # ------------------------------------------ Find current version of a resource
 1339: 
 1340: sub getversion {
 1341:     my $fname=&clutter(shift);
 1342:     unless ($fname=~/^\/res\//) { return -1; }
 1343:     return &currentversion(&filelocation('',$fname));
 1344: }
 1345: 
 1346: sub currentversion {
 1347:     my $fname=shift;
 1348:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1349:     if (defined($cached)) { return $result; }
 1350:     my $author=$fname;
 1351:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1352:     my ($udom,$uname)=split(/\//,$author);
 1353:     my $home=homeserver($uname,$udom);
 1354:     if ($home eq 'no_host') { 
 1355:         return -1; 
 1356:     }
 1357:     my $answer=reply("currentversion:$fname",$home);
 1358:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1359: 	return -1;
 1360:     }
 1361:     return &do_cache_new('resversion',$fname,$answer,600);
 1362: }
 1363: 
 1364: # ----------------------------- Subscribe to a resource, return URL if possible
 1365: 
 1366: sub subscribe {
 1367:     my $fname=shift;
 1368:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1369:     $fname=~s/[\n\r]//g;
 1370:     my $author=$fname;
 1371:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1372:     my ($udom,$uname)=split(/\//,$author);
 1373:     my $home=homeserver($uname,$udom);
 1374:     if ($home eq 'no_host') {
 1375:         return 'not_found';
 1376:     }
 1377:     my $answer=reply("sub:$fname",$home);
 1378:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1379: 	$answer.=' by '.$home;
 1380:     }
 1381:     return $answer;
 1382: }
 1383:     
 1384: # -------------------------------------------------------------- Replicate file
 1385: 
 1386: sub repcopy {
 1387:     my $filename=shift;
 1388:     $filename=~s/\/+/\//g;
 1389:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1390:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1391:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1392: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1393: 	return &repcopy_userfile($filename);
 1394:     }
 1395:     $filename=~s/[\n\r]//g;
 1396:     my $transname="$filename.in.transfer";
 1397: # FIXME: this should flock
 1398:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1399:     my $remoteurl=subscribe($filename);
 1400:     if ($remoteurl =~ /^con_lost by/) {
 1401: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1402:            return 'unavailable';
 1403:     } elsif ($remoteurl eq 'not_found') {
 1404: 	   #&logthis("Subscribe returned not_found: $filename");
 1405: 	   return 'not_found';
 1406:     } elsif ($remoteurl =~ /^rejected by/) {
 1407: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1408:            return 'forbidden';
 1409:     } elsif ($remoteurl eq 'directory') {
 1410:            return 'ok';
 1411:     } else {
 1412:         my $author=$filename;
 1413:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1414:         my ($udom,$uname)=split(/\//,$author);
 1415:         my $home=homeserver($uname,$udom);
 1416:         unless ($home eq $perlvar{'lonHostID'}) {
 1417:            my @parts=split(/\//,$filename);
 1418:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1419:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1420:                &logthis("Malconfiguration for replication: $filename");
 1421: 	       return 'bad_request';
 1422:            }
 1423:            my $count;
 1424:            for ($count=5;$count<$#parts;$count++) {
 1425:                $path.="/$parts[$count]";
 1426:                if ((-e $path)!=1) {
 1427: 		   mkdir($path,0777);
 1428:                }
 1429:            }
 1430:            my $ua=new LWP::UserAgent;
 1431:            my $request=new HTTP::Request('GET',"$remoteurl");
 1432:            my $response=$ua->request($request,$transname);
 1433:            if ($response->is_error()) {
 1434: 	       unlink($transname);
 1435:                my $message=$response->status_line;
 1436:                &logthis("<font color=\"blue\">WARNING:"
 1437:                        ." LWP get: $message: $filename</font>");
 1438:                return 'unavailable';
 1439:            } else {
 1440: 	       if ($remoteurl!~/\.meta$/) {
 1441:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1442:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1443:                   if ($mresponse->is_error()) {
 1444: 		      unlink($filename.'.meta');
 1445:                       &logthis(
 1446:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1447:                   }
 1448: 	       }
 1449:                rename($transname,$filename);
 1450:                return 'ok';
 1451:            }
 1452:        }
 1453:     }
 1454: }
 1455: 
 1456: # ------------------------------------------------ Get server side include body
 1457: sub ssi_body {
 1458:     my ($filelink,%form)=@_;
 1459:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1460:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1461:     }
 1462:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1463:                                      &ssi($filelink,%form));
 1464:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1465:     $output=~s/^.*?\<body[^\>]*\>//si;
 1466:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1467:     return $output;
 1468: }
 1469: 
 1470: # --------------------------------------------------------- Server Side Include
 1471: 
 1472: sub absolute_url {
 1473:     my ($host_name) = @_;
 1474:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1475:     if ($host_name eq '') {
 1476: 	$host_name = $ENV{'SERVER_NAME'};
 1477:     }
 1478:     return $protocol.$host_name;
 1479: }
 1480: 
 1481: sub ssi {
 1482: 
 1483:     my ($fn,%form)=@_;
 1484: 
 1485:     my $ua=new LWP::UserAgent;
 1486:     
 1487:     my $request;
 1488: 
 1489:     $form{'no_update_last_known'}=1;
 1490:     &Apache::lonenc::check_encrypt(\$fn);
 1491:     if (%form) {
 1492:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1493:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1494:     } else {
 1495:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1496:     }
 1497: 
 1498:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1499:     my $response=$ua->request($request);
 1500: 
 1501:     return $response->content;
 1502: }
 1503: 
 1504: sub externalssi {
 1505:     my ($url)=@_;
 1506:     my $ua=new LWP::UserAgent;
 1507:     my $request=new HTTP::Request('GET',$url);
 1508:     my $response=$ua->request($request);
 1509:     return $response->content;
 1510: }
 1511: 
 1512: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1513: 
 1514: sub allowuploaded {
 1515:     my ($srcurl,$url)=@_;
 1516:     $url=&clutter(&declutter($url));
 1517:     my $dir=$url;
 1518:     $dir=~s/\/[^\/]+$//;
 1519:     my %httpref=();
 1520:     my $httpurl=&hreflocation('',$url);
 1521:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1522:     &Apache::lonnet::appenv(%httpref);
 1523: }
 1524: 
 1525: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1526: # input: action, courseID, current domain, intended
 1527: #        path to file, source of file, instruction to parse file for objects,
 1528: #        ref to hash for embedded objects,
 1529: #        ref to hash for codebase of java objects.
 1530: #
 1531: # output: url to file (if action was uploaddoc), 
 1532: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1533: #
 1534: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1535: # course.
 1536: #
 1537: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1538: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1539: #          course's home server.
 1540: #
 1541: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1542: #          be copied from $source (current location) to 
 1543: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1544: #         and will then be copied to
 1545: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1546: #         course's home server.
 1547: #
 1548: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1549: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1550: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1551: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1552: #         in course's home server.
 1553: #
 1554: 
 1555: sub process_coursefile {
 1556:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1557:     my $fetchresult;
 1558:     my $home=&homeserver($docuname,$docudom);
 1559:     if ($action eq 'propagate') {
 1560:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1561: 			     $home);
 1562:     } else {
 1563:         my $fpath = '';
 1564:         my $fname = $file;
 1565:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1566:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1567:         my $filepath = &build_filepath($fpath);
 1568:         if ($action eq 'copy') {
 1569:             if ($source eq '') {
 1570:                 $fetchresult = 'no source file';
 1571:                 return $fetchresult;
 1572:             } else {
 1573:                 my $destination = $filepath.'/'.$fname;
 1574:                 rename($source,$destination);
 1575:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1576:                                  $home);
 1577:             }
 1578:         } elsif ($action eq 'uploaddoc') {
 1579:             open(my $fh,'>'.$filepath.'/'.$fname);
 1580:             print $fh $env{'form.'.$source};
 1581:             close($fh);
 1582:             if ($parser eq 'parse') {
 1583:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1584:                 unless ($parse_result eq 'ok') {
 1585:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1586:                 }
 1587:             }
 1588:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1589:                                  $home);
 1590:             if ($fetchresult eq 'ok') {
 1591:                 return '/uploaded/'.$fpath.'/'.$fname;
 1592:             } else {
 1593:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1594:                         ' to host '.$home.': '.$fetchresult);
 1595:                 return '/adm/notfound.html';
 1596:             }
 1597:         }
 1598:     }
 1599:     unless ( $fetchresult eq 'ok') {
 1600:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1601:              ' to host '.$home.': '.$fetchresult);
 1602:     }
 1603:     return $fetchresult;
 1604: }
 1605: 
 1606: sub build_filepath {
 1607:     my ($fpath) = @_;
 1608:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1609:     unless ($fpath eq '') {
 1610:         my @parts=split('/',$fpath);
 1611:         foreach my $part (@parts) {
 1612:             $filepath.= '/'.$part;
 1613:             if ((-e $filepath)!=1) {
 1614:                 mkdir($filepath,0777);
 1615:             }
 1616:         }
 1617:     }
 1618:     return $filepath;
 1619: }
 1620: 
 1621: sub store_edited_file {
 1622:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1623:     my $file = $primary_url;
 1624:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1625:     my $fpath = '';
 1626:     my $fname = $file;
 1627:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1628:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1629:     my $filepath = &build_filepath($fpath);
 1630:     open(my $fh,'>'.$filepath.'/'.$fname);
 1631:     print $fh $content;
 1632:     close($fh);
 1633:     my $home=&homeserver($docuname,$docudom);
 1634:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1635: 			  $home);
 1636:     if ($$fetchresult eq 'ok') {
 1637:         return '/uploaded/'.$fpath.'/'.$fname;
 1638:     } else {
 1639:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1640: 		 ' to host '.$home.': '.$$fetchresult);
 1641:         return '/adm/notfound.html';
 1642:     }
 1643: }
 1644: 
 1645: sub clean_filename {
 1646:     my ($fname,$args)=@_;
 1647: # Replace Windows backslashes by forward slashes
 1648:     $fname=~s/\\/\//g;
 1649:     if (!$args->{'keep_path'}) {
 1650:         # Get rid of everything but the actual filename
 1651: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1652:     }
 1653: # Replace spaces by underscores
 1654:     $fname=~s/\s+/\_/g;
 1655: # Replace all other weird characters by nothing
 1656:     $fname=~s{[^/\w\.\-]}{}g;
 1657: # Replace all .\d. sequences with _\d. so they no longer look like version
 1658: # numbers
 1659:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1660:     return $fname;
 1661: }
 1662: 
 1663: # --------------- Take an uploaded file and put it into the userfiles directory
 1664: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1665: #                    the desired filenam is in $env{"form.$formname.filename"}
 1666: #        $coursedoc - if true up to the current course
 1667: #                     if false
 1668: #        $subdir - directory in userfile to store the file into
 1669: #        $parser - instruction to parse file for objects ($parser = parse)    
 1670: #        $allfiles - reference to hash for embedded objects
 1671: #        $codebase - reference to hash for codebase of java objects
 1672: #        $desuname - username for permanent storage of uploaded file
 1673: #        $dsetudom - domain for permanaent storage of uploaded file
 1674: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1675: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1676: # 
 1677: # output: url of file in userspace, or error: <message> 
 1678: #             or /adm/notfound.html if failure to upload occurse
 1679: 
 1680: 
 1681: sub userfileupload {
 1682:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1683:         $destudom,$thumbwidth,$thumbheight)=@_;
 1684:     if (!defined($subdir)) { $subdir='unknown'; }
 1685:     my $fname=$env{'form.'.$formname.'.filename'};
 1686:     $fname=&clean_filename($fname);
 1687: # See if there is anything left
 1688:     unless ($fname) { return 'error: no uploaded file'; }
 1689:     chop($env{'form.'.$formname});
 1690:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1691:         my $now = time;
 1692:         my $filepath = 'tmp/helprequests/'.$now;
 1693:         my @parts=split(/\//,$filepath);
 1694:         my $fullpath = $perlvar{'lonDaemons'};
 1695:         for (my $i=0;$i<@parts;$i++) {
 1696:             $fullpath .= '/'.$parts[$i];
 1697:             if ((-e $fullpath)!=1) {
 1698:                 mkdir($fullpath,0777);
 1699:             }
 1700:         }
 1701:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1702:         print $fh $env{'form.'.$formname};
 1703:         close($fh);
 1704:         return $fullpath.'/'.$fname;
 1705:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1706:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1707:                        '_'.$env{'user.domain'}.'/pending';
 1708:         my @parts=split(/\//,$filepath);
 1709:         my $fullpath = $perlvar{'lonDaemons'};
 1710:         for (my $i=0;$i<@parts;$i++) {
 1711:             $fullpath .= '/'.$parts[$i];
 1712:             if ((-e $fullpath)!=1) {
 1713:                 mkdir($fullpath,0777);
 1714:             }
 1715:         }
 1716:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1717:         print $fh $env{'form.'.$formname};
 1718:         close($fh);
 1719:         return $fullpath.'/'.$fname;
 1720:     }
 1721:     
 1722: # Create the directory if not present
 1723:     $fname="$subdir/$fname";
 1724:     if ($coursedoc) {
 1725: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1726: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1727:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1728:             return &finishuserfileupload($docuname,$docudom,
 1729: 					 $formname,$fname,$parser,$allfiles,
 1730: 					 $codebase,$thumbwidth,$thumbheight);
 1731:         } else {
 1732:             $fname=$env{'form.folder'}.'/'.$fname;
 1733:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1734: 				       $fname,$formname,$parser,
 1735: 				       $allfiles,$codebase);
 1736:         }
 1737:     } elsif (defined($destuname)) {
 1738:         my $docuname=$destuname;
 1739:         my $docudom=$destudom;
 1740: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1741: 				     $parser,$allfiles,$codebase,
 1742:                                      $thumbwidth,$thumbheight);
 1743:         
 1744:     } else {
 1745:         my $docuname=$env{'user.name'};
 1746:         my $docudom=$env{'user.domain'};
 1747:         if (exists($env{'form.group'})) {
 1748:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1749:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1750:         }
 1751: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1752: 				     $parser,$allfiles,$codebase,
 1753:                                      $thumbwidth,$thumbheight);
 1754:     }
 1755: }
 1756: 
 1757: sub finishuserfileupload {
 1758:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1759:         $thumbwidth,$thumbheight) = @_;
 1760:     my $path=$docudom.'/'.$docuname.'/';
 1761:     my $filepath=$perlvar{'lonDocRoot'};
 1762:     my ($fnamepath,$file,$fetchthumb);
 1763:     $file=$fname;
 1764:     if ($fname=~m|/|) {
 1765:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1766: 	$path.=$fnamepath.'/';
 1767:     }
 1768:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1769:     my $count;
 1770:     for ($count=4;$count<=$#parts;$count++) {
 1771:         $filepath.="/$parts[$count]";
 1772:         if ((-e $filepath)!=1) {
 1773: 	    mkdir($filepath,0777);
 1774:         }
 1775:     }
 1776: # Save the file
 1777:     {
 1778: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1779: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1780: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1781: 	    return '/adm/notfound.html';
 1782: 	}
 1783: 	if (!print FH ($env{'form.'.$formname})) {
 1784: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1785: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1786: 	    return '/adm/notfound.html';
 1787: 	}
 1788: 	close(FH);
 1789:     }
 1790:     if ($parser eq 'parse') {
 1791:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1792: 						   $codebase);
 1793:         unless ($parse_result eq 'ok') {
 1794:             &logthis('Failed to parse '.$filepath.$file.
 1795: 		     ' for embedded media: '.$parse_result); 
 1796:         }
 1797:     }
 1798:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1799:         my $input = $filepath.'/'.$file;
 1800:         my $output = $filepath.'/'.'tn-'.$file;
 1801:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1802:         system("convert -sample $thumbsize $input $output");
 1803:         if (-e $filepath.'/'.'tn-'.$file) {
 1804:             $fetchthumb  = 1; 
 1805:         }
 1806:     }
 1807:  
 1808: # Notify homeserver to grep it
 1809: #
 1810:     my $docuhome=&homeserver($docuname,$docudom);
 1811:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1812:     if ($fetchresult eq 'ok') {
 1813:         if ($fetchthumb) {
 1814:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1815:             if ($thumbresult ne 'ok') {
 1816:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1817:                          $docuhome.': '.$thumbresult);
 1818:             }
 1819:         }
 1820: #
 1821: # Return the URL to it
 1822:         return '/uploaded/'.$path.$file;
 1823:     } else {
 1824:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1825: 		 ': '.$fetchresult);
 1826:         return '/adm/notfound.html';
 1827:     }
 1828: }
 1829: 
 1830: sub extract_embedded_items {
 1831:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1832:     my @state = ();
 1833:     my %javafiles = (
 1834:                       codebase => '',
 1835:                       code => '',
 1836:                       archive => ''
 1837:                     );
 1838:     my %mediafiles = (
 1839:                       src => '',
 1840:                       movie => '',
 1841:                      );
 1842:     my $p;
 1843:     if ($content) {
 1844:         $p = HTML::LCParser->new($content);
 1845:     } else {
 1846:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1847:     }
 1848:     while (my $t=$p->get_token()) {
 1849: 	if ($t->[0] eq 'S') {
 1850: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1851: 	    push(@state, $tagname);
 1852:             if (lc($tagname) eq 'allow') {
 1853:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1854:             }
 1855: 	    if (lc($tagname) eq 'img') {
 1856: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1857: 	    }
 1858: 	    if (lc($tagname) eq 'a') {
 1859: 		&add_filetype($allfiles,$attr->{'href'},'href');
 1860: 	    }
 1861:             if (lc($tagname) eq 'script') {
 1862:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1863:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1864:                 } else {
 1865:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1866:                 }
 1867:             }
 1868:             if (lc($tagname) eq 'link') {
 1869:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1870:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1871:                 }
 1872:             }
 1873: 	    if (lc($tagname) eq 'object' ||
 1874: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1875: 		foreach my $item (keys(%javafiles)) {
 1876: 		    $javafiles{$item} = '';
 1877: 		}
 1878: 	    }
 1879: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1880: 		my $name = lc($attr->{'name'});
 1881: 		foreach my $item (keys(%javafiles)) {
 1882: 		    if ($name eq $item) {
 1883: 			$javafiles{$item} = $attr->{'value'};
 1884: 			last;
 1885: 		    }
 1886: 		}
 1887: 		foreach my $item (keys(%mediafiles)) {
 1888: 		    if ($name eq $item) {
 1889: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1890: 			last;
 1891: 		    }
 1892: 		}
 1893: 	    }
 1894: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1895: 		foreach my $item (keys(%javafiles)) {
 1896: 		    if ($attr->{$item}) {
 1897: 			$javafiles{$item} = $attr->{$item};
 1898: 			last;
 1899: 		    }
 1900: 		}
 1901: 		foreach my $item (keys(%mediafiles)) {
 1902: 		    if ($attr->{$item}) {
 1903: 			&add_filetype($allfiles,$attr->{$item},$item);
 1904: 			last;
 1905: 		    }
 1906: 		}
 1907: 	    }
 1908: 	} elsif ($t->[0] eq 'E') {
 1909: 	    my ($tagname) = ($t->[1]);
 1910: 	    if ($javafiles{'codebase'} ne '') {
 1911: 		$javafiles{'codebase'} .= '/';
 1912: 	    }  
 1913: 	    if (lc($tagname) eq 'applet' ||
 1914: 		lc($tagname) eq 'object' ||
 1915: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1916: 		) {
 1917: 		foreach my $item (keys(%javafiles)) {
 1918: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1919: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1920: 			&add_filetype($allfiles,$file,$item);
 1921: 		    }
 1922: 		}
 1923: 	    } 
 1924: 	    pop @state;
 1925: 	}
 1926:     }
 1927:     return 'ok';
 1928: }
 1929: 
 1930: sub add_filetype {
 1931:     my ($allfiles,$file,$type)=@_;
 1932:     if (exists($allfiles->{$file})) {
 1933: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1934: 	    push(@{$allfiles->{$file}}, &escape($type));
 1935: 	}
 1936:     } else {
 1937: 	@{$allfiles->{$file}} = (&escape($type));
 1938:     }
 1939: }
 1940: 
 1941: sub removeuploadedurl {
 1942:     my ($url)=@_;
 1943:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1944:     return &removeuserfile($uname,$udom,$fname);
 1945: }
 1946: 
 1947: sub removeuserfile {
 1948:     my ($docuname,$docudom,$fname)=@_;
 1949:     my $home=&homeserver($docuname,$docudom);
 1950:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1951:     if ($result eq 'ok') {
 1952:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1953:             my $metafile = $fname.'.meta';
 1954:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1955: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1956:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1957:             my $sqlresult = 
 1958:                 &update_portfolio_table($docuname,$docudom,$file,
 1959:                                         'portfolio_metadata',$group,
 1960:                                         'delete');
 1961:         }
 1962:     }
 1963:     return $result;
 1964: }
 1965: 
 1966: sub mkdiruserfile {
 1967:     my ($docuname,$docudom,$dir)=@_;
 1968:     my $home=&homeserver($docuname,$docudom);
 1969:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1970: }
 1971: 
 1972: sub renameuserfile {
 1973:     my ($docuname,$docudom,$old,$new)=@_;
 1974:     my $home=&homeserver($docuname,$docudom);
 1975:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1976:                         &escape("$old").':'.&escape("$new"),$home);
 1977:     if ($result eq 'ok') {
 1978:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1979:             my $oldmeta = $old.'.meta';
 1980:             my $newmeta = $new.'.meta';
 1981:             my $metaresult = 
 1982:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1983: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1984:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1985:             my $sqlresult = 
 1986:                 &update_portfolio_table($docuname,$docudom,$file,
 1987:                                         'portfolio_metadata',$group,
 1988:                                         'delete');
 1989:         }
 1990:     }
 1991:     return $result;
 1992: }
 1993: 
 1994: # ------------------------------------------------------------------------- Log
 1995: 
 1996: sub log {
 1997:     my ($dom,$nam,$hom,$what)=@_;
 1998:     return critical("log:$dom:$nam:$what",$hom);
 1999: }
 2000: 
 2001: # ------------------------------------------------------------------ Course Log
 2002: #
 2003: # This routine flushes several buffers of non-mission-critical nature
 2004: #
 2005: 
 2006: sub flushcourselogs {
 2007:     &logthis('Flushing log buffers');
 2008: #
 2009: # course logs
 2010: # This is a log of all transactions in a course, which can be used
 2011: # for data mining purposes
 2012: #
 2013: # It also collects the courseid database, which lists last transaction
 2014: # times and course titles for all courseids
 2015: #
 2016:     my %courseidbuffer=();
 2017:     foreach my $crsid (keys %courselogs) {
 2018:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2019: 		          &escape($courselogs{$crsid}),
 2020: 		          $coursehombuf{$crsid}) eq 'ok') {
 2021: 	    delete $courselogs{$crsid};
 2022:         } else {
 2023:             &logthis('Failed to flush log buffer for '.$crsid);
 2024:             if (length($courselogs{$crsid})>40000) {
 2025:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2026:                         " exceeded maximum size, deleting.</font>");
 2027:                delete $courselogs{$crsid};
 2028:             }
 2029:         }
 2030:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 2031:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 2032: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 2033:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 2034:         } else {
 2035:            $courseidbuffer{$coursehombuf{$crsid}}=
 2036: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 2037:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 2038:         }
 2039:     }
 2040: #
 2041: # Write course id database (reverse lookup) to homeserver of courses 
 2042: # Is used in pickcourse
 2043: #
 2044:     foreach my $crs_home (keys(%courseidbuffer)) {
 2045:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 2046: 		     $crs_home);
 2047:     }
 2048: #
 2049: # File accesses
 2050: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2051: #
 2052:     foreach my $entry (keys(%accesshash)) {
 2053:         if ($entry =~ /___count$/) {
 2054:             my ($dom,$name);
 2055:             ($dom,$name,undef)=
 2056: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2057:             if (! defined($dom) || $dom eq '' || 
 2058:                 ! defined($name) || $name eq '') {
 2059:                 my $cid = $env{'request.course.id'};
 2060:                 $dom  = $env{'request.'.$cid.'.domain'};
 2061:                 $name = $env{'request.'.$cid.'.num'};
 2062:             }
 2063:             my $value = $accesshash{$entry};
 2064:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2065:             my %temphash=($url => $value);
 2066:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2067:             if ($result eq 'ok') {
 2068:                 delete $accesshash{$entry};
 2069:             } elsif ($result eq 'unknown_cmd') {
 2070:                 # Target server has old code running on it.
 2071:                 my %temphash=($entry => $value);
 2072:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2073:                     delete $accesshash{$entry};
 2074:                 }
 2075:             }
 2076:         } else {
 2077:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2078:             my %temphash=($entry => $accesshash{$entry});
 2079:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2080:                 delete $accesshash{$entry};
 2081:             }
 2082:         }
 2083:     }
 2084: #
 2085: # Roles
 2086: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2087: #
 2088:     foreach my $entry (keys(%userrolehash)) {
 2089:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2090: 	    split(/\:/,$entry);
 2091:         if (&Apache::lonnet::put('nohist_userroles',
 2092:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2093:                 $rudom,$runame) eq 'ok') {
 2094: 	    delete $userrolehash{$entry};
 2095:         }
 2096:     }
 2097: #
 2098: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2099: #
 2100:     my %domrolebuffer = ();
 2101:     foreach my $entry (keys %domainrolehash) {
 2102:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2103:         if ($domrolebuffer{$rudom}) {
 2104:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2105:                       '='.&escape($domainrolehash{$entry});
 2106:         } else {
 2107:             $domrolebuffer{$rudom}.=&escape($entry).
 2108:                       '='.&escape($domainrolehash{$entry});
 2109:         }
 2110:         delete $domainrolehash{$entry};
 2111:     }
 2112:     foreach my $dom (keys(%domrolebuffer)) {
 2113: 	my %servers = &get_servers($dom,'library');
 2114: 	foreach my $tryserver (keys(%servers)) {
 2115: 	    unless (&reply('domroleput:'.$dom.':'.
 2116: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2117: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2118: 	    }
 2119:         }
 2120:     }
 2121:     $dumpcount++;
 2122: }
 2123: 
 2124: sub courselog {
 2125:     my $what=shift;
 2126:     $what=time.':'.$what;
 2127:     unless ($env{'request.course.id'}) { return ''; }
 2128:     $coursedombuf{$env{'request.course.id'}}=
 2129:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2130:     $coursenumbuf{$env{'request.course.id'}}=
 2131:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2132:     $coursehombuf{$env{'request.course.id'}}=
 2133:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2134:     $coursedescrbuf{$env{'request.course.id'}}=
 2135:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2136:     $courseinstcodebuf{$env{'request.course.id'}}=
 2137:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2138:     $courseownerbuf{$env{'request.course.id'}}=
 2139:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2140:     $coursetypebuf{$env{'request.course.id'}}=
 2141:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2142:     if (defined $courselogs{$env{'request.course.id'}}) {
 2143: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2144:     } else {
 2145: 	$courselogs{$env{'request.course.id'}}.=$what;
 2146:     }
 2147:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2148: 	&flushcourselogs();
 2149:     }
 2150: }
 2151: 
 2152: sub courseacclog {
 2153:     my $fnsymb=shift;
 2154:     unless ($env{'request.course.id'}) { return ''; }
 2155:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2156:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2157:         $what.=':POST';
 2158:         # FIXME: Probably ought to escape things....
 2159: 	foreach my $key (keys(%env)) {
 2160:             if ($key=~/^form\.(.*)/) {
 2161: 		$what.=':'.$1.'='.$env{$key};
 2162:             }
 2163:         }
 2164:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2165:         # FIXME: We should not be depending on a form parameter that someone
 2166:         # editing lonsearchcat.pm might change in the future.
 2167:         if ($env{'form.phase'} eq 'course_search') {
 2168:             $what.= ':POST';
 2169:             # FIXME: Probably ought to escape things....
 2170:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2171:                                  'crsdiscuss') {
 2172:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2173:             }
 2174:         }
 2175:     }
 2176:     &courselog($what);
 2177: }
 2178: 
 2179: sub countacc {
 2180:     my $url=&declutter(shift);
 2181:     return if (! defined($url) || $url eq '');
 2182:     unless ($env{'request.course.id'}) { return ''; }
 2183:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2184:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2185:     $accesshash{$key}++;
 2186: }
 2187: 
 2188: sub linklog {
 2189:     my ($from,$to)=@_;
 2190:     $from=&declutter($from);
 2191:     $to=&declutter($to);
 2192:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2193:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2194: }
 2195:   
 2196: sub userrolelog {
 2197:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2198:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2199:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2200:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2201:         ($trole=~/^ta/)) {
 2202:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2203:        $userrolehash
 2204:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2205:                     =$tend.':'.$tstart;
 2206:     }
 2207:     if (($env{'request.role'} =~ /dc\./) &&
 2208: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2209: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2210: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2211:        $userrolehash
 2212:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2213:                     =$tend.':'.$tstart;
 2214:     }
 2215:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2216:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2217:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2218:         ($trole=~/^sc/)) {
 2219:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2220:        $domainrolehash
 2221:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2222:                     = $tend.':'.$tstart;
 2223:     }
 2224: }
 2225: 
 2226: sub get_course_adv_roles {
 2227:     my $cid=shift;
 2228:     $cid=$env{'request.course.id'} unless (defined($cid));
 2229:     my %coursehash=&coursedescription($cid);
 2230:     my %nothide=();
 2231:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2232: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2233:     }
 2234:     my %returnhash=();
 2235:     my %dumphash=
 2236:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2237:     my $now=time;
 2238:     foreach my $entry (keys %dumphash) {
 2239: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2240:         if (($tstart) && ($tstart<0)) { next; }
 2241:         if (($tend) && ($tend<$now)) { next; }
 2242:         if (($tstart) && ($now<$tstart)) { next; }
 2243:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2244: 	if ($username eq '' || $domain eq '') { next; }
 2245: 	if ((&privileged($username,$domain)) && 
 2246: 	    (!$nothide{$username.':'.$domain})) { next; }
 2247: 	if ($role eq 'cr') { next; }
 2248:         my $key=&plaintext($role);
 2249:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2250:         if ($returnhash{$key}) {
 2251: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2252:         } else {
 2253:             $returnhash{$key}=$username.':'.$domain;
 2254:         }
 2255:      }
 2256:     return %returnhash;
 2257: }
 2258: 
 2259: sub get_my_roles {
 2260:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2261:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2262:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2263:     my %dumphash;
 2264:     if ($context eq 'userroles') { 
 2265:         %dumphash = &dump('roles',$udom,$uname);
 2266:     } else {
 2267:         %dumphash=
 2268:             &dump('nohist_userroles',$udom,$uname);
 2269:     }
 2270:     my %returnhash=();
 2271:     my $now=time;
 2272:     foreach my $entry (keys(%dumphash)) {
 2273:         my ($role,$tend,$tstart);
 2274:         if ($context eq 'userroles') {
 2275: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2276:         } else {
 2277:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2278:         }
 2279:         if (($tstart) && ($tstart<0)) { next; }
 2280:         my $status = 'active';
 2281:         if (($tend) && ($tend<$now)) {
 2282:             $status = 'previous';
 2283:         } 
 2284:         if (($tstart) && ($now<$tstart)) {
 2285:             $status = 'future';
 2286:         }
 2287:         if (ref($types) eq 'ARRAY') {
 2288:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2289:                 next;
 2290:             } 
 2291:         } else {
 2292:             if ($status ne 'active') {
 2293:                 next;
 2294:             }
 2295:         }
 2296:         my ($rolecode,$username,$domain,$section,$area);
 2297:         if ($context eq 'userroles') {
 2298:             ($area,$rolecode) = split(/_/,$entry);
 2299:             (undef,$domain,$username,$section) = split(/\//,$area);
 2300:         } else {
 2301:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2302:         }
 2303:         if (ref($roledoms) eq 'ARRAY') {
 2304:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2305:                 next;
 2306:             }
 2307:         }
 2308:         if (ref($roles) eq 'ARRAY') {
 2309:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2310:                 next;
 2311:             }
 2312:         }
 2313: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2314:     }
 2315:     return %returnhash;
 2316: }
 2317: 
 2318: # ----------------------------------------------------- Frontpage Announcements
 2319: #
 2320: #
 2321: 
 2322: sub postannounce {
 2323:     my ($server,$text)=@_;
 2324:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2325:     unless ($text=~/\w/) { $text=''; }
 2326:     return &reply('setannounce:'.&escape($text),$server);
 2327: }
 2328: 
 2329: sub getannounce {
 2330: 
 2331:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2332: 	my $announcement='';
 2333: 	while (my $line = <$fh>) { $announcement .= $line; }
 2334: 	close($fh);
 2335: 	if ($announcement=~/\w/) { 
 2336: 	    return 
 2337:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2338:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2339: 	} else {
 2340: 	    return '';
 2341: 	}
 2342:     } else {
 2343: 	return '';
 2344:     }
 2345: }
 2346: 
 2347: # ---------------------------------------------------------- Course ID routines
 2348: # Deal with domain's nohist_courseid.db files
 2349: #
 2350: 
 2351: sub courseidput {
 2352:     my ($domain,$what,$coursehome)=@_;
 2353:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2354: }
 2355: 
 2356: sub courseiddump {
 2357:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2358:     my %returnhash=();
 2359:     unless ($domfilter) { $domfilter=''; }
 2360:     my %libserv = &all_library();
 2361:     foreach my $tryserver (keys(%libserv)) {
 2362:         if ( (  $hostidflag == 1 
 2363: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2364: 	     || (!defined($hostidflag)) ) {
 2365: 
 2366: 	    if ($domfilter eq ''
 2367: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2368: 	        foreach my $line (
 2369:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2370: 			       $sincefilter.':'.&escape($descfilter).':'.
 2371:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2372:                                $tryserver))) {
 2373: 		    my ($key,$value)=split(/\=/,$line,2);
 2374:                     if (($key) && ($value)) {
 2375: 		        $returnhash{&unescape($key)}=$value;
 2376:                     }
 2377:                 }
 2378:             }
 2379:         }
 2380:     }
 2381:     return %returnhash;
 2382: }
 2383: 
 2384: # ---------------------------------------------------------- DC e-mail
 2385: 
 2386: sub dcmailput {
 2387:     my ($domain,$msgid,$message,$server)=@_;
 2388:     my $status = &Apache::lonnet::critical(
 2389:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2390:        &escape($message),$server);
 2391:     return $status;
 2392: }
 2393: 
 2394: sub dcmaildump {
 2395:     my ($dom,$startdate,$enddate,$senders) = @_;
 2396:     my %returnhash=();
 2397: 
 2398:     if (defined(&domain($dom,'primary'))) {
 2399:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2400:                                                          &escape($enddate).':';
 2401: 	my @esc_senders=map { &escape($_)} @$senders;
 2402: 	$cmd.=&escape(join('&',@esc_senders));
 2403: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2404:             my ($key,$value) = split(/\=/,$line,2);
 2405:             if (($key) && ($value)) {
 2406:                 $returnhash{&unescape($key)} = &unescape($value);
 2407:             }
 2408:         }
 2409:     }
 2410:     return %returnhash;
 2411: }
 2412: # ---------------------------------------------------------- Domain roles
 2413: 
 2414: sub get_domain_roles {
 2415:     my ($dom,$roles,$startdate,$enddate)=@_;
 2416:     if (undef($startdate) || $startdate eq '') {
 2417:         $startdate = '.';
 2418:     }
 2419:     if (undef($enddate) || $enddate eq '') {
 2420:         $enddate = '.';
 2421:     }
 2422:     my $rolelist = join(':',@{$roles});
 2423:     my %personnel = ();
 2424: 
 2425:     my %servers = &get_servers($dom,'library');
 2426:     foreach my $tryserver (keys(%servers)) {
 2427: 	%{$personnel{$tryserver}}=();
 2428: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2429: 					    &escape($startdate).':'.
 2430: 					    &escape($enddate).':'.
 2431: 					    &escape($rolelist), $tryserver))) {
 2432: 	    my ($key,$value) = split(/\=/,$line,2);
 2433: 	    if (($key) && ($value)) {
 2434: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2435: 	    }
 2436: 	}
 2437:     }
 2438:     return %personnel;
 2439: }
 2440: 
 2441: # ----------------------------------------------------------- Check out an item
 2442: 
 2443: sub get_first_access {
 2444:     my ($type,$argsymb)=@_;
 2445:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2446:     if ($argsymb) { $symb=$argsymb; }
 2447:     my ($map,$id,$res)=&decode_symb($symb);
 2448:     if ($type eq 'map') {
 2449: 	$res=&symbread($map);
 2450:     } else {
 2451: 	$res=$symb;
 2452:     }
 2453:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2454:     return $times{"$courseid\0$res"};
 2455: }
 2456: 
 2457: sub set_first_access {
 2458:     my ($type)=@_;
 2459:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2460:     my ($map,$id,$res)=&decode_symb($symb);
 2461:     if ($type eq 'map') {
 2462: 	$res=&symbread($map);
 2463:     } else {
 2464: 	$res=$symb;
 2465:     }
 2466:     my $firstaccess=&get_first_access($type,$symb);
 2467:     if (!$firstaccess) {
 2468: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2469:     }
 2470:     return 'already_set';
 2471: }
 2472: 
 2473: sub checkout {
 2474:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2475:     my $now=time;
 2476:     my $lonhost=$perlvar{'lonHostID'};
 2477:     my $infostr=&escape(
 2478:                  'CHECKOUTTOKEN&'.
 2479:                  $tuname.'&'.
 2480:                  $tudom.'&'.
 2481:                  $tcrsid.'&'.
 2482:                  $symb.'&'.
 2483: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2484:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2485:     if ($token=~/^error\:/) { 
 2486:         &logthis("<font color=\"blue\">WARNING: ".
 2487:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2488:                  "</font>");
 2489:         return ''; 
 2490:     }
 2491: 
 2492:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2493:     $token=~tr/a-z/A-Z/;
 2494: 
 2495:     my %infohash=('resource.0.outtoken' => $token,
 2496:                   'resource.0.checkouttime' => $now,
 2497:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2498: 
 2499:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2500:        return '';
 2501:     } else {
 2502:         &logthis("<font color=\"blue\">WARNING: ".
 2503:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2504:                  "</font>");
 2505:     }    
 2506: 
 2507:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2508:                          &escape('Checkout '.$infostr.' - '.
 2509:                                                  $token)) ne 'ok') {
 2510: 	return '';
 2511:     } else {
 2512:         &logthis("<font color=\"blue\">WARNING: ".
 2513:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2514:                  "</font>");
 2515:     }
 2516:     return $token;
 2517: }
 2518: 
 2519: # ------------------------------------------------------------ Check in an item
 2520: 
 2521: sub checkin {
 2522:     my $token=shift;
 2523:     my $now=time;
 2524:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2525:     $lonhost=~tr/A-Z/a-z/;
 2526:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2527:     $dtoken=~s/\W/\_/g;
 2528:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2529:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2530: 
 2531:     unless (($tuname) && ($tudom)) {
 2532:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2533:         return '';
 2534:     }
 2535:     
 2536:     unless (&allowed('mgr',$tcrsid)) {
 2537:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2538:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2539:         return '';
 2540:     }
 2541: 
 2542:     my %infohash=('resource.0.intoken' => $token,
 2543:                   'resource.0.checkintime' => $now,
 2544:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2545: 
 2546:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2547:        return '';
 2548:     }    
 2549: 
 2550:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2551:                          &escape('Checkin - '.$token)) ne 'ok') {
 2552: 	return '';
 2553:     }
 2554: 
 2555:     return ($symb,$tuname,$tudom,$tcrsid);    
 2556: }
 2557: 
 2558: # --------------------------------------------- Set Expire Date for Spreadsheet
 2559: 
 2560: sub expirespread {
 2561:     my ($uname,$udom,$stype,$usymb)=@_;
 2562:     my $cid=$env{'request.course.id'}; 
 2563:     if ($cid) {
 2564:        my $now=time;
 2565:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2566:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2567:                             $env{'course.'.$cid.'.num'}.
 2568: 	        	    ':nohist_expirationdates:'.
 2569:                             &escape($key).'='.$now,
 2570:                             $env{'course.'.$cid.'.home'})
 2571:     }
 2572:     return 'ok';
 2573: }
 2574: 
 2575: # ----------------------------------------------------- Devalidate Spreadsheets
 2576: 
 2577: sub devalidate {
 2578:     my ($symb,$uname,$udom)=@_;
 2579:     my $cid=$env{'request.course.id'}; 
 2580:     if ($cid) {
 2581:         # delete the stored spreadsheets for
 2582:         # - the student level sheet of this user in course's homespace
 2583:         # - the assessment level sheet for this resource 
 2584:         #   for this user in user's homespace
 2585: 	# - current conditional state info
 2586: 	my $key=$uname.':'.$udom.':';
 2587:         my $status=
 2588: 	    &del('nohist_calculatedsheets',
 2589: 		 [$key.'studentcalc:'],
 2590: 		 $env{'course.'.$cid.'.domain'},
 2591: 		 $env{'course.'.$cid.'.num'})
 2592: 		.' '.
 2593: 	    &del('nohist_calculatedsheets_'.$cid,
 2594: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2595:         unless ($status eq 'ok ok') {
 2596:            &logthis('Could not devalidate spreadsheet '.
 2597:                     $uname.' at '.$udom.' for '.
 2598: 		    $symb.': '.$status);
 2599:         }
 2600: 	&delenv('user.state.'.$cid);
 2601:     }
 2602: }
 2603: 
 2604: sub get_scalar {
 2605:     my ($string,$end) = @_;
 2606:     my $value;
 2607:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2608: 	$value = $1;
 2609:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2610: 	$value = $1;
 2611:     }
 2612:     return &unescape($value);
 2613: }
 2614: 
 2615: sub array2str {
 2616:   my (@array) = @_;
 2617:   my $result=&arrayref2str(\@array);
 2618:   $result=~s/^__ARRAY_REF__//;
 2619:   $result=~s/__END_ARRAY_REF__$//;
 2620:   return $result;
 2621: }
 2622: 
 2623: sub arrayref2str {
 2624:   my ($arrayref) = @_;
 2625:   my $result='__ARRAY_REF__';
 2626:   foreach my $elem (@$arrayref) {
 2627:     if(ref($elem) eq 'ARRAY') {
 2628:       $result.=&arrayref2str($elem).'&';
 2629:     } elsif(ref($elem) eq 'HASH') {
 2630:       $result.=&hashref2str($elem).'&';
 2631:     } elsif(ref($elem)) {
 2632:       #print("Got a ref of ".(ref($elem))." skipping.");
 2633:     } else {
 2634:       $result.=&escape($elem).'&';
 2635:     }
 2636:   }
 2637:   $result=~s/\&$//;
 2638:   $result .= '__END_ARRAY_REF__';
 2639:   return $result;
 2640: }
 2641: 
 2642: sub hash2str {
 2643:   my (%hash) = @_;
 2644:   my $result=&hashref2str(\%hash);
 2645:   $result=~s/^__HASH_REF__//;
 2646:   $result=~s/__END_HASH_REF__$//;
 2647:   return $result;
 2648: }
 2649: 
 2650: sub hashref2str {
 2651:   my ($hashref)=@_;
 2652:   my $result='__HASH_REF__';
 2653:   foreach my $key (sort(keys(%$hashref))) {
 2654:     if (ref($key) eq 'ARRAY') {
 2655:       $result.=&arrayref2str($key).'=';
 2656:     } elsif (ref($key) eq 'HASH') {
 2657:       $result.=&hashref2str($key).'=';
 2658:     } elsif (ref($key)) {
 2659:       $result.='=';
 2660:       #print("Got a ref of ".(ref($key))." skipping.");
 2661:     } else {
 2662: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2663:     }
 2664: 
 2665:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2666:       $result.=&arrayref2str($hashref->{$key}).'&';
 2667:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2668:       $result.=&hashref2str($hashref->{$key}).'&';
 2669:     } elsif(ref($hashref->{$key})) {
 2670:        $result.='&';
 2671:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2672:     } else {
 2673:       $result.=&escape($hashref->{$key}).'&';
 2674:     }
 2675:   }
 2676:   $result=~s/\&$//;
 2677:   $result .= '__END_HASH_REF__';
 2678:   return $result;
 2679: }
 2680: 
 2681: sub str2hash {
 2682:     my ($string)=@_;
 2683:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2684:     return %$hash;
 2685: }
 2686: 
 2687: sub str2hashref {
 2688:   my ($string) = @_;
 2689: 
 2690:   my %hash;
 2691: 
 2692:   if($string !~ /^__HASH_REF__/) {
 2693:       if (! ($string eq '' || !defined($string))) {
 2694: 	  $hash{'error'}='Not hash reference';
 2695:       }
 2696:       return (\%hash, $string);
 2697:   }
 2698: 
 2699:   $string =~ s/^__HASH_REF__//;
 2700: 
 2701:   while($string !~ /^__END_HASH_REF__/) {
 2702:       #key
 2703:       my $key='';
 2704:       if($string =~ /^__HASH_REF__/) {
 2705:           ($key, $string)=&str2hashref($string);
 2706:           if(defined($key->{'error'})) {
 2707:               $hash{'error'}='Bad data';
 2708:               return (\%hash, $string);
 2709:           }
 2710:       } elsif($string =~ /^__ARRAY_REF__/) {
 2711:           ($key, $string)=&str2arrayref($string);
 2712:           if($key->[0] eq 'Array reference error') {
 2713:               $hash{'error'}='Bad data';
 2714:               return (\%hash, $string);
 2715:           }
 2716:       } else {
 2717:           $string =~ s/^(.*?)=//;
 2718: 	  $key=&unescape($1);
 2719:       }
 2720:       $string =~ s/^=//;
 2721: 
 2722:       #value
 2723:       my $value='';
 2724:       if($string =~ /^__HASH_REF__/) {
 2725:           ($value, $string)=&str2hashref($string);
 2726:           if(defined($value->{'error'})) {
 2727:               $hash{'error'}='Bad data';
 2728:               return (\%hash, $string);
 2729:           }
 2730:       } elsif($string =~ /^__ARRAY_REF__/) {
 2731:           ($value, $string)=&str2arrayref($string);
 2732:           if($value->[0] eq 'Array reference error') {
 2733:               $hash{'error'}='Bad data';
 2734:               return (\%hash, $string);
 2735:           }
 2736:       } else {
 2737: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2738:       }
 2739:       $string =~ s/^&//;
 2740: 
 2741:       $hash{$key}=$value;
 2742:   }
 2743: 
 2744:   $string =~ s/^__END_HASH_REF__//;
 2745: 
 2746:   return (\%hash, $string);
 2747: }
 2748: 
 2749: sub str2array {
 2750:     my ($string)=@_;
 2751:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2752:     return @$array;
 2753: }
 2754: 
 2755: sub str2arrayref {
 2756:   my ($string) = @_;
 2757:   my @array;
 2758: 
 2759:   if($string !~ /^__ARRAY_REF__/) {
 2760:       if (! ($string eq '' || !defined($string))) {
 2761: 	  $array[0]='Array reference error';
 2762:       }
 2763:       return (\@array, $string);
 2764:   }
 2765: 
 2766:   $string =~ s/^__ARRAY_REF__//;
 2767: 
 2768:   while($string !~ /^__END_ARRAY_REF__/) {
 2769:       my $value='';
 2770:       if($string =~ /^__HASH_REF__/) {
 2771:           ($value, $string)=&str2hashref($string);
 2772:           if(defined($value->{'error'})) {
 2773:               $array[0] ='Array reference error';
 2774:               return (\@array, $string);
 2775:           }
 2776:       } elsif($string =~ /^__ARRAY_REF__/) {
 2777:           ($value, $string)=&str2arrayref($string);
 2778:           if($value->[0] eq 'Array reference error') {
 2779:               $array[0] ='Array reference error';
 2780:               return (\@array, $string);
 2781:           }
 2782:       } else {
 2783: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2784:       }
 2785:       $string =~ s/^&//;
 2786: 
 2787:       push(@array, $value);
 2788:   }
 2789: 
 2790:   $string =~ s/^__END_ARRAY_REF__//;
 2791: 
 2792:   return (\@array, $string);
 2793: }
 2794: 
 2795: # -------------------------------------------------------------------Temp Store
 2796: 
 2797: sub tmpreset {
 2798:   my ($symb,$namespace,$domain,$stuname) = @_;
 2799:   if (!$symb) {
 2800:     $symb=&symbread();
 2801:     if (!$symb) { $symb= $env{'request.url'}; }
 2802:   }
 2803:   $symb=escape($symb);
 2804: 
 2805:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2806:   $namespace=~s/\//\_/g;
 2807:   $namespace=~s/\W//g;
 2808: 
 2809:   if (!$domain) { $domain=$env{'user.domain'}; }
 2810:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2811:   if ($domain eq 'public' && $stuname eq 'public') {
 2812:       $stuname=$ENV{'REMOTE_ADDR'};
 2813:   }
 2814:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2815:   my %hash;
 2816:   if (tie(%hash,'GDBM_File',
 2817: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2818: 	  &GDBM_WRCREAT(),0640)) {
 2819:     foreach my $key (keys %hash) {
 2820:       if ($key=~ /:$symb/) {
 2821: 	delete($hash{$key});
 2822:       }
 2823:     }
 2824:   }
 2825: }
 2826: 
 2827: sub tmpstore {
 2828:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2829: 
 2830:   if (!$symb) {
 2831:     $symb=&symbread();
 2832:     if (!$symb) { $symb= $env{'request.url'}; }
 2833:   }
 2834:   $symb=escape($symb);
 2835: 
 2836:   if (!$namespace) {
 2837:     # I don't think we would ever want to store this for a course.
 2838:     # it seems this will only be used if we don't have a course.
 2839:     #$namespace=$env{'request.course.id'};
 2840:     #if (!$namespace) {
 2841:       $namespace=$env{'request.state'};
 2842:     #}
 2843:   }
 2844:   $namespace=~s/\//\_/g;
 2845:   $namespace=~s/\W//g;
 2846:   if (!$domain) { $domain=$env{'user.domain'}; }
 2847:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2848:   if ($domain eq 'public' && $stuname eq 'public') {
 2849:       $stuname=$ENV{'REMOTE_ADDR'};
 2850:   }
 2851:   my $now=time;
 2852:   my %hash;
 2853:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2854:   if (tie(%hash,'GDBM_File',
 2855: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2856: 	  &GDBM_WRCREAT(),0640)) {
 2857:     $hash{"version:$symb"}++;
 2858:     my $version=$hash{"version:$symb"};
 2859:     my $allkeys=''; 
 2860:     foreach my $key (keys(%$storehash)) {
 2861:       $allkeys.=$key.':';
 2862:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2863:     }
 2864:     $hash{"$version:$symb:timestamp"}=$now;
 2865:     $allkeys.='timestamp';
 2866:     $hash{"$version:keys:$symb"}=$allkeys;
 2867:     if (untie(%hash)) {
 2868:       return 'ok';
 2869:     } else {
 2870:       return "error:$!";
 2871:     }
 2872:   } else {
 2873:     return "error:$!";
 2874:   }
 2875: }
 2876: 
 2877: # -----------------------------------------------------------------Temp Restore
 2878: 
 2879: sub tmprestore {
 2880:   my ($symb,$namespace,$domain,$stuname) = @_;
 2881: 
 2882:   if (!$symb) {
 2883:     $symb=&symbread();
 2884:     if (!$symb) { $symb= $env{'request.url'}; }
 2885:   }
 2886:   $symb=escape($symb);
 2887: 
 2888:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2889: 
 2890:   if (!$domain) { $domain=$env{'user.domain'}; }
 2891:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2892:   if ($domain eq 'public' && $stuname eq 'public') {
 2893:       $stuname=$ENV{'REMOTE_ADDR'};
 2894:   }
 2895:   my %returnhash;
 2896:   $namespace=~s/\//\_/g;
 2897:   $namespace=~s/\W//g;
 2898:   my %hash;
 2899:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2900:   if (tie(%hash,'GDBM_File',
 2901: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2902: 	  &GDBM_READER(),0640)) {
 2903:     my $version=$hash{"version:$symb"};
 2904:     $returnhash{'version'}=$version;
 2905:     my $scope;
 2906:     for ($scope=1;$scope<=$version;$scope++) {
 2907:       my $vkeys=$hash{"$scope:keys:$symb"};
 2908:       my @keys=split(/:/,$vkeys);
 2909:       my $key;
 2910:       $returnhash{"$scope:keys"}=$vkeys;
 2911:       foreach $key (@keys) {
 2912: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2913: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2914:       }
 2915:     }
 2916:     if (!(untie(%hash))) {
 2917:       return "error:$!";
 2918:     }
 2919:   } else {
 2920:     return "error:$!";
 2921:   }
 2922:   return %returnhash;
 2923: }
 2924: 
 2925: # ----------------------------------------------------------------------- Store
 2926: 
 2927: sub store {
 2928:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2929:     my $home='';
 2930: 
 2931:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2932: 
 2933:     $symb=&symbclean($symb);
 2934:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2935: 
 2936:     if (!$domain) { $domain=$env{'user.domain'}; }
 2937:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2938: 
 2939:     &devalidate($symb,$stuname,$domain);
 2940: 
 2941:     $symb=escape($symb);
 2942:     if (!$namespace) { 
 2943:        unless ($namespace=$env{'request.course.id'}) { 
 2944:           return ''; 
 2945:        } 
 2946:     }
 2947:     if (!$home) { $home=$env{'user.home'}; }
 2948: 
 2949:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2950:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2951: 
 2952:     my $namevalue='';
 2953:     foreach my $key (keys(%$storehash)) {
 2954:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2955:     }
 2956:     $namevalue=~s/\&$//;
 2957:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2958:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2959: }
 2960: 
 2961: # -------------------------------------------------------------- Critical Store
 2962: 
 2963: sub cstore {
 2964:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2965:     my $home='';
 2966: 
 2967:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2968: 
 2969:     $symb=&symbclean($symb);
 2970:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2971: 
 2972:     if (!$domain) { $domain=$env{'user.domain'}; }
 2973:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2974: 
 2975:     &devalidate($symb,$stuname,$domain);
 2976: 
 2977:     $symb=escape($symb);
 2978:     if (!$namespace) { 
 2979:        unless ($namespace=$env{'request.course.id'}) { 
 2980:           return ''; 
 2981:        } 
 2982:     }
 2983:     if (!$home) { $home=$env{'user.home'}; }
 2984: 
 2985:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2986:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2987: 
 2988:     my $namevalue='';
 2989:     foreach my $key (keys(%$storehash)) {
 2990:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2991:     }
 2992:     $namevalue=~s/\&$//;
 2993:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2994:     return critical
 2995:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2996: }
 2997: 
 2998: # --------------------------------------------------------------------- Restore
 2999: 
 3000: sub restore {
 3001:     my ($symb,$namespace,$domain,$stuname) = @_;
 3002:     my $home='';
 3003: 
 3004:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3005: 
 3006:     if (!$symb) {
 3007:       unless ($symb=escape(&symbread())) { return ''; }
 3008:     } else {
 3009:       $symb=&escape(&symbclean($symb));
 3010:     }
 3011:     if (!$namespace) { 
 3012:        unless ($namespace=$env{'request.course.id'}) { 
 3013:           return ''; 
 3014:        } 
 3015:     }
 3016:     if (!$domain) { $domain=$env{'user.domain'}; }
 3017:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3018:     if (!$home) { $home=$env{'user.home'}; }
 3019:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3020: 
 3021:     my %returnhash=();
 3022:     foreach my $line (split(/\&/,$answer)) {
 3023: 	my ($name,$value)=split(/\=/,$line);
 3024:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3025:     }
 3026:     my $version;
 3027:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3028:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3029:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3030:        }
 3031:     }
 3032:     return %returnhash;
 3033: }
 3034: 
 3035: # ---------------------------------------------------------- Course Description
 3036: 
 3037: sub coursedescription {
 3038:     my ($courseid,$args)=@_;
 3039:     $courseid=~s/^\///;
 3040:     $courseid=~s/\_/\//g;
 3041:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3042:     my $chome=&homeserver($cnum,$cdomain);
 3043:     my $normalid=$cdomain.'_'.$cnum;
 3044:     # need to always cache even if we get errors otherwise we keep 
 3045:     # trying and trying and trying to get the course description.
 3046:     my %envhash=();
 3047:     my %returnhash=();
 3048:     
 3049:     my $expiretime=600;
 3050:     if ($env{'request.course.id'} eq $normalid) {
 3051: 	$expiretime=120;
 3052:     }
 3053: 
 3054:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3055:     if (!$args->{'freshen_cache'}
 3056: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3057: 	foreach my $key (keys(%env)) {
 3058: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3059: 	    my ($setting) = $1;
 3060: 	    $returnhash{$setting} = $env{$key};
 3061: 	}
 3062: 	return %returnhash;
 3063:     }
 3064: 
 3065:     # get the data agin
 3066:     if (!$args->{'one_time'}) {
 3067: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3068:     }
 3069: 
 3070:     if ($chome ne 'no_host') {
 3071:        %returnhash=&dump('environment',$cdomain,$cnum);
 3072:        if (!exists($returnhash{'con_lost'})) {
 3073:            $returnhash{'home'}= $chome;
 3074: 	   $returnhash{'domain'} = $cdomain;
 3075: 	   $returnhash{'num'} = $cnum;
 3076:            if (!defined($returnhash{'type'})) {
 3077:                $returnhash{'type'} = 'Course';
 3078:            }
 3079:            while (my ($name,$value) = each %returnhash) {
 3080:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3081:            }
 3082:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3083:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3084: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3085:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3086:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3087:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3088:        }
 3089:     }
 3090:     if (!$args->{'one_time'}) {
 3091: 	&appenv(%envhash);
 3092:     }
 3093:     return %returnhash;
 3094: }
 3095: 
 3096: # -------------------------------------------------See if a user is privileged
 3097: 
 3098: sub privileged {
 3099:     my ($username,$domain)=@_;
 3100:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3101: 			&homeserver($username,$domain));
 3102:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3103:     my $now=time;
 3104:     if ($rolesdump ne '') {
 3105:         foreach my $entry (split(/&/,$rolesdump)) {
 3106: 	    if ($entry!~/^rolesdef_/) {
 3107: 		my ($area,$role)=split(/=/,$entry);
 3108: 		$area=~s/\_\w\w$//;
 3109: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3110: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3111: 		    my $active=1;
 3112: 		    if ($tend) {
 3113: 			if ($tend<$now) { $active=0; }
 3114: 		    }
 3115: 		    if ($tstart) {
 3116: 			if ($tstart>$now) { $active=0; }
 3117: 		    }
 3118: 		    if ($active) { return 1; }
 3119: 		}
 3120: 	    }
 3121: 	}
 3122:     }
 3123:     return 0;
 3124: }
 3125: 
 3126: # -------------------------------------------------------- Get user privileges
 3127: 
 3128: sub rolesinit {
 3129:     my ($domain,$username,$authhost)=@_;
 3130:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3131:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3132:     my %allroles=();
 3133:     my %allgroups=();   
 3134:     my $now=time;
 3135:     my %userroles = ('user.login.time' => $now);
 3136:     my $group_privs;
 3137: 
 3138:     if ($rolesdump ne '') {
 3139:         foreach my $entry (split(/&/,$rolesdump)) {
 3140: 	  if ($entry!~/^rolesdef_/) {
 3141:             my ($area,$role)=split(/=/,$entry);
 3142: 	    $area=~s/\_\w\w$//;
 3143:             my ($trole,$tend,$tstart,$group_privs);
 3144: 	    if ($role=~/^cr/) { 
 3145: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3146: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3147: 		    ($tend,$tstart)=split('_',$trest);
 3148: 		} else {
 3149: 		    $trole=$role;
 3150: 		}
 3151:             } elsif ($role =~ m|^gr/|) {
 3152:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3153:                 ($trole,$group_privs) = split(/\//,$trole);
 3154:                 $group_privs = &unescape($group_privs);
 3155: 	    } else {
 3156: 		($trole,$tend,$tstart)=split(/_/,$role);
 3157: 	    }
 3158: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3159: 					 $username);
 3160: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3161:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3162:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3163:             if (($area ne '') && ($trole ne '')) {
 3164: 		my $spec=$trole.'.'.$area;
 3165: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3166: 		if ($trole =~ /^cr\//) {
 3167:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3168:                 } elsif ($trole eq 'gr') {
 3169:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3170: 		} else {
 3171:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3172: 		}
 3173:             }
 3174:           }
 3175:         }
 3176:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3177:         $userroles{'user.adv'}    = $adv;
 3178: 	$userroles{'user.author'} = $author;
 3179:         $env{'user.adv'}=$adv;
 3180:     }
 3181:     return \%userroles;  
 3182: }
 3183: 
 3184: sub set_arearole {
 3185:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3186: # log the associated role with the area
 3187:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3188:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3189: }
 3190: 
 3191: sub custom_roleprivs {
 3192:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3193:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3194:     my $homsvr=homeserver($rauthor,$rdomain);
 3195:     if (&hostname($homsvr) ne '') {
 3196:         my ($rdummy,$roledef)=
 3197:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3198:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3199:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3200:             if (defined($syspriv)) {
 3201:                 $$allroles{'cm./'}.=':'.$syspriv;
 3202:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3203:             }
 3204:             if ($tdomain ne '') {
 3205:                 if (defined($dompriv)) {
 3206:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3207:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3208:                 }
 3209:                 if (($trest ne '') && (defined($coursepriv))) {
 3210:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3211:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3212:                 }
 3213:             }
 3214:         }
 3215:     }
 3216: }
 3217: 
 3218: sub group_roleprivs {
 3219:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3220:     my $access = 1;
 3221:     my $now = time;
 3222:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3223:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3224:     if ($access) {
 3225:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3226:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3227:     }
 3228: }
 3229: 
 3230: sub standard_roleprivs {
 3231:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3232:     if (defined($pr{$trole.':s'})) {
 3233:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3234:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3235:     }
 3236:     if ($tdomain ne '') {
 3237:         if (defined($pr{$trole.':d'})) {
 3238:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3239:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3240:         }
 3241:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3242:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3243:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3244:         }
 3245:     }
 3246: }
 3247: 
 3248: sub set_userprivs {
 3249:     my ($userroles,$allroles,$allgroups) = @_; 
 3250:     my $author=0;
 3251:     my $adv=0;
 3252:     my %grouproles = ();
 3253:     if (keys(%{$allgroups}) > 0) {
 3254:         foreach my $role (keys %{$allroles}) {
 3255:             my ($trole,$area,$sec,$extendedarea);
 3256:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3257:                 $trole = $1;
 3258:                 $area = $2;
 3259:                 $sec = $3;
 3260:                 $extendedarea = $area.$sec;
 3261:                 if (exists($$allgroups{$area})) {
 3262:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3263:                         my $spec = $trole.'.'.$extendedarea;
 3264:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3265:                                                 $$allgroups{$area}{$group};
 3266:                     }
 3267:                 }
 3268:             }
 3269:         }
 3270:     }
 3271:     foreach my $group (keys(%grouproles)) {
 3272:         $$allroles{$group} = $grouproles{$group};
 3273:     }
 3274:     foreach my $role (keys(%{$allroles})) {
 3275:         my %thesepriv;
 3276:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3277:         foreach my $item (split(/:/,$$allroles{$role})) {
 3278:             if ($item ne '') {
 3279:                 my ($privilege,$restrictions)=split(/&/,$item);
 3280:                 if ($restrictions eq '') {
 3281:                     $thesepriv{$privilege}='F';
 3282:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3283:                     $thesepriv{$privilege}.=$restrictions;
 3284:                 }
 3285:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3286:             }
 3287:         }
 3288:         my $thesestr='';
 3289:         foreach my $priv (keys(%thesepriv)) {
 3290: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3291: 	}
 3292:         $userroles->{'user.priv.'.$role} = $thesestr;
 3293:     }
 3294:     return ($author,$adv);
 3295: }
 3296: 
 3297: # --------------------------------------------------------------- get interface
 3298: 
 3299: sub get {
 3300:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3301:    my $items='';
 3302:    foreach my $item (@$storearr) {
 3303:        $items.=&escape($item).'&';
 3304:    }
 3305:    $items=~s/\&$//;
 3306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3307:    if (!$uname) { $uname=$env{'user.name'}; }
 3308:    my $uhome=&homeserver($uname,$udomain);
 3309: 
 3310:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3311:    my @pairs=split(/\&/,$rep);
 3312:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3313:      return @pairs;
 3314:    }
 3315:    my %returnhash=();
 3316:    my $i=0;
 3317:    foreach my $item (@$storearr) {
 3318:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3319:       $i++;
 3320:    }
 3321:    return %returnhash;
 3322: }
 3323: 
 3324: # --------------------------------------------------------------- del interface
 3325: 
 3326: sub del {
 3327:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3328:    my $items='';
 3329:    foreach my $item (@$storearr) {
 3330:        $items.=&escape($item).'&';
 3331:    }
 3332:    $items=~s/\&$//;
 3333:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3334:    if (!$uname) { $uname=$env{'user.name'}; }
 3335:    my $uhome=&homeserver($uname,$udomain);
 3336: 
 3337:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3338: }
 3339: 
 3340: # -------------------------------------------------------------- dump interface
 3341: 
 3342: sub dump {
 3343:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3344:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3345:     if (!$uname) { $uname=$env{'user.name'}; }
 3346:     my $uhome=&homeserver($uname,$udomain);
 3347:     if ($regexp) {
 3348: 	$regexp=&escape($regexp);
 3349:     } else {
 3350: 	$regexp='.';
 3351:     }
 3352:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3353:     my @pairs=split(/\&/,$rep);
 3354:     my %returnhash=();
 3355:     foreach my $item (@pairs) {
 3356: 	my ($key,$value)=split(/=/,$item,2);
 3357: 	$key = &unescape($key);
 3358: 	next if ($key =~ /^error: 2 /);
 3359: 	$returnhash{$key}=&thaw_unescape($value);
 3360:     }
 3361:     return %returnhash;
 3362: }
 3363: 
 3364: # --------------------------------------------------------- dumpstore interface
 3365: 
 3366: sub dumpstore {
 3367:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3368:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3369:    if (!$uname) { $uname=$env{'user.name'}; }
 3370:    my $uhome=&homeserver($uname,$udomain);
 3371:    if ($regexp) {
 3372:        $regexp=&escape($regexp);
 3373:    } else {
 3374:        $regexp='.';
 3375:    }
 3376:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3377:    my @pairs=split(/\&/,$rep);
 3378:    my %returnhash=();
 3379:    foreach my $item (@pairs) {
 3380:        my ($key,$value)=split(/=/,$item,2);
 3381:        next if ($key =~ /^error: 2 /);
 3382:        $returnhash{$key}=&thaw_unescape($value);
 3383:    }
 3384:    return %returnhash;
 3385: }
 3386: 
 3387: # -------------------------------------------------------------- keys interface
 3388: 
 3389: sub getkeys {
 3390:    my ($namespace,$udomain,$uname)=@_;
 3391:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3392:    if (!$uname) { $uname=$env{'user.name'}; }
 3393:    my $uhome=&homeserver($uname,$udomain);
 3394:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3395:    my @keyarray=();
 3396:    foreach my $key (split(/\&/,$rep)) {
 3397:       next if ($key =~ /^error: 2 /);
 3398:       push(@keyarray,&unescape($key));
 3399:    }
 3400:    return @keyarray;
 3401: }
 3402: 
 3403: # --------------------------------------------------------------- currentdump
 3404: sub currentdump {
 3405:    my ($courseid,$sdom,$sname)=@_;
 3406:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3407:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3408:    $sname    = $env{'user.name'}         if (! defined($sname));
 3409:    my $uhome = &homeserver($sname,$sdom);
 3410:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3411:    return if ($rep =~ /^(error:|no_such_host)/);
 3412:    #
 3413:    my %returnhash=();
 3414:    #
 3415:    if ($rep eq "unknown_cmd") { 
 3416:        # an old lond will not know currentdump
 3417:        # Do a dump and make it look like a currentdump
 3418:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3419:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3420:        my %hash = @tmp;
 3421:        @tmp=();
 3422:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3423:    } else {
 3424:        my @pairs=split(/\&/,$rep);
 3425:        foreach my $pair (@pairs) {
 3426:            my ($key,$value)=split(/=/,$pair,2);
 3427:            my ($symb,$param) = split(/:/,$key);
 3428:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3429:                                                         &thaw_unescape($value);
 3430:        }
 3431:    }
 3432:    return %returnhash;
 3433: }
 3434: 
 3435: sub convert_dump_to_currentdump{
 3436:     my %hash = %{shift()};
 3437:     my %returnhash;
 3438:     # Code ripped from lond, essentially.  The only difference
 3439:     # here is the unescaping done by lonnet::dump().  Conceivably
 3440:     # we might run in to problems with parameter names =~ /^v\./
 3441:     while (my ($key,$value) = each(%hash)) {
 3442:         my ($v,$symb,$param) = split(/:/,$key);
 3443: 	$symb  = &unescape($symb);
 3444: 	$param = &unescape($param);
 3445:         next if ($v eq 'version' || $symb eq 'keys');
 3446:         next if (exists($returnhash{$symb}) &&
 3447:                  exists($returnhash{$symb}->{$param}) &&
 3448:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3449:         $returnhash{$symb}->{$param}=$value;
 3450:         $returnhash{$symb}->{'v.'.$param}=$v;
 3451:     }
 3452:     #
 3453:     # Remove all of the keys in the hashes which keep track of
 3454:     # the version of the parameter.
 3455:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3456:         # use a foreach because we are going to delete from the hash.
 3457:         foreach my $key (keys(%$param_hash)) {
 3458:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3459:         }
 3460:     }
 3461:     return \%returnhash;
 3462: }
 3463: 
 3464: # ------------------------------------------------------ critical inc interface
 3465: 
 3466: sub cinc {
 3467:     return &inc(@_,'critical');
 3468: }
 3469: 
 3470: # --------------------------------------------------------------- inc interface
 3471: 
 3472: sub inc {
 3473:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3474:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3475:     if (!$uname) { $uname=$env{'user.name'}; }
 3476:     my $uhome=&homeserver($uname,$udomain);
 3477:     my $items='';
 3478:     if (! ref($store)) {
 3479:         # got a single value, so use that instead
 3480:         $items = &escape($store).'=&';
 3481:     } elsif (ref($store) eq 'SCALAR') {
 3482:         $items = &escape($$store).'=&';        
 3483:     } elsif (ref($store) eq 'ARRAY') {
 3484:         $items = join('=&',map {&escape($_);} @{$store});
 3485:     } elsif (ref($store) eq 'HASH') {
 3486:         while (my($key,$value) = each(%{$store})) {
 3487:             $items.= &escape($key).'='.&escape($value).'&';
 3488:         }
 3489:     }
 3490:     $items=~s/\&$//;
 3491:     if ($critical) {
 3492: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3493:     } else {
 3494: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3495:     }
 3496: }
 3497: 
 3498: # --------------------------------------------------------------- put interface
 3499: 
 3500: sub put {
 3501:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3502:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3503:    if (!$uname) { $uname=$env{'user.name'}; }
 3504:    my $uhome=&homeserver($uname,$udomain);
 3505:    my $items='';
 3506:    foreach my $item (keys(%$storehash)) {
 3507:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3508:    }
 3509:    $items=~s/\&$//;
 3510:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3511: }
 3512: 
 3513: # ------------------------------------------------------------ newput interface
 3514: 
 3515: sub newput {
 3516:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3517:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3518:    if (!$uname) { $uname=$env{'user.name'}; }
 3519:    my $uhome=&homeserver($uname,$udomain);
 3520:    my $items='';
 3521:    foreach my $key (keys(%$storehash)) {
 3522:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3523:    }
 3524:    $items=~s/\&$//;
 3525:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3526: }
 3527: 
 3528: # ---------------------------------------------------------  putstore interface
 3529: 
 3530: sub putstore {
 3531:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3532:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3533:    if (!$uname) { $uname=$env{'user.name'}; }
 3534:    my $uhome=&homeserver($uname,$udomain);
 3535:    my $items='';
 3536:    foreach my $key (keys(%$storehash)) {
 3537:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3538:    }
 3539:    $items=~s/\&$//;
 3540:    my $esc_symb=&escape($symb);
 3541:    my $esc_v=&escape($version);
 3542:    my $reply =
 3543:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3544: 	      $uhome);
 3545:    if ($reply eq 'unknown_cmd') {
 3546:        # gfall back to way things use to be done
 3547:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3548: 			    $uname);
 3549:    }
 3550:    return $reply;
 3551: }
 3552: 
 3553: sub old_putstore {
 3554:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3555:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3556:     if (!$uname) { $uname=$env{'user.name'}; }
 3557:     my $uhome=&homeserver($uname,$udomain);
 3558:     my %newstorehash;
 3559:     foreach my $item (keys(%$storehash)) {
 3560: 	my $key = $version.':'.&escape($symb).':'.$item;
 3561: 	$newstorehash{$key} = $storehash->{$item};
 3562:     }
 3563:     my $items='';
 3564:     my %allitems = ();
 3565:     foreach my $item (keys(%newstorehash)) {
 3566: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3567: 	    my $key = $1.':keys:'.$2;
 3568: 	    $allitems{$key} .= $3.':';
 3569: 	}
 3570: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3571:     }
 3572:     foreach my $item (keys(%allitems)) {
 3573: 	$allitems{$item} =~ s/\:$//;
 3574: 	$items.= $item.'='.$allitems{$item}.'&';
 3575:     }
 3576:     $items=~s/\&$//;
 3577:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3578: }
 3579: 
 3580: # ------------------------------------------------------ critical put interface
 3581: 
 3582: sub cput {
 3583:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3584:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3585:    if (!$uname) { $uname=$env{'user.name'}; }
 3586:    my $uhome=&homeserver($uname,$udomain);
 3587:    my $items='';
 3588:    foreach my $item (keys(%$storehash)) {
 3589:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3590:    }
 3591:    $items=~s/\&$//;
 3592:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3593: }
 3594: 
 3595: # -------------------------------------------------------------- eget interface
 3596: 
 3597: sub eget {
 3598:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3599:    my $items='';
 3600:    foreach my $item (@$storearr) {
 3601:        $items.=&escape($item).'&';
 3602:    }
 3603:    $items=~s/\&$//;
 3604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3605:    if (!$uname) { $uname=$env{'user.name'}; }
 3606:    my $uhome=&homeserver($uname,$udomain);
 3607:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3608:    my @pairs=split(/\&/,$rep);
 3609:    my %returnhash=();
 3610:    my $i=0;
 3611:    foreach my $item (@$storearr) {
 3612:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3613:       $i++;
 3614:    }
 3615:    return %returnhash;
 3616: }
 3617: 
 3618: # ------------------------------------------------------------ tmpput interface
 3619: sub tmpput {
 3620:     my ($storehash,$server,$context)=@_;
 3621:     my $items='';
 3622:     foreach my $item (keys(%$storehash)) {
 3623: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3624:     }
 3625:     $items=~s/\&$//;
 3626:     if (defined($context)) {
 3627:         $items .= ':'.&escape($context);
 3628:     }
 3629:     return &reply("tmpput:$items",$server);
 3630: }
 3631: 
 3632: # ------------------------------------------------------------ tmpget interface
 3633: sub tmpget {
 3634:     my ($token,$server)=@_;
 3635:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3636:     my $rep=&reply("tmpget:$token",$server);
 3637:     my %returnhash;
 3638:     foreach my $item (split(/\&/,$rep)) {
 3639: 	my ($key,$value)=split(/=/,$item);
 3640: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3641:     }
 3642:     return %returnhash;
 3643: }
 3644: 
 3645: # ------------------------------------------------------------ tmpget interface
 3646: sub tmpdel {
 3647:     my ($token,$server)=@_;
 3648:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3649:     return &reply("tmpdel:$token",$server);
 3650: }
 3651: 
 3652: # -------------------------------------------------- portfolio access checking
 3653: 
 3654: sub portfolio_access {
 3655:     my ($requrl) = @_;
 3656:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3657:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3658:     if ($result) {
 3659:         my %setters;
 3660:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3661:             my ($startblock,$endblock) =
 3662:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3663:             if ($startblock && $endblock) {
 3664:                 return 'B';
 3665:             }
 3666:         } else {
 3667:             my ($startblock,$endblock) =
 3668:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3669:             if ($startblock && $endblock) {
 3670:                 return 'B';
 3671:             }
 3672:         }
 3673:     }
 3674:     if ($result eq 'ok') {
 3675:        return 'F';
 3676:     } elsif ($result =~ /^[^:]+:guest_/) {
 3677:        return 'A';
 3678:     }
 3679:     return '';
 3680: }
 3681: 
 3682: sub get_portfolio_access {
 3683:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3684: 
 3685:     if (!ref($access_hash)) {
 3686: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3687: 	my %access_controls = &get_access_controls($current_perms,$group,
 3688: 						   $file_name);
 3689: 	$access_hash = $access_controls{$file_name};
 3690:     }
 3691: 
 3692:     my ($public,$guest,@domains,@users,@courses,@groups);
 3693:     my $now = time;
 3694:     if (ref($access_hash) eq 'HASH') {
 3695:         foreach my $key (keys(%{$access_hash})) {
 3696:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3697:             if ($start > $now) {
 3698:                 next;
 3699:             }
 3700:             if ($end && $end<$now) {
 3701:                 next;
 3702:             }
 3703:             if ($scope eq 'public') {
 3704:                 $public = $key;
 3705:                 last;
 3706:             } elsif ($scope eq 'guest') {
 3707:                 $guest = $key;
 3708:             } elsif ($scope eq 'domains') {
 3709:                 push(@domains,$key);
 3710:             } elsif ($scope eq 'users') {
 3711:                 push(@users,$key);
 3712:             } elsif ($scope eq 'course') {
 3713:                 push(@courses,$key);
 3714:             } elsif ($scope eq 'group') {
 3715:                 push(@groups,$key);
 3716:             }
 3717:         }
 3718:         if ($public) {
 3719:             return 'ok';
 3720:         }
 3721:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3722:             if ($guest) {
 3723:                 return $guest;
 3724:             }
 3725:         } else {
 3726:             if (@domains > 0) {
 3727:                 foreach my $domkey (@domains) {
 3728:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3729:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3730:                             return 'ok';
 3731:                         }
 3732:                     }
 3733:                 }
 3734:             }
 3735:             if (@users > 0) {
 3736:                 foreach my $userkey (@users) {
 3737:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3738:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3739:                             if (ref($item) eq 'HASH') {
 3740:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3741:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3742:                                     return 'ok';
 3743:                                 }
 3744:                             }
 3745:                         }
 3746:                     } 
 3747:                 }
 3748:             }
 3749:             my %roleshash;
 3750:             my @courses_and_groups = @courses;
 3751:             push(@courses_and_groups,@groups); 
 3752:             if (@courses_and_groups > 0) {
 3753:                 my (%allgroups,%allroles); 
 3754:                 my ($start,$end,$role,$sec,$group);
 3755:                 foreach my $envkey (%env) {
 3756:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3757:                         my $cid = $2.'_'.$3; 
 3758:                         if ($1 eq 'gr') {
 3759:                             $group = $4;
 3760:                             $allgroups{$cid}{$group} = $env{$envkey};
 3761:                         } else {
 3762:                             if ($4 eq '') {
 3763:                                 $sec = 'none';
 3764:                             } else {
 3765:                                 $sec = $4;
 3766:                             }
 3767:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3768:                         }
 3769:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3770:                         my $cid = $2.'_'.$3;
 3771:                         if ($4 eq '') {
 3772:                             $sec = 'none';
 3773:                         } else {
 3774:                             $sec = $4;
 3775:                         }
 3776:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3777:                     }
 3778:                 }
 3779:                 if (keys(%allroles) == 0) {
 3780:                     return;
 3781:                 }
 3782:                 foreach my $key (@courses_and_groups) {
 3783:                     my %content = %{$$access_hash{$key}};
 3784:                     my $cnum = $content{'number'};
 3785:                     my $cdom = $content{'domain'};
 3786:                     my $cid = $cdom.'_'.$cnum;
 3787:                     if (!exists($allroles{$cid})) {
 3788:                         next;
 3789:                     }    
 3790:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3791:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3792:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3793:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3794:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3795:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3796:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3797:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3798:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3799:                                         if (grep/^all$/,@sections) {
 3800:                                             return 'ok';
 3801:                                         } else {
 3802:                                             if (grep/^$sec$/,@sections) {
 3803:                                                 return 'ok';
 3804:                                             }
 3805:                                         }
 3806:                                     }
 3807:                                 }
 3808:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3809:                                     if (grep/^none$/,@groups) {
 3810:                                         return 'ok';
 3811:                                     }
 3812:                                 } else {
 3813:                                     if (grep/^all$/,@groups) {
 3814:                                         return 'ok';
 3815:                                     } 
 3816:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3817:                                         if (grep/^$group$/,@groups) {
 3818:                                             return 'ok';
 3819:                                         }
 3820:                                     }
 3821:                                 } 
 3822:                             }
 3823:                         }
 3824:                     }
 3825:                 }
 3826:             }
 3827:             if ($guest) {
 3828:                 return $guest;
 3829:             }
 3830:         }
 3831:     }
 3832:     return;
 3833: }
 3834: 
 3835: sub course_group_datechecker {
 3836:     my ($dates,$now,$status) = @_;
 3837:     my ($start,$end) = split(/\./,$dates);
 3838:     if (!$start && !$end) {
 3839:         return 'ok';
 3840:     }
 3841:     if (grep/^active$/,@{$status}) {
 3842:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3843:             return 'ok';
 3844:         }
 3845:     }
 3846:     if (grep/^previous$/,@{$status}) {
 3847:         if ($end > $now ) {
 3848:             return 'ok';
 3849:         }
 3850:     }
 3851:     if (grep/^future$/,@{$status}) {
 3852:         if ($start > $now) {
 3853:             return 'ok';
 3854:         }
 3855:     }
 3856:     return; 
 3857: }
 3858: 
 3859: sub parse_portfolio_url {
 3860:     my ($url) = @_;
 3861: 
 3862:     my ($type,$udom,$unum,$group,$file_name);
 3863:     
 3864:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3865: 	$type = 1;
 3866:         $udom = $1;
 3867:         $unum = $2;
 3868:         $file_name = $3;
 3869:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3870: 	$type = 2;
 3871:         $udom = $1;
 3872:         $unum = $2;
 3873:         $group = $3;
 3874:         $file_name = $3.'/'.$4;
 3875:     }
 3876:     if (wantarray) {
 3877: 	return ($type,$udom,$unum,$file_name,$group);
 3878:     }
 3879:     return $type;
 3880: }
 3881: 
 3882: sub is_portfolio_url {
 3883:     my ($url) = @_;
 3884:     return scalar(&parse_portfolio_url($url));
 3885: }
 3886: 
 3887: sub is_portfolio_file {
 3888:     my ($file) = @_;
 3889:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3890:         return 1;
 3891:     }
 3892:     return;
 3893: }
 3894: 
 3895: 
 3896: # ---------------------------------------------- Custom access rule evaluation
 3897: 
 3898: sub customaccess {
 3899:     my ($priv,$uri)=@_;
 3900:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3901:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3902:     $udom = &LONCAPA::clean_domain($udom);
 3903:     $ucrs = &LONCAPA::clean_username($ucrs);
 3904:     my $access=0;
 3905:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3906: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 3907: 	if ($type eq 'user') {
 3908: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3909: 		my ($tdom,$tuname)=split(m{/},$scope);
 3910: 		if ($tdom) {
 3911: 		    if ($tdom ne $env{'user.domain'}) { next; }
 3912: 		}
 3913: 		if ($tuname) {
 3914: 		    if ($tuname ne $env{'user.name'}) { next; }
 3915: 		}
 3916: 		$access=($effect eq 'allow');
 3917: 		last;
 3918: 	    }
 3919: 	} else {
 3920: 	    if ($role) {
 3921: 		if ($role ne $urole) { next; }
 3922: 	    }
 3923: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3924: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3925: 		if ($tdom) {
 3926: 		    if ($tdom ne $udom) { next; }
 3927: 		}
 3928: 		if ($tcrs) {
 3929: 		    if ($tcrs ne $ucrs) { next; }
 3930: 		}
 3931: 		if ($tsec) {
 3932: 		    if ($tsec ne $usec) { next; }
 3933: 		}
 3934: 		$access=($effect eq 'allow');
 3935: 		last;
 3936: 	    }
 3937: 	    if ($realm eq '' && $role eq '') {
 3938: 		$access=($effect eq 'allow');
 3939: 	    }
 3940: 	}
 3941:     }
 3942:     return $access;
 3943: }
 3944: 
 3945: # ------------------------------------------------- Check for a user privilege
 3946: 
 3947: sub allowed {
 3948:     my ($priv,$uri,$symb,$role)=@_;
 3949:     my $ver_orguri=$uri;
 3950:     $uri=&deversion($uri);
 3951:     my $orguri=$uri;
 3952:     $uri=&declutter($uri);
 3953: 
 3954:     if ($priv eq 'evb') {
 3955: # Evade communication block restrictions for specified role in a course
 3956:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3957:             return $1;
 3958:         } else {
 3959:             return;
 3960:         }
 3961:     }
 3962: 
 3963:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3964: # Free bre access to adm and meta resources
 3965:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3966: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3967: 	&& ($priv eq 'bre')) {
 3968: 	return 'F';
 3969:     }
 3970: 
 3971: # Free bre access to user's own portfolio contents
 3972:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3973:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3974: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3975:         my %setters;
 3976:         my ($startblock,$endblock) = 
 3977:             &Apache::loncommon::blockcheck(\%setters,'port');
 3978:         if ($startblock && $endblock) {
 3979:             return 'B';
 3980:         } else {
 3981:             return 'F';
 3982:         }
 3983:     }
 3984: 
 3985: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3986:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3987:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3988:         if (exists($env{'request.course.id'})) {
 3989:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3990:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3991:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3992:                 my $courseprivid=$env{'request.course.id'};
 3993:                 $courseprivid=~s/\_/\//;
 3994:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3995:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3996:                     return $1; 
 3997:                 } else {
 3998:                     if ($env{'request.course.sec'}) {
 3999:                         $courseprivid.='/'.$env{'request.course.sec'};
 4000:                     }
 4001:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4002:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4003:                         return $2;
 4004:                     }
 4005:                 }
 4006:             }
 4007:         }
 4008:     }
 4009: 
 4010: # Free bre to public access
 4011: 
 4012:     if ($priv eq 'bre') {
 4013:         my $copyright=&metadata($uri,'copyright');
 4014: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4015:            return 'F'; 
 4016:         }
 4017:         if ($copyright eq 'priv') {
 4018:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4019: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4020: 		return '';
 4021:             }
 4022:         }
 4023:         if ($copyright eq 'domain') {
 4024:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4025: 	    unless (($env{'user.domain'} eq $1) ||
 4026:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4027: 		return '';
 4028:             }
 4029:         }
 4030:         if ($env{'request.role'}=~ /li\.\//) {
 4031:             # Library role, so allow browsing of resources in this domain.
 4032:             return 'F';
 4033:         }
 4034:         if ($copyright eq 'custom') {
 4035: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4036:         }
 4037:     }
 4038:     # Domain coordinator is trying to create a course
 4039:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4040:         # uri is the requested domain in this case.
 4041:         # comparison to 'request.role.domain' shows if the user has selected
 4042:         # a role of dc for the domain in question.
 4043:         return 'F' if ($uri eq $env{'request.role.domain'});
 4044:     }
 4045: 
 4046:     my $thisallowed='';
 4047:     my $statecond=0;
 4048:     my $courseprivid='';
 4049: 
 4050: # Course
 4051: 
 4052:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4053:        $thisallowed.=$1;
 4054:     }
 4055: 
 4056: # Domain
 4057: 
 4058:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4059:        =~/\Q$priv\E\&([^\:]*)/) {
 4060:        $thisallowed.=$1;
 4061:     }
 4062: 
 4063: # Course: uri itself is a course
 4064:     my $courseuri=$uri;
 4065:     $courseuri=~s/\_(\d)/\/$1/;
 4066:     $courseuri=~s/^([^\/])/\/$1/;
 4067: 
 4068:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4069:        =~/\Q$priv\E\&([^\:]*)/) {
 4070:        $thisallowed.=$1;
 4071:     }
 4072: 
 4073: # URI is an uploaded document for this course, default permissions don't matter
 4074: # not allowing 'edit' access (editupload) to uploaded course docs
 4075:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4076: 	$thisallowed='';
 4077:         my ($match)=&is_on_map($uri);
 4078:         if ($match) {
 4079:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4080:                   =~/\Q$priv\E\&([^\:]*)/) {
 4081:                 $thisallowed.=$1;
 4082:             }
 4083:         } else {
 4084:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4085:             if ($refuri) {
 4086:                 if ($refuri =~ m|^/adm/|) {
 4087:                     $thisallowed='F';
 4088:                 } else {
 4089:                     $refuri=&declutter($refuri);
 4090:                     my ($match) = &is_on_map($refuri);
 4091:                     if ($match) {
 4092:                         $thisallowed='F';
 4093:                     }
 4094:                 }
 4095:             }
 4096:         }
 4097:     }
 4098: 
 4099:     if ($priv eq 'bre'
 4100: 	&& $thisallowed ne 'F' 
 4101: 	&& $thisallowed ne '2'
 4102: 	&& &is_portfolio_url($uri)) {
 4103: 	$thisallowed = &portfolio_access($uri);
 4104:     }
 4105:     
 4106: # Full access at system, domain or course-wide level? Exit.
 4107: 
 4108:     if ($thisallowed=~/F/) {
 4109: 	return 'F';
 4110:     }
 4111: 
 4112: # If this is generating or modifying users, exit with special codes
 4113: 
 4114:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4115: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4116: 	    my ($audom,$auname)=split('/',$uri);
 4117: # no author name given, so this just checks on the general right to make a co-author in this domain
 4118: 	    unless ($auname) { return $thisallowed; }
 4119: # an author name is given, so we are about to actually make a co-author for a certain account
 4120: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4121: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4122: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4123: 	}
 4124: 	return $thisallowed;
 4125:     }
 4126: #
 4127: # Gathered so far: system, domain and course wide privileges
 4128: #
 4129: # Course: See if uri or referer is an individual resource that is part of 
 4130: # the course
 4131: 
 4132:     if ($env{'request.course.id'}) {
 4133: 
 4134:        $courseprivid=$env{'request.course.id'};
 4135:        if ($env{'request.course.sec'}) {
 4136:           $courseprivid.='/'.$env{'request.course.sec'};
 4137:        }
 4138:        $courseprivid=~s/\_/\//;
 4139:        my $checkreferer=1;
 4140:        my ($match,$cond)=&is_on_map($uri);
 4141:        if ($match) {
 4142:            $statecond=$cond;
 4143:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4144:                =~/\Q$priv\E\&([^\:]*)/) {
 4145:                $thisallowed.=$1;
 4146:                $checkreferer=0;
 4147:            }
 4148:        }
 4149:        
 4150:        if ($checkreferer) {
 4151: 	  my $refuri=$env{'httpref.'.$orguri};
 4152:             unless ($refuri) {
 4153:                 foreach my $key (keys(%env)) {
 4154: 		    if ($key=~/^httpref\..*\*/) {
 4155: 			my $pattern=$key;
 4156:                         $pattern=~s/^httpref\.\/res\///;
 4157:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4158:                         $pattern=~s/\//\\\//g;
 4159:                         if ($orguri=~/$pattern/) {
 4160: 			    $refuri=$env{$key};
 4161:                         }
 4162:                     }
 4163:                 }
 4164:             }
 4165: 
 4166:          if ($refuri) { 
 4167: 	  $refuri=&declutter($refuri);
 4168:           my ($match,$cond)=&is_on_map($refuri);
 4169:             if ($match) {
 4170:               my $refstatecond=$cond;
 4171:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4172:                   =~/\Q$priv\E\&([^\:]*)/) {
 4173:                   $thisallowed.=$1;
 4174:                   $uri=$refuri;
 4175:                   $statecond=$refstatecond;
 4176:               }
 4177:           }
 4178:         }
 4179:        }
 4180:    }
 4181: 
 4182: #
 4183: # Gathered now: all privileges that could apply, and condition number
 4184: # 
 4185: #
 4186: # Full or no access?
 4187: #
 4188: 
 4189:     if ($thisallowed=~/F/) {
 4190: 	return 'F';
 4191:     }
 4192: 
 4193:     unless ($thisallowed) {
 4194:         return '';
 4195:     }
 4196: 
 4197: # Restrictions exist, deal with them
 4198: #
 4199: #   C:according to course preferences
 4200: #   R:according to resource settings
 4201: #   L:unless locked
 4202: #   X:according to user session state
 4203: #
 4204: 
 4205: # Possibly locked functionality, check all courses
 4206: # Locks might take effect only after 10 minutes cache expiration for other
 4207: # courses, and 2 minutes for current course
 4208: 
 4209:     my $envkey;
 4210:     if ($thisallowed=~/L/) {
 4211:         foreach $envkey (keys %env) {
 4212:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4213:                my $courseid=$2;
 4214:                my $roleid=$1.'.'.$2;
 4215:                $courseid=~s/^\///;
 4216:                my $expiretime=600;
 4217:                if ($env{'request.role'} eq $roleid) {
 4218: 		  $expiretime=120;
 4219:                }
 4220: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4221:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4222:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4223: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4224:                }
 4225:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4226:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4227: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4228:                        &log($env{'user.domain'},$env{'user.name'},
 4229:                             $env{'user.home'},
 4230:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4231:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4232:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4233: 		       return '';
 4234:                    }
 4235:                }
 4236:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4237:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4238: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4239:                        &log($env{'user.domain'},$env{'user.name'},
 4240:                             $env{'user.home'},
 4241:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4242:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4243:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4244: 		       return '';
 4245:                    }
 4246:                }
 4247: 	   }
 4248:        }
 4249:     }
 4250:    
 4251: #
 4252: # Rest of the restrictions depend on selected course
 4253: #
 4254: 
 4255:     unless ($env{'request.course.id'}) {
 4256: 	if ($thisallowed eq 'A') {
 4257: 	    return 'A';
 4258:         } elsif ($thisallowed eq 'B') {
 4259:             return 'B';
 4260: 	} else {
 4261: 	    return '1';
 4262: 	}
 4263:     }
 4264: 
 4265: #
 4266: # Now user is definitely in a course
 4267: #
 4268: 
 4269: 
 4270: # Course preferences
 4271: 
 4272:    if ($thisallowed=~/C/) {
 4273:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4274:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4275:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4276: 	   =~/\Q$rolecode\E/) {
 4277: 	   if ($priv ne 'pch') { 
 4278: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4279: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4280: 			$env{'request.course.id'});
 4281: 	   }
 4282:            return '';
 4283:        }
 4284: 
 4285:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4286: 	   =~/\Q$unamedom\E/) {
 4287: 	   if ($priv ne 'pch') { 
 4288: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4289: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4290: 			$env{'request.course.id'});
 4291: 	   }
 4292:            return '';
 4293:        }
 4294:    }
 4295: 
 4296: # Resource preferences
 4297: 
 4298:    if ($thisallowed=~/R/) {
 4299:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4300:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4301: 	   if ($priv ne 'pch') { 
 4302: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4303: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4304: 	   }
 4305: 	   return '';
 4306:        }
 4307:    }
 4308: 
 4309: # Restricted by state or randomout?
 4310: 
 4311:    if ($thisallowed=~/X/) {
 4312:       if ($env{'acc.randomout'}) {
 4313: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4314:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4315:             return ''; 
 4316:          }
 4317:       }
 4318:       if (&condval($statecond)) {
 4319: 	 return '2';
 4320:       } else {
 4321:          return '';
 4322:       }
 4323:    }
 4324: 
 4325:     if ($thisallowed eq 'A') {
 4326: 	return 'A';
 4327:     } elsif ($thisallowed eq 'B') {
 4328:         return 'B';
 4329:     }
 4330:    return 'F';
 4331: }
 4332: 
 4333: sub split_uri_for_cond {
 4334:     my $uri=&deversion(&declutter(shift));
 4335:     my @uriparts=split(/\//,$uri);
 4336:     my $filename=pop(@uriparts);
 4337:     my $pathname=join('/',@uriparts);
 4338:     return ($pathname,$filename);
 4339: }
 4340: # --------------------------------------------------- Is a resource on the map?
 4341: 
 4342: sub is_on_map {
 4343:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4344:     #Trying to find the conditional for the file
 4345:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4346: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4347:     if ($match) {
 4348: 	return (1,$1);
 4349:     } else {
 4350: 	return (0,0);
 4351:     }
 4352: }
 4353: 
 4354: # --------------------------------------------------------- Get symb from alias
 4355: 
 4356: sub get_symb_from_alias {
 4357:     my $symb=shift;
 4358:     my ($map,$resid,$url)=&decode_symb($symb);
 4359: # Already is a symb
 4360:     if ($url) { return $symb; }
 4361: # Must be an alias
 4362:     my $aliassymb='';
 4363:     my %bighash;
 4364:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4365:                             &GDBM_READER(),0640)) {
 4366:         my $rid=$bighash{'mapalias_'.$symb};
 4367: 	if ($rid) {
 4368: 	    my ($mapid,$resid)=split(/\./,$rid);
 4369: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4370: 				    $resid,$bighash{'src_'.$rid});
 4371: 	}
 4372:         untie %bighash;
 4373:     }
 4374:     return $aliassymb;
 4375: }
 4376: 
 4377: # ----------------------------------------------------------------- Define Role
 4378: 
 4379: sub definerole {
 4380:   if (allowed('mcr','/')) {
 4381:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4382:     foreach my $role (split(':',$sysrole)) {
 4383: 	my ($crole,$cqual)=split(/\&/,$role);
 4384:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4385:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4386: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4387:                return "refused:s:$crole&$cqual"; 
 4388:             }
 4389:         }
 4390:     }
 4391:     foreach my $role (split(':',$domrole)) {
 4392: 	my ($crole,$cqual)=split(/\&/,$role);
 4393:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4394:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4395: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4396:                return "refused:d:$crole&$cqual"; 
 4397:             }
 4398:         }
 4399:     }
 4400:     foreach my $role (split(':',$courole)) {
 4401: 	my ($crole,$cqual)=split(/\&/,$role);
 4402:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4403:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4404: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4405:                return "refused:c:$crole&$cqual"; 
 4406:             }
 4407:         }
 4408:     }
 4409:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4410:                 "$env{'user.domain'}:$env{'user.name'}:".
 4411: 	        "rolesdef_$rolename=".
 4412:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4413:     return reply($command,$env{'user.home'});
 4414:   } else {
 4415:     return 'refused';
 4416:   }
 4417: }
 4418: 
 4419: # ---------------- Make a metadata query against the network of library servers
 4420: 
 4421: sub metadata_query {
 4422:     my ($query,$custom,$customshow,$server_array)=@_;
 4423:     my %rhash;
 4424:     my %libserv = &all_library();
 4425:     my @server_list = (defined($server_array) ? @$server_array
 4426:                                               : keys(%libserv) );
 4427:     for my $server (@server_list) {
 4428: 	unless ($custom or $customshow) {
 4429: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4430: 	    $rhash{$server}=$reply;
 4431: 	}
 4432: 	else {
 4433: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4434: 			     &escape($custom).':'.&escape($customshow),
 4435: 			     $server);
 4436: 	    $rhash{$server}=$reply;
 4437: 	}
 4438:     }
 4439:     return \%rhash;
 4440: }
 4441: 
 4442: # ----------------------------------------- Send log queries and wait for reply
 4443: 
 4444: sub log_query {
 4445:     my ($uname,$udom,$query,%filters)=@_;
 4446:     my $uhome=&homeserver($uname,$udom);
 4447:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4448:     my $uhost=&hostname($uhome);
 4449:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4450:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4451:                        $uhome);
 4452:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4453:     return get_query_reply($queryid);
 4454: }
 4455: 
 4456: # -------------------------- Update MySQL table for portfolio file
 4457: 
 4458: sub update_portfolio_table {
 4459:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4460:     my $homeserver = &homeserver($uname,$udom);
 4461:     my $queryid=
 4462:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4463:                ':'.&escape($file_name).':'.$action,$homeserver);
 4464:     my $reply = &get_query_reply($queryid);
 4465:     return $reply;
 4466: }
 4467: 
 4468: # -------------------------- Update MySQL allusers table
 4469: 
 4470: sub update_allusers_table {
 4471:     my ($uname,$udom,$names) = @_;
 4472:     my $homeserver = &homeserver($uname,$udom);
 4473:     my $queryid=
 4474:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4475:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4476:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4477:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4478:                'generation='.&escape($names->{'generation'}).'%%'.
 4479:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4480:                'id='.&escape($names->{'id'}),$homeserver);
 4481:     my $reply = &get_query_reply($queryid);
 4482:     return $reply;
 4483: }
 4484: 
 4485: # ------- Request retrieval of institutional classlists for course(s)
 4486: 
 4487: sub fetch_enrollment_query {
 4488:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4489:     my $homeserver;
 4490:     my $maxtries = 1;
 4491:     if ($context eq 'automated') {
 4492:         $homeserver = $perlvar{'lonHostID'};
 4493:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4494:     } else {
 4495:         $homeserver = &homeserver($cnum,$dom);
 4496:     }
 4497:     my $host=&hostname($homeserver);
 4498:     my $cmd = '';
 4499:     foreach my $affiliate (keys %{$affiliatesref}) {
 4500:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4501:     }
 4502:     $cmd =~ s/%%$//;
 4503:     $cmd = &escape($cmd);
 4504:     my $query = 'fetchenrollment';
 4505:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4506:     unless ($queryid=~/^\Q$host\E\_/) { 
 4507:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4508:         return 'error: '.$queryid;
 4509:     }
 4510:     my $reply = &get_query_reply($queryid);
 4511:     my $tries = 1;
 4512:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4513:         $reply = &get_query_reply($queryid);
 4514:         $tries ++;
 4515:     }
 4516:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4517:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4518:     } else {
 4519:         my @responses = split(/:/,$reply);
 4520:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4521:             foreach my $line (@responses) {
 4522:                 my ($key,$value) = split(/=/,$line,2);
 4523:                 $$replyref{$key} = $value;
 4524:             }
 4525:         } else {
 4526:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4527:             foreach my $line (@responses) {
 4528:                 my ($key,$value) = split(/=/,$line);
 4529:                 $$replyref{$key} = $value;
 4530:                 if ($value > 0) {
 4531:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4532:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4533:                         my $destname = $pathname.'/'.$filename;
 4534:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4535:                         if ($xml_classlist =~ /^error/) {
 4536:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4537:                         } else {
 4538:                             if ( open(FILE,">$destname") ) {
 4539:                                 print FILE &unescape($xml_classlist);
 4540:                                 close(FILE);
 4541:                             } else {
 4542:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4543:                             }
 4544:                         }
 4545:                     }
 4546:                 }
 4547:             }
 4548:         }
 4549:         return 'ok';
 4550:     }
 4551:     return 'error';
 4552: }
 4553: 
 4554: sub get_query_reply {
 4555:     my $queryid=shift;
 4556:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4557:     my $reply='';
 4558:     for (1..100) {
 4559: 	sleep 2;
 4560:         if (-e $replyfile.'.end') {
 4561: 	    if (open(my $fh,$replyfile)) {
 4562: 		$reply = join('',<$fh>);
 4563: 		close($fh);
 4564: 	   } else { return 'error: reply_file_error'; }
 4565:            return &unescape($reply);
 4566: 	}
 4567:     }
 4568:     return 'timeout:'.$queryid;
 4569: }
 4570: 
 4571: sub courselog_query {
 4572: #
 4573: # possible filters:
 4574: # url: url or symb
 4575: # username
 4576: # domain
 4577: # action: view, submit, grade
 4578: # start: timestamp
 4579: # end: timestamp
 4580: #
 4581:     my (%filters)=@_;
 4582:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4583:     if ($filters{'url'}) {
 4584: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4585:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4586:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4587:     }
 4588:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4589:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4590:     return &log_query($cname,$cdom,'courselog',%filters);
 4591: }
 4592: 
 4593: sub userlog_query {
 4594: #
 4595: # possible filters:
 4596: # action: log check role
 4597: # start: timestamp
 4598: # end: timestamp
 4599: #
 4600:     my ($uname,$udom,%filters)=@_;
 4601:     return &log_query($uname,$udom,'userlog',%filters);
 4602: }
 4603: 
 4604: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4605: 
 4606: sub auto_run {
 4607:     my ($cnum,$cdom) = @_;
 4608:     my $response = 0;
 4609:     my $settings;
 4610:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4611:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4612:         $settings = $domconfig{'autoenroll'};
 4613:         if ($settings->{'run'} eq '1') {
 4614:             $response = 1;
 4615:         }
 4616:     } else {
 4617:         my $homeserver = &homeserver($cnum,$cdom);
 4618:         $response = &reply('autorun:'.$cdom,$homeserver);
 4619:     }
 4620:     return $response;
 4621: }
 4622: 
 4623: sub auto_get_sections {
 4624:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4625:     my $homeserver = &homeserver($cnum,$cdom);
 4626:     my @secs = ();
 4627:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4628:     unless ($response eq 'refused') {
 4629:         @secs = split(/:/,$response);
 4630:     }
 4631:     return @secs;
 4632: }
 4633: 
 4634: sub auto_new_course {
 4635:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4636:     my $homeserver = &homeserver($cnum,$cdom);
 4637:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4638:     return $response;
 4639: }
 4640: 
 4641: sub auto_validate_courseID {
 4642:     my ($cnum,$cdom,$inst_course_id) = @_;
 4643:     my $homeserver = &homeserver($cnum,$cdom);
 4644:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4645:     return $response;
 4646: }
 4647: 
 4648: sub auto_create_password {
 4649:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4650:     my ($homeserver,$response);
 4651:     my $create_passwd = 0;
 4652:     my $authchk = '';
 4653:     if ($udom =~ /^$match_domain$/) {
 4654:         $homeserver = &domain($udom,'primary');
 4655:     }
 4656:     if ($homeserver eq '') {
 4657:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4658:             $homeserver = &homeserver($cnum,$cdom);
 4659:         }
 4660:     }
 4661:     if ($homeserver eq '') {
 4662:         $authchk = 'nodomain';
 4663:     } else {
 4664:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4665:         if ($response eq 'refused') {
 4666:             $authchk = 'refused';
 4667:         } else {
 4668:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 4669:         }
 4670:     }
 4671:     return ($authparam,$create_passwd,$authchk);
 4672: }
 4673: 
 4674: sub auto_photo_permission {
 4675:     my ($cnum,$cdom,$students) = @_;
 4676:     my $homeserver = &homeserver($cnum,$cdom);
 4677:     my ($outcome,$perm_reqd,$conditions) = 
 4678: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4679:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4680: 	return (undef,undef);
 4681:     }
 4682:     return ($outcome,$perm_reqd,$conditions);
 4683: }
 4684: 
 4685: sub auto_checkphotos {
 4686:     my ($uname,$udom,$pid) = @_;
 4687:     my $homeserver = &homeserver($uname,$udom);
 4688:     my ($result,$resulttype);
 4689:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4690: 				   &escape($uname).':'.&escape($pid),
 4691: 				   $homeserver));
 4692:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4693: 	return (undef,undef);
 4694:     }
 4695:     if ($outcome) {
 4696:         ($result,$resulttype) = split(/:/,$outcome);
 4697:     } 
 4698:     return ($result,$resulttype);
 4699: }
 4700: 
 4701: sub auto_photochoice {
 4702:     my ($cnum,$cdom) = @_;
 4703:     my $homeserver = &homeserver($cnum,$cdom);
 4704:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4705: 						       &escape($cdom),
 4706: 						       $homeserver)));
 4707:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4708: 	return (undef,undef);
 4709:     }
 4710:     return ($update,$comment);
 4711: }
 4712: 
 4713: sub auto_photoupdate {
 4714:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4715:     my $homeserver = &homeserver($cnum,$dom);
 4716:     my $host=&hostname($homeserver);
 4717:     my $cmd = '';
 4718:     my $maxtries = 1;
 4719:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4720:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4721:     }
 4722:     $cmd =~ s/%%$//;
 4723:     $cmd = &escape($cmd);
 4724:     my $query = 'institutionalphotos';
 4725:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4726:     unless ($queryid=~/^\Q$host\E\_/) {
 4727:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4728:         return 'error: '.$queryid;
 4729:     }
 4730:     my $reply = &get_query_reply($queryid);
 4731:     my $tries = 1;
 4732:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4733:         $reply = &get_query_reply($queryid);
 4734:         $tries ++;
 4735:     }
 4736:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4737:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4738:     } else {
 4739:         my @responses = split(/:/,$reply);
 4740:         my $outcome = shift(@responses); 
 4741:         foreach my $item (@responses) {
 4742:             my ($key,$value) = split(/=/,$item);
 4743:             $$photo{$key} = $value;
 4744:         }
 4745:         return $outcome;
 4746:     }
 4747:     return 'error';
 4748: }
 4749: 
 4750: sub auto_instcode_format {
 4751:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4752: 	$cat_order) = @_;
 4753:     my $courses = '';
 4754:     my @homeservers;
 4755:     if ($caller eq 'global') {
 4756: 	my %servers = &get_servers($codedom,'library');
 4757: 	foreach my $tryserver (keys(%servers)) {
 4758: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4759: 		push(@homeservers,$tryserver);
 4760: 	    }
 4761:         }
 4762:     } else {
 4763:         push(@homeservers,&homeserver($caller,$codedom));
 4764:     }
 4765:     foreach my $code (keys(%{$instcodes})) {
 4766:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4767:     }
 4768:     chop($courses);
 4769:     my $ok_response = 0;
 4770:     my $response;
 4771:     while (@homeservers > 0 && $ok_response == 0) {
 4772:         my $server = shift(@homeservers); 
 4773:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4774:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4775:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4776: 		split(/:/,$response);
 4777:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4778:             push(@{$codetitles},&str2array($codetitles_str));
 4779:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4780:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4781:             $ok_response = 1;
 4782:         }
 4783:     }
 4784:     if ($ok_response) {
 4785:         return 'ok';
 4786:     } else {
 4787:         return $response;
 4788:     }
 4789: }
 4790: 
 4791: sub auto_instcode_defaults {
 4792:     my ($domain,$returnhash,$code_order) = @_;
 4793:     my @homeservers;
 4794: 
 4795:     my %servers = &get_servers($domain,'library');
 4796:     foreach my $tryserver (keys(%servers)) {
 4797: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4798: 	    push(@homeservers,$tryserver);
 4799: 	}
 4800:     }
 4801: 
 4802:     my $response;
 4803:     foreach my $server (@homeservers) {
 4804:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4805:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4806: 	
 4807: 	foreach my $pair (split(/\&/,$response)) {
 4808: 	    my ($name,$value)=split(/\=/,$pair);
 4809: 	    if ($name eq 'code_order') {
 4810: 		@{$code_order} = split(/\&/,&unescape($value));
 4811: 	    } else {
 4812: 		$returnhash->{&unescape($name)}=&unescape($value);
 4813: 	    }
 4814: 	}
 4815: 	return 'ok';
 4816:     }
 4817: 
 4818:     return $response;
 4819: } 
 4820: 
 4821: sub auto_validate_class_sec {
 4822:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4823:     my $homeserver = &homeserver($cnum,$cdom);
 4824:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4825:                         &escape($owner).':'.$cdom,$homeserver);
 4826:     return $response;
 4827: }
 4828: 
 4829: # ------------------------------------------------------- Course Group routines
 4830: 
 4831: sub get_coursegroups {
 4832:     my ($cdom,$cnum,$group,$namespace) = @_;
 4833:     return(&dump($namespace,$cdom,$cnum,$group));
 4834: }
 4835: 
 4836: sub modify_coursegroup {
 4837:     my ($cdom,$cnum,$groupsettings) = @_;
 4838:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4839: }
 4840: 
 4841: sub toggle_coursegroup_status {
 4842:     my ($cdom,$cnum,$group,$action) = @_;
 4843:     my ($from_namespace,$to_namespace);
 4844:     if ($action eq 'delete') {
 4845:         $from_namespace = 'coursegroups';
 4846:         $to_namespace = 'deleted_groups';
 4847:     } else {
 4848:         $from_namespace = 'deleted_groups';
 4849:         $to_namespace = 'coursegroups';
 4850:     }
 4851:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4852:     if (my $tmp = &error(%curr_group)) {
 4853:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4854:         return ('read error',$tmp);
 4855:     } else {
 4856:         my %savedsettings = %curr_group; 
 4857:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4858:         my $deloutcome;
 4859:         if ($result eq 'ok') {
 4860:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4861:         } else {
 4862:             return ('write error',$result);
 4863:         }
 4864:         if ($deloutcome eq 'ok') {
 4865:             return 'ok';
 4866:         } else {
 4867:             return ('delete error',$deloutcome);
 4868:         }
 4869:     }
 4870: }
 4871: 
 4872: sub modify_group_roles {
 4873:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4874:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4875:     my $role = 'gr/'.&escape($userprivs);
 4876:     my ($uname,$udom) = split(/:/,$user);
 4877:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4878:     if ($result eq 'ok') {
 4879:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4880:     }
 4881:     return $result;
 4882: }
 4883: 
 4884: sub modify_coursegroup_membership {
 4885:     my ($cdom,$cnum,$membership) = @_;
 4886:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4887:     return $result;
 4888: }
 4889: 
 4890: sub get_active_groups {
 4891:     my ($udom,$uname,$cdom,$cnum) = @_;
 4892:     my $now = time;
 4893:     my %groups = ();
 4894:     foreach my $key (keys(%env)) {
 4895:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4896:             my ($start,$end) = split(/\./,$env{$key});
 4897:             if (($end!=0) && ($end<$now)) { next; }
 4898:             if (($start!=0) && ($start>$now)) { next; }
 4899:             if ($1 eq $cdom && $2 eq $cnum) {
 4900:                 $groups{$3} = $env{$key} ;
 4901:             }
 4902:         }
 4903:     }
 4904:     return %groups;
 4905: }
 4906: 
 4907: sub get_group_membership {
 4908:     my ($cdom,$cnum,$group) = @_;
 4909:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4910: }
 4911: 
 4912: sub get_users_groups {
 4913:     my ($udom,$uname,$courseid) = @_;
 4914:     my @usersgroups;
 4915:     my $cachetime=1800;
 4916: 
 4917:     my $hashid="$udom:$uname:$courseid";
 4918:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4919:     if (defined($cached)) {
 4920:         @usersgroups = split(/:/,$grouplist);
 4921:     } else {  
 4922:         $grouplist = '';
 4923:         my $courseurl = &courseid_to_courseurl($courseid);
 4924:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4925:         my $access_end = $env{'course.'.$courseid.
 4926:                               '.default_enrollment_end_date'};
 4927:         my $now = time;
 4928:         foreach my $key (keys(%roleshash)) {
 4929:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4930:                 my $group = $1;
 4931:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4932:                     my $start = $2;
 4933:                     my $end = $1;
 4934:                     if ($start == -1) { next; } # deleted from group
 4935:                     if (($start!=0) && ($start>$now)) { next; }
 4936:                     if (($end!=0) && ($end<$now)) {
 4937:                         if ($access_end && $access_end < $now) {
 4938:                             if ($access_end - $end < 86400) {
 4939:                                 push(@usersgroups,$group);
 4940:                             }
 4941:                         }
 4942:                         next;
 4943:                     }
 4944:                     push(@usersgroups,$group);
 4945:                 }
 4946:             }
 4947:         }
 4948:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4949:         $grouplist = join(':',@usersgroups);
 4950:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4951:     }
 4952:     return @usersgroups;
 4953: }
 4954: 
 4955: sub devalidate_getgroups_cache {
 4956:     my ($udom,$uname,$cdom,$cnum)=@_;
 4957:     my $courseid = $cdom.'_'.$cnum;
 4958: 
 4959:     my $hashid="$udom:$uname:$courseid";
 4960:     &devalidate_cache_new('getgroups',$hashid);
 4961: }
 4962: 
 4963: # ------------------------------------------------------------------ Plain Text
 4964: 
 4965: sub plaintext {
 4966:     my ($short,$type,$cid) = @_;
 4967:     if ($short =~ /^cr/) {
 4968: 	return (split('/',$short))[-1];
 4969:     }
 4970:     if (!defined($cid)) {
 4971:         $cid = $env{'request.course.id'};
 4972:     }
 4973:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4974:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4975:                                           '.plaintext'});
 4976:     }
 4977:     my %rolenames = (
 4978:                       Course => 'std',
 4979:                       Group => 'alt1',
 4980:                     );
 4981:     if (defined($type) && 
 4982:          defined($rolenames{$type}) && 
 4983:          defined($prp{$short}{$rolenames{$type}})) {
 4984:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4985:     } else {
 4986:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4987:     }
 4988: }
 4989: 
 4990: # ----------------------------------------------------------------- Assign Role
 4991: 
 4992: sub assignrole {
 4993:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4994:     my $mrole;
 4995:     if ($role =~ /^cr\//) {
 4996:         my $cwosec=$url;
 4997:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4998: 	unless (&allowed('ccr',$cwosec)) {
 4999:            &logthis('Refused custom assignrole: '.
 5000:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5001: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5002:            return 'refused'; 
 5003:         }
 5004:         $mrole='cr';
 5005:     } elsif ($role =~ /^gr\//) {
 5006:         my $cwogrp=$url;
 5007:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5008:         unless (&allowed('mdg',$cwogrp)) {
 5009:             &logthis('Refused group assignrole: '.
 5010:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5011:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5012:             return 'refused';
 5013:         }
 5014:         $mrole='gr';
 5015:     } else {
 5016:         my $cwosec=$url;
 5017:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5018:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 5019:            &logthis('Refused assignrole: '.
 5020:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5021: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5022:            return 'refused'; 
 5023:         }
 5024:         $mrole=$role;
 5025:     }
 5026:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5027:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5028:     if ($end) { $command.='_'.$end; }
 5029:     if ($start) {
 5030: 	if ($end) { 
 5031:            $command.='_'.$start; 
 5032:         } else {
 5033:            $command.='_0_'.$start;
 5034:         }
 5035:     }
 5036:     my $origstart = $start;
 5037:     my $origend = $end;
 5038: # actually delete
 5039:     if ($deleteflag) {
 5040: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5041: # modify command to delete the role
 5042:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5043:                 "$udom:$uname:$url".'_'."$mrole";
 5044: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5045: # set start and finish to negative values for userrolelog
 5046:            $start=-1;
 5047:            $end=-1;
 5048:         }
 5049:     }
 5050: # send command
 5051:     my $answer=&reply($command,&homeserver($uname,$udom));
 5052: # log new user role if status is ok
 5053:     if ($answer eq 'ok') {
 5054: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5055: # for course roles, perform group memberships changes triggered by role change.
 5056:         unless ($role =~ /^gr/) {
 5057:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5058:                                              $origstart);
 5059:         }
 5060:     }
 5061:     return $answer;
 5062: }
 5063: 
 5064: # -------------------------------------------------- Modify user authentication
 5065: # Overrides without validation
 5066: 
 5067: sub modifyuserauth {
 5068:     my ($udom,$uname,$umode,$upass)=@_;
 5069:     my $uhome=&homeserver($uname,$udom);
 5070:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5071:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5072:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5073:              ' in domain '.$env{'request.role.domain'});  
 5074:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5075: 		     &escape($upass),$uhome);
 5076:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5077:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5078:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5079:     &log($udom,,$uname,$uhome,
 5080:         'Authentication changed by '.$env{'user.domain'}.', '.
 5081:                                      $env{'user.name'}.', '.$umode.
 5082:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5083:     unless ($reply eq 'ok') {
 5084:         &logthis('Authentication mode error: '.$reply);
 5085: 	return 'error: '.$reply;
 5086:     }   
 5087:     return 'ok';
 5088: }
 5089: 
 5090: # --------------------------------------------------------------- Modify a user
 5091: 
 5092: sub modifyuser {
 5093:     my ($udom,    $uname, $uid,
 5094:         $umode,   $upass, $first,
 5095:         $middle,  $last,  $gene,
 5096:         $forceid, $desiredhome, $email)=@_;
 5097:     $udom= &LONCAPA::clean_domain($udom);
 5098:     $uname=&LONCAPA::clean_username($uname);
 5099:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5100:              $umode.', '.$first.', '.$middle.', '.
 5101: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5102:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5103:                                      ' desiredhome not specified'). 
 5104:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5105:              ' in domain '.$env{'request.role.domain'});
 5106:     my $uhome=&homeserver($uname,$udom,'true');
 5107: # ----------------------------------------------------------------- Create User
 5108:     if (($uhome eq 'no_host') && 
 5109: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5110:         my $unhome='';
 5111:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5112:             $unhome = $desiredhome;
 5113: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5114: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5115:         } else { # load balancing routine for determining $unhome
 5116:             my $loadm=10000000;
 5117: 	    my %servers = &get_servers($udom,'library');
 5118: 	    foreach my $tryserver (keys(%servers)) {
 5119: 		my $answer=reply('load',$tryserver);
 5120: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5121: 		    $loadm=$answer;
 5122: 		    $unhome=$tryserver;
 5123: 		}
 5124: 	    }
 5125:         }
 5126:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5127: 	    return 'error: unable to find a home server for '.$uname.
 5128:                    ' in domain '.$udom;
 5129:         }
 5130:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5131:                          &escape($upass),$unhome);
 5132: 	unless ($reply eq 'ok') {
 5133:             return 'error: '.$reply;
 5134:         }   
 5135:         $uhome=&homeserver($uname,$udom,'true');
 5136:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5137: 	    return 'error: unable verify users home machine.';
 5138:         }
 5139:     }   # End of creation of new user
 5140: # ---------------------------------------------------------------------- Add ID
 5141:     if ($uid) {
 5142:        $uid=~tr/A-Z/a-z/;
 5143:        my %uidhash=&idrget($udom,$uname);
 5144:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5145:          && (!$forceid)) {
 5146: 	  unless ($uid eq $uidhash{$uname}) {
 5147: 	      return 'error: user id "'.$uid.'" does not match '.
 5148:                   'current user id "'.$uidhash{$uname}.'".';
 5149:           }
 5150:        } else {
 5151: 	  &idput($udom,($uname => $uid));
 5152:        }
 5153:     }
 5154: # -------------------------------------------------------------- Add names, etc
 5155:     my @tmp=&get('environment',
 5156: 		   ['firstname','middlename','lastname','generation','id',
 5157:                     'permanentemail'],
 5158: 		   $udom,$uname);
 5159:     my %names;
 5160:     if ($tmp[0] =~ m/^error:.*/) { 
 5161:         %names=(); 
 5162:     } else {
 5163:         %names = @tmp;
 5164:     }
 5165: #
 5166: # Make sure to not trash student environment if instructor does not bother
 5167: # to supply name and email information
 5168: #
 5169:     if ($first)  { $names{'firstname'}  = $first; }
 5170:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5171:     if ($last)   { $names{'lastname'}   = $last; }
 5172:     if (defined($gene))   { $names{'generation'} = $gene; }
 5173:     if ($email) {
 5174:        $email=~s/[^\w\@\.\-\,]//gs;
 5175:        if ($email=~/\@/) { $names{'notification'} = $email;
 5176: 			   $names{'critnotification'} = $email;
 5177: 			   $names{'permanentemail'} = $email; }
 5178:     }
 5179:     if ($uid) { $names{'id'}  = $uid; }
 5180:     my $reply = &put('environment', \%names, $udom,$uname);
 5181:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5182:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5183:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5184:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5185:              $umode.', '.$first.', '.$middle.', '.
 5186: 	     $last.', '.$gene.' by '.
 5187:              $env{'user.name'}.' at '.$env{'user.domain'});
 5188:     return 'ok';
 5189: }
 5190: 
 5191: # -------------------------------------------------------------- Modify student
 5192: 
 5193: sub modifystudent {
 5194:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5195:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5196:     if (!$cid) {
 5197: 	unless ($cid=$env{'request.course.id'}) {
 5198: 	    return 'not_in_class';
 5199: 	}
 5200:     }
 5201: # --------------------------------------------------------------- Make the user
 5202:     my $reply=&modifyuser
 5203: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5204:          $desiredhome,$email);
 5205:     unless ($reply eq 'ok') { return $reply; }
 5206:     # This will cause &modify_student_enrollment to get the uid from the
 5207:     # students environment
 5208:     $uid = undef if (!$forceid);
 5209:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5210: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5211:     return $reply;
 5212: }
 5213: 
 5214: sub modify_student_enrollment {
 5215:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5216:     my ($cdom,$cnum,$chome);
 5217:     if (!$cid) {
 5218: 	unless ($cid=$env{'request.course.id'}) {
 5219: 	    return 'not_in_class';
 5220: 	}
 5221: 	$cdom=$env{'course.'.$cid.'.domain'};
 5222: 	$cnum=$env{'course.'.$cid.'.num'};
 5223:     } else {
 5224: 	($cdom,$cnum)=split(/_/,$cid);
 5225:     }
 5226:     $chome=$env{'course.'.$cid.'.home'};
 5227:     if (!$chome) {
 5228: 	$chome=&homeserver($cnum,$cdom);
 5229:     }
 5230:     if (!$chome) { return 'unknown_course'; }
 5231:     # Make sure the user exists
 5232:     my $uhome=&homeserver($uname,$udom);
 5233:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5234: 	return 'error: no such user';
 5235:     }
 5236:     # Get student data if we were not given enough information
 5237:     if (!defined($first)  || $first  eq '' || 
 5238:         !defined($last)   || $last   eq '' || 
 5239:         !defined($uid)    || $uid    eq '' || 
 5240:         !defined($middle) || $middle eq '' || 
 5241:         !defined($gene)   || $gene   eq '') {
 5242:         # They did not supply us with enough data to enroll the student, so
 5243:         # we need to pick up more information.
 5244:         my %tmp = &get('environment',
 5245:                        ['firstname','middlename','lastname', 'generation','id']
 5246:                        ,$udom,$uname);
 5247: 
 5248:         #foreach my $key (keys(%tmp)) {
 5249:         #    &logthis("key $key = ".$tmp{$key});
 5250:         #}
 5251:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5252:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5253:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5254:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5255:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5256:     }
 5257:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5258:     my $reply=cput('classlist',
 5259: 		   {"$uname:$udom" => 
 5260: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5261: 		   $cdom,$cnum);
 5262:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5263: 	return 'error: '.$reply;
 5264:     } else {
 5265: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5266:     }
 5267:     # Add student role to user
 5268:     my $uurl='/'.$cid;
 5269:     $uurl=~s/\_/\//g;
 5270:     if ($usec) {
 5271: 	$uurl.='/'.$usec;
 5272:     }
 5273:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5274: }
 5275: 
 5276: sub format_name {
 5277:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5278:     my $name;
 5279:     if ($first ne 'lastname') {
 5280: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5281:     } else {
 5282: 	if ($lastname=~/\S/) {
 5283: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5284: 	    $name=~s/\s+,/,/;
 5285: 	} else {
 5286: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5287: 	}
 5288:     }
 5289:     $name=~s/^\s+//;
 5290:     $name=~s/\s+$//;
 5291:     $name=~s/\s+/ /g;
 5292:     return $name;
 5293: }
 5294: 
 5295: # ------------------------------------------------- Write to course preferences
 5296: 
 5297: sub writecoursepref {
 5298:     my ($courseid,%prefs)=@_;
 5299:     $courseid=~s/^\///;
 5300:     $courseid=~s/\_/\//g;
 5301:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5302:     my $chome=homeserver($cnum,$cdomain);
 5303:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5304: 	return 'error: no such course';
 5305:     }
 5306:     my $cstring='';
 5307:     foreach my $pref (keys(%prefs)) {
 5308: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5309:     }
 5310:     $cstring=~s/\&$//;
 5311:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5312: }
 5313: 
 5314: # ---------------------------------------------------------- Make/modify course
 5315: 
 5316: sub createcourse {
 5317:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5318:         $course_owner,$crstype)=@_;
 5319:     $url=&declutter($url);
 5320:     my $cid='';
 5321:     unless (&allowed('ccc',$udom)) {
 5322:         return 'refused';
 5323:     }
 5324: # ------------------------------------------------------------------- Create ID
 5325:    my $uname=int(1+rand(9)).
 5326:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5327:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5328:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5329: # ----------------------------------------------- Make sure that does not exist
 5330:    my $uhome=&homeserver($uname,$udom,'true');
 5331:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5332:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5333:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5334:        $uhome=&homeserver($uname,$udom,'true');       
 5335:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5336:            return 'error: unable to generate unique course-ID';
 5337:        } 
 5338:    }
 5339: # ------------------------------------------------ Check supplied server name
 5340:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5341:     if (! &is_library($course_server)) {
 5342:         return 'error:bad server name '.$course_server;
 5343:     }
 5344: # ------------------------------------------------------------- Make the course
 5345:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5346:                       $course_server);
 5347:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5348:     $uhome=&homeserver($uname,$udom,'true');
 5349:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5350: 	return 'error: no such course';
 5351:     }
 5352: # ----------------------------------------------------------------- Course made
 5353: # log existence
 5354:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5355:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5356:                   &escape($crstype),$uhome);
 5357:     &flushcourselogs();
 5358: # set toplevel url
 5359:     my $topurl=$url;
 5360:     unless ($nonstandard) {
 5361: # ------------------------------------------ For standard courses, make top url
 5362:         my $mapurl=&clutter($url);
 5363:         if ($mapurl eq '/res/') { $mapurl=''; }
 5364:         $env{'form.initmap'}=(<<ENDINITMAP);
 5365: <map>
 5366: <resource id="1" type="start"></resource>
 5367: <resource id="2" src="$mapurl"></resource>
 5368: <resource id="3" type="finish"></resource>
 5369: <link index="1" from="1" to="2"></link>
 5370: <link index="2" from="2" to="3"></link>
 5371: </map>
 5372: ENDINITMAP
 5373:         $topurl=&declutter(
 5374:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5375:                           );
 5376:     }
 5377: # ----------------------------------------------------------- Write preferences
 5378:     &writecoursepref($udom.'_'.$uname,
 5379:                      ('description' => $description,
 5380:                       'url'         => $topurl));
 5381:     return '/'.$udom.'/'.$uname;
 5382: }
 5383: 
 5384: sub is_course {
 5385:     my ($cdom,$cnum) = @_;
 5386:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5387: 				undef,'.');
 5388:     if (exists($courses{$cdom.'_'.$cnum})) {
 5389:         return 1;
 5390:     }
 5391:     return 0;
 5392: }
 5393: 
 5394: # ---------------------------------------------------------- Assign Custom Role
 5395: 
 5396: sub assigncustomrole {
 5397:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5398:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5399:                        $end,$start,$deleteflag);
 5400: }
 5401: 
 5402: # ----------------------------------------------------------------- Revoke Role
 5403: 
 5404: sub revokerole {
 5405:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5406:     my $now=time;
 5407:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5408: }
 5409: 
 5410: # ---------------------------------------------------------- Revoke Custom Role
 5411: 
 5412: sub revokecustomrole {
 5413:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5414:     my $now=time;
 5415:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5416:            $deleteflag);
 5417: }
 5418: 
 5419: # ------------------------------------------------------------ Disk usage
 5420: sub diskusage {
 5421:     my ($udom,$uname,$directoryRoot)=@_;
 5422:     $directoryRoot =~ s/\/$//;
 5423:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5424:     return $listing;
 5425: }
 5426: 
 5427: sub is_locked {
 5428:     my ($file_name, $domain, $user) = @_;
 5429:     my @check;
 5430:     my $is_locked;
 5431:     push @check, $file_name;
 5432:     my %locked = &get('file_permissions',\@check,
 5433: 		      $env{'user.domain'},$env{'user.name'});
 5434:     my ($tmp)=keys(%locked);
 5435:     if ($tmp=~/^error:/) { undef(%locked); }
 5436:     
 5437:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5438:         $is_locked = 'false';
 5439:         foreach my $entry (@{$locked{$file_name}}) {
 5440:            if (ref($entry) eq 'ARRAY') { 
 5441:                $is_locked = 'true';
 5442:                last;
 5443:            }
 5444:        }
 5445:     } else {
 5446:         $is_locked = 'false';
 5447:     }
 5448: }
 5449: 
 5450: sub declutter_portfile {
 5451:     my ($file) = @_;
 5452:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5453:     return $file;
 5454: }
 5455: 
 5456: # ------------------------------------------------------------- Mark as Read Only
 5457: 
 5458: sub mark_as_readonly {
 5459:     my ($domain,$user,$files,$what) = @_;
 5460:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5461:     my ($tmp)=keys(%current_permissions);
 5462:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5463:     foreach my $file (@{$files}) {
 5464: 	$file = &declutter_portfile($file);
 5465:         push(@{$current_permissions{$file}},$what);
 5466:     }
 5467:     &put('file_permissions',\%current_permissions,$domain,$user);
 5468:     return;
 5469: }
 5470: 
 5471: # ------------------------------------------------------------Save Selected Files
 5472: 
 5473: sub save_selected_files {
 5474:     my ($user, $path, @files) = @_;
 5475:     my $filename = $user."savedfiles";
 5476:     my @other_files = &files_not_in_path($user, $path);
 5477:     open (OUT, '>'.$tmpdir.$filename);
 5478:     foreach my $file (@files) {
 5479:         print (OUT $env{'form.currentpath'}.$file."\n");
 5480:     }
 5481:     foreach my $file (@other_files) {
 5482:         print (OUT $file."\n");
 5483:     }
 5484:     close (OUT);
 5485:     return 'ok';
 5486: }
 5487: 
 5488: sub clear_selected_files {
 5489:     my ($user) = @_;
 5490:     my $filename = $user."savedfiles";
 5491:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5492:     print (OUT undef);
 5493:     close (OUT);
 5494:     return ("ok");    
 5495: }
 5496: 
 5497: sub files_in_path {
 5498:     my ($user, $path) = @_;
 5499:     my $filename = $user."savedfiles";
 5500:     my %return_files;
 5501:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5502:     while (my $line_in = <IN>) {
 5503:         chomp ($line_in);
 5504:         my @paths_and_file = split (m!/!, $line_in);
 5505:         my $file_part = pop (@paths_and_file);
 5506:         my $path_part = join ('/', @paths_and_file);
 5507:         $path_part.='/';
 5508:         my $path_and_file = $path_part.$file_part;
 5509:         if ($path_part eq $path) {
 5510:             $return_files{$file_part}= 'selected';
 5511:         }
 5512:     }
 5513:     close (IN);
 5514:     return (\%return_files);
 5515: }
 5516: 
 5517: # called in portfolio select mode, to show files selected NOT in current directory
 5518: sub files_not_in_path {
 5519:     my ($user, $path) = @_;
 5520:     my $filename = $user."savedfiles";
 5521:     my @return_files;
 5522:     my $path_part;
 5523:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5524:     while (my $line = <IN>) {
 5525:         #ok, I know it's clunky, but I want it to work
 5526:         my @paths_and_file = split(m|/|, $line);
 5527:         my $file_part = pop(@paths_and_file);
 5528:         chomp($file_part);
 5529:         my $path_part = join('/', @paths_and_file);
 5530:         $path_part .= '/';
 5531:         my $path_and_file = $path_part.$file_part;
 5532:         if ($path_part ne $path) {
 5533:             push(@return_files, ($path_and_file));
 5534:         }
 5535:     }
 5536:     close(OUT);
 5537:     return (@return_files);
 5538: }
 5539: 
 5540: #----------------------------------------------Get portfolio file permissions
 5541: 
 5542: sub get_portfile_permissions {
 5543:     my ($domain,$user) = @_;
 5544:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5545:     my ($tmp)=keys(%current_permissions);
 5546:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5547:     return \%current_permissions;
 5548: }
 5549: 
 5550: #---------------------------------------------Get portfolio file access controls
 5551: 
 5552: sub get_access_controls {
 5553:     my ($current_permissions,$group,$file) = @_;
 5554:     my %access;
 5555:     my $real_file = $file;
 5556:     $file =~ s/\.meta$//;
 5557:     if (defined($file)) {
 5558:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5559:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5560:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5561:             }
 5562:         }
 5563:     } else {
 5564:         foreach my $key (keys(%{$current_permissions})) {
 5565:             if ($key =~ /\0accesscontrol$/) {
 5566:                 if (defined($group)) {
 5567:                     if ($key !~ m-^\Q$group\E/-) {
 5568:                         next;
 5569:                     }
 5570:                 }
 5571:                 my ($fullpath) = split(/\0/,$key);
 5572:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5573:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5574:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5575:                     }
 5576:                 }
 5577:             }
 5578:         }
 5579:     }
 5580:     return %access;
 5581: }
 5582: 
 5583: sub modify_access_controls {
 5584:     my ($file_name,$changes,$domain,$user)=@_;
 5585:     my ($outcome,$deloutcome);
 5586:     my %store_permissions;
 5587:     my %new_values;
 5588:     my %new_control;
 5589:     my %translation;
 5590:     my @deletions = ();
 5591:     my $now = time;
 5592:     if (exists($$changes{'activate'})) {
 5593:         if (ref($$changes{'activate'}) eq 'HASH') {
 5594:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5595:             my $numnew = scalar(@newitems);
 5596:             for (my $i=0; $i<$numnew; $i++) {
 5597:                 my $newkey = $newitems[$i];
 5598:                 my $newid = &Apache::loncommon::get_cgi_id();
 5599:                 if ($newkey =~ /^\d+:/) { 
 5600:                     $newkey =~ s/^(\d+)/$newid/;
 5601:                     $translation{$1} = $newid;
 5602:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5603:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5604:                     $translation{$1} = $newid;
 5605:                 }
 5606:                 $new_values{$file_name."\0".$newkey} = 
 5607:                                           $$changes{'activate'}{$newitems[$i]};
 5608:                 $new_control{$newkey} = $now;
 5609:             }
 5610:         }
 5611:     }
 5612:     my %todelete;
 5613:     my %changed_items;
 5614:     foreach my $action ('delete','update') {
 5615:         if (exists($$changes{$action})) {
 5616:             if (ref($$changes{$action}) eq 'HASH') {
 5617:                 foreach my $key (keys(%{$$changes{$action}})) {
 5618:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5619:                     if ($action eq 'delete') { 
 5620:                         $todelete{$itemnum} = 1;
 5621:                     } else {
 5622:                         $changed_items{$itemnum} = $key;
 5623:                     }
 5624:                 }
 5625:             }
 5626:         }
 5627:     }
 5628:     # get lock on access controls for file.
 5629:     my $lockhash = {
 5630:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5631:                                                        ':'.$env{'user.domain'},
 5632:                    }; 
 5633:     my $tries = 0;
 5634:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5635:    
 5636:     while (($gotlock ne 'ok') && $tries <3) {
 5637:         $tries ++;
 5638:         sleep 1;
 5639:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5640:     }
 5641:     if ($gotlock eq 'ok') {
 5642:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5643:         my ($tmp)=keys(%curr_permissions);
 5644:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5645:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5646:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5647:             if (ref($curr_controls) eq 'HASH') {
 5648:                 foreach my $control_item (keys(%{$curr_controls})) {
 5649:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5650:                     if (defined($todelete{$itemnum})) {
 5651:                         push(@deletions,$file_name."\0".$control_item);
 5652:                     } else {
 5653:                         if (defined($changed_items{$itemnum})) {
 5654:                             $new_control{$changed_items{$itemnum}} = $now;
 5655:                             push(@deletions,$file_name."\0".$control_item);
 5656:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5657:                         } else {
 5658:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5659:                         }
 5660:                     }
 5661:                 }
 5662:             }
 5663:         }
 5664:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5665:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5666:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5667:         #  remove lock
 5668:         my @del_lock = ($file_name."\0".'locked_access_records');
 5669:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5670:         my ($file,$group);
 5671:         if (&is_course($domain,$user)) {
 5672:             ($group,$file) = split(/\//,$file_name,2);
 5673:         } else {
 5674:             $file = $file_name;
 5675:         }
 5676:         my $sqlresult =
 5677:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5678:                                     $group);
 5679:     } else {
 5680:         $outcome = "error: could not obtain lockfile\n";  
 5681:     }
 5682:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5683: }
 5684: 
 5685: sub make_public_indefinitely {
 5686:     my ($requrl) = @_;
 5687:     my $now = time;
 5688:     my $action = 'activate';
 5689:     my $aclnum = 0;
 5690:     if (&is_portfolio_url($requrl)) {
 5691:         my (undef,$udom,$unum,$file_name,$group) =
 5692:             &parse_portfolio_url($requrl);
 5693:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5694:         my %access_controls = &get_access_controls($current_perms,
 5695:                                                    $group,$file_name);
 5696:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5697:             my ($num,$scope,$end,$start) = 
 5698:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5699:             if ($scope eq 'public') {
 5700:                 if ($start <= $now && $end == 0) {
 5701:                     $action = 'none';
 5702:                 } else {
 5703:                     $action = 'update';
 5704:                     $aclnum = $num;
 5705:                 }
 5706:                 last;
 5707:             }
 5708:         }
 5709:         if ($action eq 'none') {
 5710:              return 'ok';
 5711:         } else {
 5712:             my %changes;
 5713:             my $newend = 0;
 5714:             my $newstart = $now;
 5715:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5716:             $changes{$action}{$newkey} = {
 5717:                 type => 'public',
 5718:                 time => {
 5719:                     start => $newstart,
 5720:                     end   => $newend,
 5721:                 },
 5722:             };
 5723:             my ($outcome,$deloutcome,$new_values,$translation) =
 5724:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5725:             return $outcome;
 5726:         }
 5727:     } else {
 5728:         return 'invalid';
 5729:     }
 5730: }
 5731: 
 5732: #------------------------------------------------------Get Marked as Read Only
 5733: 
 5734: sub get_marked_as_readonly {
 5735:     my ($domain,$user,$what,$group) = @_;
 5736:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5737:     my @readonly_files;
 5738:     my $cmp1=$what;
 5739:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5740:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5741:         if (defined($group)) {
 5742:             if ($file_name !~ m-^\Q$group\E/-) {
 5743:                 next;
 5744:             }
 5745:         }
 5746:         if (ref($value) eq "ARRAY"){
 5747:             foreach my $stored_what (@{$value}) {
 5748:                 my $cmp2=$stored_what;
 5749:                 if (ref($stored_what) eq 'ARRAY') {
 5750:                     $cmp2=join('',@{$stored_what});
 5751:                 }
 5752:                 if ($cmp1 eq $cmp2) {
 5753:                     push(@readonly_files, $file_name);
 5754:                     last;
 5755:                 } elsif (!defined($what)) {
 5756:                     push(@readonly_files, $file_name);
 5757:                     last;
 5758:                 }
 5759:             }
 5760:         }
 5761:     }
 5762:     return @readonly_files;
 5763: }
 5764: #-----------------------------------------------------------Get Marked as Read Only Hash
 5765: 
 5766: sub get_marked_as_readonly_hash {
 5767:     my ($current_permissions,$group,$what) = @_;
 5768:     my %readonly_files;
 5769:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5770:         if (defined($group)) {
 5771:             if ($file_name !~ m-^\Q$group\E/-) {
 5772:                 next;
 5773:             }
 5774:         }
 5775:         if (ref($value) eq "ARRAY"){
 5776:             foreach my $stored_what (@{$value}) {
 5777:                 if (ref($stored_what) eq 'ARRAY') {
 5778:                     foreach my $lock_descriptor(@{$stored_what}) {
 5779:                         if ($lock_descriptor eq 'graded') {
 5780:                             $readonly_files{$file_name} = 'graded';
 5781:                         } elsif ($lock_descriptor eq 'handback') {
 5782:                             $readonly_files{$file_name} = 'handback';
 5783:                         } else {
 5784:                             if (!exists($readonly_files{$file_name})) {
 5785:                                 $readonly_files{$file_name} = 'locked';
 5786:                             }
 5787:                         }
 5788:                     }
 5789:                 } 
 5790:             }
 5791:         } 
 5792:     }
 5793:     return %readonly_files;
 5794: }
 5795: # ------------------------------------------------------------ Unmark as Read Only
 5796: 
 5797: sub unmark_as_readonly {
 5798:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5799:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5800:     my ($domain,$user,$what,$file_name,$group) = @_;
 5801:     $file_name = &declutter_portfile($file_name);
 5802:     my $symb_crs = $what;
 5803:     if (ref($what)) { $symb_crs=join('',@$what); }
 5804:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5805:     my ($tmp)=keys(%current_permissions);
 5806:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5807:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5808:     foreach my $file (@readonly_files) {
 5809: 	my $clean_file = &declutter_portfile($file);
 5810: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5811: 	my $current_locks = $current_permissions{$file};
 5812:         my @new_locks;
 5813:         my @del_keys;
 5814:         if (ref($current_locks) eq "ARRAY"){
 5815:             foreach my $locker (@{$current_locks}) {
 5816:                 my $compare=$locker;
 5817:                 if (ref($locker) eq 'ARRAY') {
 5818:                     $compare=join('',@{$locker});
 5819:                     if ($compare ne $symb_crs) {
 5820:                         push(@new_locks, $locker);
 5821:                     }
 5822:                 }
 5823:             }
 5824:             if (scalar(@new_locks) > 0) {
 5825:                 $current_permissions{$file} = \@new_locks;
 5826:             } else {
 5827:                 push(@del_keys, $file);
 5828:                 &del('file_permissions',\@del_keys, $domain, $user);
 5829:                 delete($current_permissions{$file});
 5830:             }
 5831:         }
 5832:     }
 5833:     &put('file_permissions',\%current_permissions,$domain,$user);
 5834:     return;
 5835: }
 5836: 
 5837: # ------------------------------------------------------------ Directory lister
 5838: 
 5839: sub dirlist {
 5840:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5841: 
 5842:     $uri=~s/^\///;
 5843:     $uri=~s/\/$//;
 5844:     my ($udom, $uname);
 5845:     (undef,$udom,$uname)=split(/\//,$uri);
 5846:     if(defined($userdomain)) {
 5847:         $udom = $userdomain;
 5848:     }
 5849:     if(defined($username)) {
 5850:         $uname = $username;
 5851:     }
 5852: 
 5853:     my $dirRoot = $perlvar{'lonDocRoot'};
 5854:     if(defined($alternateDirectoryRoot)) {
 5855:         $dirRoot = $alternateDirectoryRoot;
 5856:         $dirRoot =~ s/\/$//;
 5857:     }
 5858: 
 5859:     if($udom) {
 5860:         if($uname) {
 5861:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5862: 				 &homeserver($uname,$udom));
 5863:             my @listing_results;
 5864:             if ($listing eq 'unknown_cmd') {
 5865:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5866: 				  &homeserver($uname,$udom));
 5867:                 @listing_results = split(/:/,$listing);
 5868:             } else {
 5869:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5870:             }
 5871:             return @listing_results;
 5872:         } elsif(!defined($alternateDirectoryRoot)) {
 5873:             my %allusers;
 5874: 	    my %servers = &get_servers($udom,'library');
 5875: 	    foreach my $tryserver (keys(%servers)) {
 5876: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5877: 				     $udom, $tryserver);
 5878: 		my @listing_results;
 5879: 		if ($listing eq 'unknown_cmd') {
 5880: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5881: 				      $udom, $tryserver);
 5882: 		    @listing_results = split(/:/,$listing);
 5883: 		} else {
 5884: 		    @listing_results =
 5885: 			map { &unescape($_); } split(/:/,$listing);
 5886: 		}
 5887: 		if ($listing_results[0] ne 'no_such_dir' && 
 5888: 		    $listing_results[0] ne 'empty'       &&
 5889: 		    $listing_results[0] ne 'con_lost') {
 5890: 		    foreach my $line (@listing_results) {
 5891: 			my ($entry) = split(/&/,$line,2);
 5892: 			$allusers{$entry} = 1;
 5893: 		    }
 5894: 		}
 5895:             }
 5896:             my $alluserstr='';
 5897:             foreach my $user (sort(keys(%allusers))) {
 5898:                 $alluserstr.=$user.'&user:';
 5899:             }
 5900:             $alluserstr=~s/:$//;
 5901:             return split(/:/,$alluserstr);
 5902:         } else {
 5903:             return ('missing user name');
 5904:         }
 5905:     } elsif(!defined($alternateDirectoryRoot)) {
 5906:         my @all_domains = sort(&all_domains());
 5907:          foreach my $domain (@all_domains) {
 5908:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5909:          }
 5910:          return @all_domains;
 5911:      } else {
 5912:         return ('missing domain');
 5913:     }
 5914: }
 5915: 
 5916: # --------------------------------------------- GetFileTimestamp
 5917: # This function utilizes dirlist and returns the date stamp for
 5918: # when it was last modified.  It will also return an error of -1
 5919: # if an error occurs
 5920: 
 5921: ##
 5922: ## FIXME: This subroutine assumes its caller knows something about the
 5923: ## directory structure of the home server for the student ($root).
 5924: ## Not a good assumption to make.  Since this is for looking up files
 5925: ## in user directories, the full path should be constructed by lond, not
 5926: ## whatever machine we request data from.
 5927: ##
 5928: sub GetFileTimestamp {
 5929:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5930:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5931:     $studentName   = &LONCAPA::clean_username($studentName);
 5932:     my $subdir=$studentName.'__';
 5933:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5934:     my $proname="$studentDomain/$subdir/$studentName";
 5935:     $proname .= '/'.$filename;
 5936:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5937:                                               $studentName, $root);
 5938:     my @stats = split('&', $fileStat);
 5939:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5940:         # @stats contains first the filename, then the stat output
 5941:         return $stats[10]; # so this is 10 instead of 9.
 5942:     } else {
 5943:         return -1;
 5944:     }
 5945: }
 5946: 
 5947: sub stat_file {
 5948:     my ($uri) = @_;
 5949:     $uri = &clutter_with_no_wrapper($uri);
 5950: 
 5951:     my ($udom,$uname,$file,$dir);
 5952:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5953: 	($udom,$uname,$file) =
 5954: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5955: 	$file = 'userfiles/'.$file;
 5956: 	$dir = &propath($udom,$uname);
 5957:     }
 5958:     if ($uri =~ m-^/res/-) {
 5959: 	($udom,$uname) = 
 5960: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5961: 	$file = $uri;
 5962:     }
 5963: 
 5964:     if (!$udom || !$uname || !$file) {
 5965: 	# unable to handle the uri
 5966: 	return ();
 5967:     }
 5968: 
 5969:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5970:     my @stats = split('&', $result);
 5971:     
 5972:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5973: 	shift(@stats); #filename is first
 5974: 	return @stats;
 5975:     }
 5976:     return ();
 5977: }
 5978: 
 5979: # -------------------------------------------------------- Value of a Condition
 5980: 
 5981: # gets the value of a specific preevaluated condition
 5982: #    stored in the string  $env{user.state.<cid>}
 5983: # or looks up a condition reference in the bighash and if if hasn't
 5984: # already been evaluated recurses into docondval to get the value of
 5985: # the condition, then memoizing it to 
 5986: #   $env{user.state.<cid>.<condition>}
 5987: sub directcondval {
 5988:     my $number=shift;
 5989:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5990: 	&Apache::lonuserstate::evalstate();
 5991:     }
 5992:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5993: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5994:     } elsif ($number =~ /^_/) {
 5995: 	my $sub_condition;
 5996: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5997: 		&GDBM_READER(),0640)) {
 5998: 	    $sub_condition=$bighash{'conditions'.$number};
 5999: 	    untie(%bighash);
 6000: 	}
 6001: 	my $value = &docondval($sub_condition);
 6002: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 6003: 	return $value;
 6004:     }
 6005:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6006:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6007:     } else {
 6008:        return 2;
 6009:     }
 6010: }
 6011: 
 6012: # get the collection of conditions for this resource
 6013: sub condval {
 6014:     my $condidx=shift;
 6015:     my $allpathcond='';
 6016:     foreach my $cond (split(/\|/,$condidx)) {
 6017: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6018: 	    $allpathcond.=
 6019: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6020: 	}
 6021:     }
 6022:     $allpathcond=~s/\|$//;
 6023:     return &docondval($allpathcond);
 6024: }
 6025: 
 6026: #evaluates an expression of conditions
 6027: sub docondval {
 6028:     my ($allpathcond) = @_;
 6029:     my $result=0;
 6030:     if ($env{'request.course.id'}
 6031: 	&& defined($allpathcond)) {
 6032: 	my $operand='|';
 6033: 	my @stack;
 6034: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6035: 	    if ($chunk eq '(') {
 6036: 		push @stack,($operand,$result);
 6037: 	    } elsif ($chunk eq ')') {
 6038: 		my $before=pop @stack;
 6039: 		if (pop @stack eq '&') {
 6040: 		    $result=$result>$before?$before:$result;
 6041: 		} else {
 6042: 		    $result=$result>$before?$result:$before;
 6043: 		}
 6044: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6045: 		$operand=$chunk;
 6046: 	    } else {
 6047: 		my $new=directcondval($chunk);
 6048: 		if ($operand eq '&') {
 6049: 		    $result=$result>$new?$new:$result;
 6050: 		} else {
 6051: 		    $result=$result>$new?$result:$new;
 6052: 		}
 6053: 	    }
 6054: 	}
 6055:     }
 6056:     return $result;
 6057: }
 6058: 
 6059: # ---------------------------------------------------- Devalidate courseresdata
 6060: 
 6061: sub devalidatecourseresdata {
 6062:     my ($coursenum,$coursedomain)=@_;
 6063:     my $hashid=$coursenum.':'.$coursedomain;
 6064:     &devalidate_cache_new('courseres',$hashid);
 6065: }
 6066: 
 6067: 
 6068: # --------------------------------------------------- Course Resourcedata Query
 6069: #
 6070: #  Parameters:
 6071: #      $coursenum    - Number of the course.
 6072: #      $coursedomain - Domain at which the course was created.
 6073: #  Returns:
 6074: #     A hash of the course parameters along (I think) with timestamps
 6075: #     and version info.
 6076: 
 6077: sub get_courseresdata {
 6078:     my ($coursenum,$coursedomain)=@_;
 6079:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6080:     my $hashid=$coursenum.':'.$coursedomain;
 6081:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6082:     my %dumpreply;
 6083:     unless (defined($cached)) {
 6084: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6085: 	$result=\%dumpreply;
 6086: 	my ($tmp) = keys(%dumpreply);
 6087: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6088: 	    &do_cache_new('courseres',$hashid,$result,600);
 6089: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6090: 	    return $tmp;
 6091: 	} elsif ($tmp =~ /^(error)/) {
 6092: 	    $result=undef;
 6093: 	    &do_cache_new('courseres',$hashid,$result,600);
 6094: 	}
 6095:     }
 6096:     return $result;
 6097: }
 6098: 
 6099: sub devalidateuserresdata {
 6100:     my ($uname,$udom)=@_;
 6101:     my $hashid="$udom:$uname";
 6102:     &devalidate_cache_new('userres',$hashid);
 6103: }
 6104: 
 6105: sub get_userresdata {
 6106:     my ($uname,$udom)=@_;
 6107:     #most student don\'t have any data set, check if there is some data
 6108:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6109: 
 6110:     my $hashid="$udom:$uname";
 6111:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6112:     if (!defined($cached)) {
 6113: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6114: 	$result=\%resourcedata;
 6115: 	&do_cache_new('userres',$hashid,$result,600);
 6116:     }
 6117:     my ($tmp)=keys(%$result);
 6118:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6119: 	return $result;
 6120:     }
 6121:     #error 2 occurs when the .db doesn't exist
 6122:     if ($tmp!~/error: 2 /) {
 6123: 	&logthis("<font color=\"blue\">WARNING:".
 6124: 		 " Trying to get resource data for ".
 6125: 		 $uname." at ".$udom.": ".
 6126: 		 $tmp."</font>");
 6127:     } elsif ($tmp=~/error: 2 /) {
 6128: 	#&EXT_cache_set($udom,$uname);
 6129: 	&do_cache_new('userres',$hashid,undef,600);
 6130: 	undef($tmp); # not really an error so don't send it back
 6131:     }
 6132:     return $tmp;
 6133: }
 6134: #----------------------------------------------- resdata - return resource data
 6135: #  Purpose:
 6136: #    Return resource data for either users or for a course.
 6137: #  Parameters:
 6138: #     $name      - Course/user name.
 6139: #     $domain    - Name of the domain the user/course is registered on.
 6140: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6141: #     @which     - Array of names of resources desired.
 6142: #  Returns:
 6143: #     The value of the first reasource in @which that is found in the
 6144: #     resource hash.
 6145: #  Exceptional Conditions:
 6146: #     If the $type passed in is not valid (not the string 'course' or 
 6147: #     'user', an undefined  reference is returned.
 6148: #     If none of the resources are found, an undef is returned
 6149: sub resdata {
 6150:     my ($name,$domain,$type,@which)=@_;
 6151:     my $result;
 6152:     if ($type eq 'course') {
 6153: 	$result=&get_courseresdata($name,$domain);
 6154:     } elsif ($type eq 'user') {
 6155: 	$result=&get_userresdata($name,$domain);
 6156:     }
 6157:     if (!ref($result)) { return $result; }    
 6158:     foreach my $item (@which) {
 6159: 	if (defined($result->{$item})) {
 6160: 	    return $result->{$item};
 6161: 	}
 6162:     }
 6163:     return undef;
 6164: }
 6165: 
 6166: #
 6167: # EXT resource caching routines
 6168: #
 6169: 
 6170: sub clear_EXT_cache_status {
 6171:     &delenv('cache.EXT.');
 6172: }
 6173: 
 6174: sub EXT_cache_status {
 6175:     my ($target_domain,$target_user) = @_;
 6176:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6177:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6178:         # We know already the user has no data
 6179:         return 1;
 6180:     } else {
 6181:         return 0;
 6182:     }
 6183: }
 6184: 
 6185: sub EXT_cache_set {
 6186:     my ($target_domain,$target_user) = @_;
 6187:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6188:     #&appenv($cachename => time);
 6189: }
 6190: 
 6191: # --------------------------------------------------------- Value of a Variable
 6192: sub EXT {
 6193: 
 6194:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6195:     unless ($varname) { return ''; }
 6196:     #get real user name/domain, courseid and symb
 6197:     my $courseid;
 6198:     my $publicuser;
 6199:     if ($symbparm) {
 6200: 	$symbparm=&get_symb_from_alias($symbparm);
 6201:     }
 6202:     if (!($uname && $udom)) {
 6203:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6204:       if (!$symbparm) {	$symbparm=$cursymb; }
 6205:     } else {
 6206: 	$courseid=$env{'request.course.id'};
 6207:     }
 6208:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6209:     my $rest;
 6210:     if (defined($therest[0])) {
 6211:        $rest=join('.',@therest);
 6212:     } else {
 6213:        $rest='';
 6214:     }
 6215: 
 6216:     my $qualifierrest=$qualifier;
 6217:     if ($rest) { $qualifierrest.='.'.$rest; }
 6218:     my $spacequalifierrest=$space;
 6219:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6220:     if ($realm eq 'user') {
 6221: # --------------------------------------------------------------- user.resource
 6222: 	if ($space eq 'resource') {
 6223: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6224: 		  || defined($Apache::lonhomework::parsing_a_task))
 6225: 		 &&
 6226: 		 ($symbparm eq &symbread()) ) {	
 6227: 		# if we are in the middle of processing the resource the
 6228: 		# get the value we are planning on committing
 6229:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6230:                     return $Apache::lonhomework::results{$qualifierrest};
 6231:                 } else {
 6232:                     return $Apache::lonhomework::history{$qualifierrest};
 6233:                 }
 6234: 	    } else {
 6235: 		my %restored;
 6236: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6237: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6238: 		} else {
 6239: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6240: 		}
 6241: 		return $restored{$qualifierrest};
 6242: 	    }
 6243: # ----------------------------------------------------------------- user.access
 6244:         } elsif ($space eq 'access') {
 6245: 	    # FIXME - not supporting calls for a specific user
 6246:             return &allowed($qualifier,$rest);
 6247: # ------------------------------------------ user.preferences, user.environment
 6248:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6249: 	    if (($uname eq $env{'user.name'}) &&
 6250: 		($udom eq $env{'user.domain'})) {
 6251: 		return $env{join('.',('environment',$qualifierrest))};
 6252: 	    } else {
 6253: 		my %returnhash;
 6254: 		if (!$publicuser) {
 6255: 		    %returnhash=&userenvironment($udom,$uname,
 6256: 						 $qualifierrest);
 6257: 		}
 6258: 		return $returnhash{$qualifierrest};
 6259: 	    }
 6260: # ----------------------------------------------------------------- user.course
 6261:         } elsif ($space eq 'course') {
 6262: 	    # FIXME - not supporting calls for a specific user
 6263:             return $env{join('.',('request.course',$qualifier))};
 6264: # ------------------------------------------------------------------- user.role
 6265:         } elsif ($space eq 'role') {
 6266: 	    # FIXME - not supporting calls for a specific user
 6267:             my ($role,$where)=split(/\./,$env{'request.role'});
 6268:             if ($qualifier eq 'value') {
 6269: 		return $role;
 6270:             } elsif ($qualifier eq 'extent') {
 6271:                 return $where;
 6272:             }
 6273: # ----------------------------------------------------------------- user.domain
 6274:         } elsif ($space eq 'domain') {
 6275:             return $udom;
 6276: # ------------------------------------------------------------------- user.name
 6277:         } elsif ($space eq 'name') {
 6278:             return $uname;
 6279: # ---------------------------------------------------- Any other user namespace
 6280:         } else {
 6281: 	    my %reply;
 6282: 	    if (!$publicuser) {
 6283: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6284: 	    }
 6285: 	    return $reply{$qualifierrest};
 6286:         }
 6287:     } elsif ($realm eq 'query') {
 6288: # ---------------------------------------------- pull stuff out of query string
 6289:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6290: 						[$spacequalifierrest]);
 6291: 	return $env{'form.'.$spacequalifierrest}; 
 6292:    } elsif ($realm eq 'request') {
 6293: # ------------------------------------------------------------- request.browser
 6294:         if ($space eq 'browser') {
 6295: 	    if ($qualifier eq 'textremote') {
 6296: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6297: 		    return 1;
 6298: 		} else {
 6299: 		    return 0;
 6300: 		}
 6301: 	    } else {
 6302: 		return $env{'browser.'.$qualifier};
 6303: 	    }
 6304: # ------------------------------------------------------------ request.filename
 6305:         } else {
 6306:             return $env{'request.'.$spacequalifierrest};
 6307:         }
 6308:     } elsif ($realm eq 'course') {
 6309: # ---------------------------------------------------------- course.description
 6310:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6311:     } elsif ($realm eq 'resource') {
 6312: 
 6313: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6314: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6315: 	}
 6316: 
 6317: 	if ($space eq 'title') {
 6318: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6319: 	    return &gettitle($symbparm);
 6320: 	}
 6321: 	
 6322: 	if ($space eq 'map') {
 6323: 	    my ($map) = &decode_symb($symbparm);
 6324: 	    return &symbread($map);
 6325: 	}
 6326: 	if ($space eq 'filename') {
 6327: 	    if ($symbparm) {
 6328: 		return &clutter((&decode_symb($symbparm))[2]);
 6329: 	    }
 6330: 	    return &hreflocation('',$env{'request.filename'});
 6331: 	}
 6332: 
 6333: 	my ($section, $group, @groups);
 6334: 	my ($courselevelm,$courselevel);
 6335: 	if ($symbparm && defined($courseid) && 
 6336: 	    $courseid eq $env{'request.course.id'}) {
 6337: 
 6338: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6339: 
 6340: # ----------------------------------------------------- Cascading lookup scheme
 6341: 	    my $symbp=$symbparm;
 6342: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6343: 
 6344: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6345: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6346: 
 6347: 	    if (($env{'user.name'} eq $uname) &&
 6348: 		($env{'user.domain'} eq $udom)) {
 6349: 		$section=$env{'request.course.sec'};
 6350:                 @groups = split(/:/,$env{'request.course.groups'});  
 6351:                 @groups=&sort_course_groups($courseid,@groups); 
 6352: 	    } else {
 6353: 		if (! defined($usection)) {
 6354: 		    $section=&getsection($udom,$uname,$courseid);
 6355: 		} else {
 6356: 		    $section = $usection;
 6357: 		}
 6358:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6359: 	    }
 6360: 
 6361: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6362: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6363: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6364: 
 6365: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6366: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6367: 	    $courselevelm=$courseid.'.'.$mapparm;
 6368: 
 6369: # ----------------------------------------------------------- first, check user
 6370: 
 6371: 	    my $userreply=&resdata($uname,$udom,'user',
 6372: 				       ($courselevelr,$courselevelm,
 6373: 					$courselevel));
 6374: 	    if (defined($userreply)) { return $userreply; }
 6375: 
 6376: # ------------------------------------------------ second, check some of course
 6377:             my $coursereply;
 6378:             if (@groups > 0) {
 6379:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6380:                                        $mapparm,$spacequalifierrest);
 6381:                 if (defined($coursereply)) { return $coursereply; }
 6382:             }
 6383: 
 6384: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6385: 				     $env{'course.'.$courseid.'.domain'},
 6386: 				     'course',
 6387: 				     ($seclevelr,$seclevelm,$seclevel,
 6388: 				      $courselevelr));
 6389: 	    if (defined($coursereply)) { return $coursereply; }
 6390: 
 6391: # ------------------------------------------------------ third, check map parms
 6392: 	    my %parmhash=();
 6393: 	    my $thisparm='';
 6394: 	    if (tie(%parmhash,'GDBM_File',
 6395: 		    $env{'request.course.fn'}.'_parms.db',
 6396: 		    &GDBM_READER(),0640)) {
 6397: 		$thisparm=$parmhash{$symbparm};
 6398: 		untie(%parmhash);
 6399: 	    }
 6400: 	    if ($thisparm) { return $thisparm; }
 6401: 	}
 6402: # ------------------------------------------ fourth, look in resource metadata
 6403: 
 6404: 	$spacequalifierrest=~s/\./\_/;
 6405: 	my $filename;
 6406: 	if (!$symbparm) { $symbparm=&symbread(); }
 6407: 	if ($symbparm) {
 6408: 	    $filename=(&decode_symb($symbparm))[2];
 6409: 	} else {
 6410: 	    $filename=$env{'request.filename'};
 6411: 	}
 6412: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6413: 	if (defined($metadata)) { return $metadata; }
 6414: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6415: 	if (defined($metadata)) { return $metadata; }
 6416: 
 6417: # ---------------------------------------------- fourth, look in rest pf course
 6418: 	if ($symbparm && defined($courseid) && 
 6419: 	    $courseid eq $env{'request.course.id'}) {
 6420: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6421: 				     $env{'course.'.$courseid.'.domain'},
 6422: 				     'course',
 6423: 				     ($courselevelm,$courselevel));
 6424: 	    if (defined($coursereply)) { return $coursereply; }
 6425: 	}
 6426: # ------------------------------------------------------------------ Cascade up
 6427: 	unless ($space eq '0') {
 6428: 	    my @parts=split(/_/,$space);
 6429: 	    my $id=pop(@parts);
 6430: 	    my $part=join('_',@parts);
 6431: 	    if ($part eq '') { $part='0'; }
 6432: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6433: 				 $symbparm,$udom,$uname,$section,1);
 6434: 	    if (defined($partgeneral)) { return $partgeneral; }
 6435: 	}
 6436: 	if ($recurse) { return undef; }
 6437: 	my $pack_def=&packages_tab_default($filename,$varname);
 6438: 	if (defined($pack_def)) { return $pack_def; }
 6439: 
 6440: # ---------------------------------------------------- Any other user namespace
 6441:     } elsif ($realm eq 'environment') {
 6442: # ----------------------------------------------------------------- environment
 6443: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6444: 	    return $env{'environment.'.$spacequalifierrest};
 6445: 	} else {
 6446: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6447: 		return '';
 6448: 	    }
 6449: 	    my %returnhash=&userenvironment($udom,$uname,
 6450: 					    $spacequalifierrest);
 6451: 	    return $returnhash{$spacequalifierrest};
 6452: 	}
 6453:     } elsif ($realm eq 'system') {
 6454: # ----------------------------------------------------------------- system.time
 6455: 	if ($space eq 'time') {
 6456: 	    return time;
 6457:         }
 6458:     } elsif ($realm eq 'server') {
 6459: # ----------------------------------------------------------------- system.time
 6460: 	if ($space eq 'name') {
 6461: 	    return $ENV{'SERVER_NAME'};
 6462:         }
 6463:     }
 6464:     return '';
 6465: }
 6466: 
 6467: sub check_group_parms {
 6468:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6469:     my @groupitems = ();
 6470:     my $resultitem;
 6471:     my @levels = ($symbparm,$mapparm,$what);
 6472:     foreach my $group (@{$groups}) {
 6473:         foreach my $level (@levels) {
 6474:              my $item = $courseid.'.['.$group.'].'.$level;
 6475:              push(@groupitems,$item);
 6476:         }
 6477:     }
 6478:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6479:                             $env{'course.'.$courseid.'.domain'},
 6480:                                      'course',@groupitems);
 6481:     return $coursereply;
 6482: }
 6483: 
 6484: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6485:     my ($courseid,@groups) = @_;
 6486:     @groups = sort(@groups);
 6487:     return @groups;
 6488: }
 6489: 
 6490: sub packages_tab_default {
 6491:     my ($uri,$varname)=@_;
 6492:     my (undef,$part,$name)=split(/\./,$varname);
 6493: 
 6494:     my (@extension,@specifics,$do_default);
 6495:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6496: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6497: 	if ($pack_type eq 'default') {
 6498: 	    $do_default=1;
 6499: 	} elsif ($pack_type eq 'extension') {
 6500: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6501: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6502: 	    # only look at packages defaults for packages that this id is
 6503: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6504: 	}
 6505:     }
 6506:     # first look for a package that matches the requested part id
 6507:     foreach my $package (@specifics) {
 6508: 	my (undef,$pack_type,$pack_part)=@{$package};
 6509: 	next if ($pack_part ne $part);
 6510: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6511: 	    return $packagetab{"$pack_type&$name&default"};
 6512: 	}
 6513:     }
 6514:     # look for any possible matching non extension_ package
 6515:     foreach my $package (@specifics) {
 6516: 	my (undef,$pack_type,$pack_part)=@{$package};
 6517: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6518: 	    return $packagetab{"$pack_type&$name&default"};
 6519: 	}
 6520: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6521: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6522: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6523: 	}
 6524:     }
 6525:     # look for any posible extension_ match
 6526:     foreach my $package (@extension) {
 6527: 	my ($package,$pack_type)=@{$package};
 6528: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6529: 	    return $packagetab{"$pack_type&$name&default"};
 6530: 	}
 6531: 	if (defined($packagetab{$package."&$name&default"})) {
 6532: 	    return $packagetab{$package."&$name&default"};
 6533: 	}
 6534:     }
 6535:     # look for a global default setting
 6536:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6537: 	return $packagetab{"default&$name&default"};
 6538:     }
 6539:     return undef;
 6540: }
 6541: 
 6542: sub add_prefix_and_part {
 6543:     my ($prefix,$part)=@_;
 6544:     my $keyroot;
 6545:     if (defined($prefix) && $prefix !~ /^__/) {
 6546: 	# prefix that has a part already
 6547: 	$keyroot=$prefix;
 6548:     } elsif (defined($prefix)) {
 6549: 	# prefix that is missing a part
 6550: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6551:     } else {
 6552: 	# no prefix at all
 6553: 	if (defined($part)) { $keyroot='_'.$part; }
 6554:     }
 6555:     return $keyroot;
 6556: }
 6557: 
 6558: # ---------------------------------------------------------------- Get metadata
 6559: 
 6560: my %metaentry;
 6561: sub metadata {
 6562:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6563:     $uri=&declutter($uri);
 6564:     # if it is a non metadata possible uri return quickly
 6565:     if (($uri eq '') || 
 6566: 	(($uri =~ m|^/*adm/|) && 
 6567: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6568:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6569: 	($uri =~ m|home/$match_username/public_html/|)) {
 6570: 	return undef;
 6571:     }
 6572:     my $filename=$uri;
 6573:     $uri=~s/\.meta$//;
 6574: #
 6575: # Is the metadata already cached?
 6576: # Look at timestamp of caching
 6577: # Everything is cached by the main uri, libraries are never directly cached
 6578: #
 6579:     if (!defined($liburi)) {
 6580: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6581: 	if (defined($cached)) { return $result->{':'.$what}; }
 6582:     }
 6583:     {
 6584: #
 6585: # Is this a recursive call for a library?
 6586: #
 6587: #	if (! exists($metacache{$uri})) {
 6588: #	    $metacache{$uri}={};
 6589: #	}
 6590:         if ($liburi) {
 6591: 	    $liburi=&declutter($liburi);
 6592:             $filename=$liburi;
 6593:         } else {
 6594: 	    &devalidate_cache_new('meta',$uri);
 6595: 	    undef(%metaentry);
 6596: 	}
 6597:         my %metathesekeys=();
 6598:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6599: 	my $metastring;
 6600: 	if ($uri !~ m -^(editupload)/-) {
 6601: 	    my $file=&filelocation('',&clutter($filename));
 6602: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6603: 	    $metastring=&getfile($file);
 6604: 	}
 6605:         my $parser=HTML::LCParser->new(\$metastring);
 6606:         my $token;
 6607:         undef %metathesekeys;
 6608:         while ($token=$parser->get_token) {
 6609: 	    if ($token->[0] eq 'S') {
 6610: 		if (defined($token->[2]->{'package'})) {
 6611: #
 6612: # This is a package - get package info
 6613: #
 6614: 		    my $package=$token->[2]->{'package'};
 6615: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6616: 		    if (defined($token->[2]->{'id'})) { 
 6617: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6618: 		    }
 6619: 		    if ($metaentry{':packages'}) {
 6620: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6621: 		    } else {
 6622: 			$metaentry{':packages'}=$package.$keyroot;
 6623: 		    }
 6624: 		    foreach my $pack_entry (keys(%packagetab)) {
 6625: 			my $part=$keyroot;
 6626: 			$part=~s/^\_//;
 6627: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6628: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6629: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6630: 			    # ignore package.tab specified default values
 6631:                             # here &package_tab_default() will fetch those
 6632: 			    if ($subp eq 'default') { next; }
 6633: 			    my $value=$packagetab{$pack_entry};
 6634: 			    my $unikey;
 6635: 			    if ($pack =~ /_0$/) {
 6636: 				$unikey='parameter_0_'.$name;
 6637: 				$part=0;
 6638: 			    } else {
 6639: 				$unikey='parameter'.$keyroot.'_'.$name;
 6640: 			    }
 6641: 			    if ($subp eq 'display') {
 6642: 				$value.=' [Part: '.$part.']';
 6643: 			    }
 6644: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6645: 			    $metathesekeys{$unikey}=1;
 6646: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6647: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6648: 			    }
 6649: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6650: 				$metaentry{':'.$unikey}=
 6651: 				    $metaentry{':'.$unikey.'.default'};
 6652: 			    }
 6653: 			}
 6654: 		    }
 6655: 		} else {
 6656: #
 6657: # This is not a package - some other kind of start tag
 6658: #
 6659: 		    my $entry=$token->[1];
 6660: 		    my $unikey;
 6661: 		    if ($entry eq 'import') {
 6662: 			$unikey='';
 6663: 		    } else {
 6664: 			$unikey=$entry;
 6665: 		    }
 6666: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6667: 
 6668: 		    if (defined($token->[2]->{'id'})) { 
 6669: 			$unikey.='_'.$token->[2]->{'id'}; 
 6670: 		    }
 6671: 
 6672: 		    if ($entry eq 'import') {
 6673: #
 6674: # Importing a library here
 6675: #
 6676: 			if ($depthcount<20) {
 6677: 			    my $location=$parser->get_text('/import');
 6678: 			    my $dir=$filename;
 6679: 			    $dir=~s|[^/]*$||;
 6680: 			    $location=&filelocation($dir,$location);
 6681: 			    my $metadata = 
 6682: 				&metadata($uri,'keys', $location,$unikey,
 6683: 					  $depthcount+1);
 6684: 			    foreach my $meta (split(',',$metadata)) {
 6685: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6686: 				$metathesekeys{$meta}=1;
 6687: 			    }
 6688: 			}
 6689: 		    } else { 
 6690: 			
 6691: 			if (defined($token->[2]->{'name'})) { 
 6692: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6693: 			}
 6694: 			$metathesekeys{$unikey}=1;
 6695: 			foreach my $param (@{$token->[3]}) {
 6696: 			    $metaentry{':'.$unikey.'.'.$param} =
 6697: 				$token->[2]->{$param};
 6698: 			}
 6699: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6700: 			my $default=$metaentry{':'.$unikey.'.default'};
 6701: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6702: 		 # only ws inside the tag, and not in default, so use default
 6703: 		 # as value
 6704: 			    $metaentry{':'.$unikey}=$default;
 6705: 			} elsif ( $internaltext =~ /\S/ ) {
 6706: 		  # something interesting inside the tag
 6707: 			    $metaentry{':'.$unikey}=$internaltext;
 6708: 			} else {
 6709: 		  # no interesting values, don't set a default
 6710: 			}
 6711: # end of not-a-package not-a-library import
 6712: 		    }
 6713: # end of not-a-package start tag
 6714: 		}
 6715: # the next is the end of "start tag"
 6716: 	    }
 6717: 	}
 6718: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6719: 	$extension = lc($extension);
 6720: 	if ($extension eq 'htm') { $extension='html'; }
 6721: 
 6722: 	foreach my $key (keys(%packagetab)) {
 6723: 	    #no specific packages #how's our extension
 6724: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6725: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6726: 					 \%metathesekeys);
 6727: 	}
 6728: 
 6729: 	if (!exists($metaentry{':packages'})
 6730: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 6731: 	    foreach my $key (keys(%packagetab)) {
 6732: 		#no specific packages well let's get default then
 6733: 		if ($key!~/^default&/) { next; }
 6734: 		&metadata_create_package_def($uri,$key,'default',
 6735: 					     \%metathesekeys);
 6736: 	    }
 6737: 	}
 6738: # are there custom rights to evaluate
 6739: 	if ($metaentry{':copyright'} eq 'custom') {
 6740: 
 6741:     #
 6742:     # Importing a rights file here
 6743:     #
 6744: 	    unless ($depthcount) {
 6745: 		my $location=$metaentry{':customdistributionfile'};
 6746: 		my $dir=$filename;
 6747: 		$dir=~s|[^/]*$||;
 6748: 		$location=&filelocation($dir,$location);
 6749: 		my $rights_metadata =
 6750: 		    &metadata($uri,'keys',$location,'_rights',
 6751: 			      $depthcount+1);
 6752: 		foreach my $rights (split(',',$rights_metadata)) {
 6753: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6754: 		    $metathesekeys{$rights}=1;
 6755: 		}
 6756: 	    }
 6757: 	}
 6758: 	# uniqifiy package listing
 6759: 	my %seen;
 6760: 	my @uniq_packages =
 6761: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6762: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6763: 
 6764: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6765: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6766: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6767: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6768: # this is the end of "was not already recently cached
 6769:     }
 6770:     return $metaentry{':'.$what};
 6771: }
 6772: 
 6773: sub metadata_create_package_def {
 6774:     my ($uri,$key,$package,$metathesekeys)=@_;
 6775:     my ($pack,$name,$subp)=split(/\&/,$key);
 6776:     if ($subp eq 'default') { next; }
 6777:     
 6778:     if (defined($metaentry{':packages'})) {
 6779: 	$metaentry{':packages'}.=','.$package;
 6780:     } else {
 6781: 	$metaentry{':packages'}=$package;
 6782:     }
 6783:     my $value=$packagetab{$key};
 6784:     my $unikey;
 6785:     $unikey='parameter_0_'.$name;
 6786:     $metaentry{':'.$unikey.'.part'}=0;
 6787:     $$metathesekeys{$unikey}=1;
 6788:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6789: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6790:     }
 6791:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6792: 	$metaentry{':'.$unikey}=
 6793: 	    $metaentry{':'.$unikey.'.default'};
 6794:     }
 6795: }
 6796: 
 6797: sub metadata_generate_part0 {
 6798:     my ($metadata,$metacache,$uri) = @_;
 6799:     my %allnames;
 6800:     foreach my $metakey (keys(%$metadata)) {
 6801: 	if ($metakey=~/^parameter\_(.*)/) {
 6802: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6803: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6804: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6805: 	    $allnames{$name}=$part;
 6806: 	  }
 6807: 	}
 6808:     }
 6809:     foreach my $name (keys(%allnames)) {
 6810:       $$metadata{"parameter_0_$name"}=1;
 6811:       my $key=":parameter_0_$name";
 6812:       $$metacache{"$key.part"}='0';
 6813:       $$metacache{"$key.name"}=$name;
 6814:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6815: 					   $allnames{$name}.'_'.$name.
 6816: 					   '.type'};
 6817:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6818: 			     '.display'};
 6819:       my $expr='[Part: '.$allnames{$name}.']';
 6820:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6821:       $$metacache{"$key.display"}=$olddis;
 6822:     }
 6823: }
 6824: 
 6825: # ------------------------------------------------------ Devalidate title cache
 6826: 
 6827: sub devalidate_title_cache {
 6828:     my ($url)=@_;
 6829:     if (!$env{'request.course.id'}) { return; }
 6830:     my $symb=&symbread($url);
 6831:     if (!$symb) { return; }
 6832:     my $key=$env{'request.course.id'}."\0".$symb;
 6833:     &devalidate_cache_new('title',$key);
 6834: }
 6835: 
 6836: # ------------------------------------------------- Get the title of a resource
 6837: 
 6838: sub gettitle {
 6839:     my $urlsymb=shift;
 6840:     my $symb=&symbread($urlsymb);
 6841:     if ($symb) {
 6842: 	my $key=$env{'request.course.id'}."\0".$symb;
 6843: 	my ($result,$cached)=&is_cached_new('title',$key);
 6844: 	if (defined($cached)) { 
 6845: 	    return $result;
 6846: 	}
 6847: 	my ($map,$resid,$url)=&decode_symb($symb);
 6848: 	my $title='';
 6849: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 6850: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 6851: 	} else {
 6852: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6853: 		    &GDBM_READER(),0640)) {
 6854: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6855: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 6856: 		untie(%bighash);
 6857: 	    }
 6858: 	}
 6859: 	$title=~s/\&colon\;/\:/gs;
 6860: 	if ($title) {
 6861: 	    return &do_cache_new('title',$key,$title,600);
 6862: 	}
 6863: 	$urlsymb=$url;
 6864:     }
 6865:     my $title=&metadata($urlsymb,'title');
 6866:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6867:     return $title;
 6868: }
 6869: 
 6870: sub get_slot {
 6871:     my ($which,$cnum,$cdom)=@_;
 6872:     if (!$cnum || !$cdom) {
 6873: 	(undef,my $courseid)=&whichuser();
 6874: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6875: 	$cnum=$env{'course.'.$courseid.'.num'};
 6876:     }
 6877:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6878:     my %slotinfo;
 6879:     if (exists($remembered{$key})) {
 6880: 	$slotinfo{$which} = $remembered{$key};
 6881:     } else {
 6882: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6883: 	&Apache::lonhomework::showhash(%slotinfo);
 6884: 	my ($tmp)=keys(%slotinfo);
 6885: 	if ($tmp=~/^error:/) { return (); }
 6886: 	$remembered{$key} = $slotinfo{$which};
 6887:     }
 6888:     if (ref($slotinfo{$which}) eq 'HASH') {
 6889: 	return %{$slotinfo{$which}};
 6890:     }
 6891:     return $slotinfo{$which};
 6892: }
 6893: # ------------------------------------------------- Update symbolic store links
 6894: 
 6895: sub symblist {
 6896:     my ($mapname,%newhash)=@_;
 6897:     $mapname=&deversion(&declutter($mapname));
 6898:     my %hash;
 6899:     if (($env{'request.course.fn'}) && (%newhash)) {
 6900:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6901:                       &GDBM_WRCREAT(),0640)) {
 6902: 	    foreach my $url (keys %newhash) {
 6903: 		next if ($url eq 'last_known'
 6904: 			 && $env{'form.no_update_last_known'});
 6905: 		$hash{declutter($url)}=&encode_symb($mapname,
 6906: 						    $newhash{$url}->[1],
 6907: 						    $newhash{$url}->[0]);
 6908:             }
 6909:             if (untie(%hash)) {
 6910: 		return 'ok';
 6911:             }
 6912:         }
 6913:     }
 6914:     return 'error';
 6915: }
 6916: 
 6917: # --------------------------------------------------------------- Verify a symb
 6918: 
 6919: sub symbverify {
 6920:     my ($symb,$thisurl)=@_;
 6921:     my $thisfn=$thisurl;
 6922:     $thisfn=&declutter($thisfn);
 6923: # direct jump to resource in page or to a sequence - will construct own symbs
 6924:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6925: # check URL part
 6926:     my ($map,$resid,$url)=&decode_symb($symb);
 6927: 
 6928:     unless ($url eq $thisfn) { return 0; }
 6929: 
 6930:     $symb=&symbclean($symb);
 6931:     $thisurl=&deversion($thisurl);
 6932:     $thisfn=&deversion($thisfn);
 6933: 
 6934:     my %bighash;
 6935:     my $okay=0;
 6936: 
 6937:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6938:                             &GDBM_READER(),0640)) {
 6939:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6940:         unless ($ids) { 
 6941:            $ids=$bighash{'ids_/'.$thisurl};
 6942:         }
 6943:         if ($ids) {
 6944: # ------------------------------------------------------------------- Has ID(s)
 6945: 	    foreach my $id (split(/\,/,$ids)) {
 6946: 	       my ($mapid,$resid)=split(/\./,$id);
 6947:                if (
 6948:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6949:    eq $symb) { 
 6950: 		   if (($env{'request.role.adv'}) ||
 6951: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6952: 		       $okay=1; 
 6953: 		   }
 6954: 	       }
 6955: 	   }
 6956:         }
 6957: 	untie(%bighash);
 6958:     }
 6959:     return $okay;
 6960: }
 6961: 
 6962: # --------------------------------------------------------------- Clean-up symb
 6963: 
 6964: sub symbclean {
 6965:     my $symb=shift;
 6966:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6967: # remove version from map
 6968:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6969: 
 6970: # remove version from URL
 6971:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6972: 
 6973: # remove wrapper
 6974: 
 6975:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6976:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6977:     return $symb;
 6978: }
 6979: 
 6980: # ---------------------------------------------- Split symb to find map and url
 6981: 
 6982: sub encode_symb {
 6983:     my ($map,$resid,$url)=@_;
 6984:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6985: }
 6986: 
 6987: sub decode_symb {
 6988:     my $symb=shift;
 6989:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6990:     my ($map,$resid,$url)=split(/___/,$symb);
 6991:     return (&fixversion($map),$resid,&fixversion($url));
 6992: }
 6993: 
 6994: sub fixversion {
 6995:     my $fn=shift;
 6996:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6997:     my %bighash;
 6998:     my $uri=&clutter($fn);
 6999:     my $key=$env{'request.course.id'}.'_'.$uri;
 7000: # is this cached?
 7001:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7002:     if (defined($cached)) { return $result; }
 7003: # unfortunately not cached, or expired
 7004:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7005: 	    &GDBM_READER(),0640)) {
 7006:  	if ($bighash{'version_'.$uri}) {
 7007:  	    my $version=$bighash{'version_'.$uri};
 7008:  	    unless (($version eq 'mostrecent') || 
 7009: 		    ($version==&getversion($uri))) {
 7010:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7011:  	    }
 7012:  	}
 7013:  	untie %bighash;
 7014:     }
 7015:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7016: }
 7017: 
 7018: sub deversion {
 7019:     my $url=shift;
 7020:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7021:     return $url;
 7022: }
 7023: 
 7024: # ------------------------------------------------------ Return symb list entry
 7025: 
 7026: sub symbread {
 7027:     my ($thisfn,$donotrecurse)=@_;
 7028:     my $cache_str='request.symbread.cached.'.$thisfn;
 7029:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7030: # no filename provided? try from environment
 7031:     unless ($thisfn) {
 7032:         if ($env{'request.symb'}) {
 7033: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7034: 	}
 7035: 	$thisfn=$env{'request.filename'};
 7036:     }
 7037:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7038: # is that filename actually a symb? Verify, clean, and return
 7039:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7040: 	if (&symbverify($thisfn,$1)) {
 7041: 	    return $env{$cache_str}=&symbclean($thisfn);
 7042: 	}
 7043:     }
 7044:     $thisfn=declutter($thisfn);
 7045:     my %hash;
 7046:     my %bighash;
 7047:     my $syval='';
 7048:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7049:         my $targetfn = $thisfn;
 7050:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7051:             $targetfn = 'adm/wrapper/'.$thisfn;
 7052:         }
 7053: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7054: 	    $targetfn=$1;
 7055: 	}
 7056:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7057:                       &GDBM_READER(),0640)) {
 7058: 	    $syval=$hash{$targetfn};
 7059:             untie(%hash);
 7060:         }
 7061: # ---------------------------------------------------------- There was an entry
 7062:         if ($syval) {
 7063: 	    #unless ($syval=~/\_\d+$/) {
 7064: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7065: 		    #&appenv('request.ambiguous' => $thisfn);
 7066: 		    #return $env{$cache_str}='';
 7067: 		#}    
 7068: 		#$syval.=$1;
 7069: 	    #}
 7070:         } else {
 7071: # ------------------------------------------------------- Was not in symb table
 7072:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7073:                             &GDBM_READER(),0640)) {
 7074: # ---------------------------------------------- Get ID(s) for current resource
 7075:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7076:               unless ($ids) { 
 7077:                  $ids=$bighash{'ids_/'.$thisfn};
 7078:               }
 7079:               unless ($ids) {
 7080: # alias?
 7081: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7082:               }
 7083:               if ($ids) {
 7084: # ------------------------------------------------------------------- Has ID(s)
 7085:                  my @possibilities=split(/\,/,$ids);
 7086:                  if ($#possibilities==0) {
 7087: # ----------------------------------------------- There is only one possibility
 7088: 		     my ($mapid,$resid)=split(/\./,$ids);
 7089: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7090: 						    $resid,$thisfn);
 7091:                  } elsif (!$donotrecurse) {
 7092: # ------------------------------------------ There is more than one possibility
 7093:                      my $realpossible=0;
 7094:                      foreach my $id (@possibilities) {
 7095: 			 my $file=$bighash{'src_'.$id};
 7096:                          if (&allowed('bre',$file)) {
 7097:          		    my ($mapid,$resid)=split(/\./,$id);
 7098:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7099: 				$realpossible++;
 7100:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7101: 						    $resid,$thisfn);
 7102:                             }
 7103: 			 }
 7104:                      }
 7105: 		     if ($realpossible!=1) { $syval=''; }
 7106:                  } else {
 7107:                      $syval='';
 7108:                  }
 7109: 	      }
 7110:               untie(%bighash)
 7111:            }
 7112:         }
 7113:         if ($syval) {
 7114: 	    return $env{$cache_str}=$syval;
 7115:         }
 7116:     }
 7117:     &appenv('request.ambiguous' => $thisfn);
 7118:     return $env{$cache_str}='';
 7119: }
 7120: 
 7121: # ---------------------------------------------------------- Return random seed
 7122: 
 7123: sub numval {
 7124:     my $txt=shift;
 7125:     $txt=~tr/A-J/0-9/;
 7126:     $txt=~tr/a-j/0-9/;
 7127:     $txt=~tr/K-T/0-9/;
 7128:     $txt=~tr/k-t/0-9/;
 7129:     $txt=~tr/U-Z/0-5/;
 7130:     $txt=~tr/u-z/0-5/;
 7131:     $txt=~s/\D//g;
 7132:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7133:     return int($txt);
 7134: }
 7135: 
 7136: sub numval2 {
 7137:     my $txt=shift;
 7138:     $txt=~tr/A-J/0-9/;
 7139:     $txt=~tr/a-j/0-9/;
 7140:     $txt=~tr/K-T/0-9/;
 7141:     $txt=~tr/k-t/0-9/;
 7142:     $txt=~tr/U-Z/0-5/;
 7143:     $txt=~tr/u-z/0-5/;
 7144:     $txt=~s/\D//g;
 7145:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7146:     my $total;
 7147:     foreach my $val (@txts) { $total+=$val; }
 7148:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7149:     return int($total);
 7150: }
 7151: 
 7152: sub numval3 {
 7153:     use integer;
 7154:     my $txt=shift;
 7155:     $txt=~tr/A-J/0-9/;
 7156:     $txt=~tr/a-j/0-9/;
 7157:     $txt=~tr/K-T/0-9/;
 7158:     $txt=~tr/k-t/0-9/;
 7159:     $txt=~tr/U-Z/0-5/;
 7160:     $txt=~tr/u-z/0-5/;
 7161:     $txt=~s/\D//g;
 7162:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7163:     my $total;
 7164:     foreach my $val (@txts) { $total+=$val; }
 7165:     if ($_64bit) { $total=(($total<<32)>>32); }
 7166:     return $total;
 7167: }
 7168: 
 7169: sub digest {
 7170:     my ($data)=@_;
 7171:     my $digest=&Digest::MD5::md5($data);
 7172:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7173:     my ($e,$f);
 7174:     {
 7175:         use integer;
 7176:         $e=($a+$b);
 7177:         $f=($c+$d);
 7178:         if ($_64bit) {
 7179:             $e=(($e<<32)>>32);
 7180:             $f=(($f<<32)>>32);
 7181:         }
 7182:     }
 7183:     if (wantarray) {
 7184: 	return ($e,$f);
 7185:     } else {
 7186: 	my $g;
 7187: 	{
 7188: 	    use integer;
 7189: 	    $g=($e+$f);
 7190: 	    if ($_64bit) {
 7191: 		$g=(($g<<32)>>32);
 7192: 	    }
 7193: 	}
 7194: 	return $g;
 7195:     }
 7196: }
 7197: 
 7198: sub latest_rnd_algorithm_id {
 7199:     return '64bit5';
 7200: }
 7201: 
 7202: sub get_rand_alg {
 7203:     my ($courseid)=@_;
 7204:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7205:     if ($courseid) {
 7206: 	return $env{"course.$courseid.rndseed"};
 7207:     }
 7208:     return &latest_rnd_algorithm_id();
 7209: }
 7210: 
 7211: sub validCODE {
 7212:     my ($CODE)=@_;
 7213:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7214:     return 0;
 7215: }
 7216: 
 7217: sub getCODE {
 7218:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7219:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7220: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7221: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7222: 	return $Apache::lonhomework::history{'resource.CODE'};
 7223:     }
 7224:     return undef;
 7225: }
 7226: 
 7227: sub rndseed {
 7228:     my ($symb,$courseid,$domain,$username)=@_;
 7229:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7230:     if (!defined($symb)) {
 7231: 	unless ($symb=$wsymb) { return time; }
 7232:     }
 7233:     if (!$courseid) { $courseid=$wcourseid; }
 7234:     if (!$domain) { $domain=$wdomain; }
 7235:     if (!$username) { $username=$wusername }
 7236:     my $which=&get_rand_alg();
 7237: 
 7238:     if (defined(&getCODE())) {
 7239: 	if ($which eq '64bit5') {
 7240: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7241: 	} elsif ($which eq '64bit4') {
 7242: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7243: 	} else {
 7244: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7245: 	}
 7246:     } elsif ($which eq '64bit5') {
 7247: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7248:     } elsif ($which eq '64bit4') {
 7249: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7250:     } elsif ($which eq '64bit3') {
 7251: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7252:     } elsif ($which eq '64bit2') {
 7253: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7254:     } elsif ($which eq '64bit') {
 7255: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7256:     }
 7257:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7258: }
 7259: 
 7260: sub rndseed_32bit {
 7261:     my ($symb,$courseid,$domain,$username)=@_;
 7262:     {
 7263: 	use integer;
 7264: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7265: 	my $symbseed=numval($symb) << 22;
 7266: 	my $namechck=unpack("%32C*",$username) << 17;
 7267: 	my $nameseed=numval($username) << 12;
 7268: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7269: 	my $courseseed=unpack("%32C*",$courseid);
 7270: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7271: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7272: 	#&logthis("rndseed :$num:$symb");
 7273: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7274: 	return $num;
 7275:     }
 7276: }
 7277: 
 7278: sub rndseed_64bit {
 7279:     my ($symb,$courseid,$domain,$username)=@_;
 7280:     {
 7281: 	use integer;
 7282: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7283: 	my $symbseed=numval($symb) << 10;
 7284: 	my $namechck=unpack("%32S*",$username);
 7285: 	
 7286: 	my $nameseed=numval($username) << 21;
 7287: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7288: 	my $courseseed=unpack("%32S*",$courseid);
 7289: 	
 7290: 	my $num1=$symbchck+$symbseed+$namechck;
 7291: 	my $num2=$nameseed+$domainseed+$courseseed;
 7292: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7293: 	#&logthis("rndseed :$num:$symb");
 7294: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7295: 	return "$num1,$num2";
 7296:     }
 7297: }
 7298: 
 7299: sub rndseed_64bit2 {
 7300:     my ($symb,$courseid,$domain,$username)=@_;
 7301:     {
 7302: 	use integer;
 7303: 	# strings need to be an even # of cahracters long, it it is odd the
 7304:         # last characters gets thrown away
 7305: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7306: 	my $symbseed=numval($symb) << 10;
 7307: 	my $namechck=unpack("%32S*",$username.' ');
 7308: 	
 7309: 	my $nameseed=numval($username) << 21;
 7310: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7311: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7312: 	
 7313: 	my $num1=$symbchck+$symbseed+$namechck;
 7314: 	my $num2=$nameseed+$domainseed+$courseseed;
 7315: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7316: 	#&logthis("rndseed :$num:$symb");
 7317: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7318: 	return "$num1,$num2";
 7319:     }
 7320: }
 7321: 
 7322: sub rndseed_64bit3 {
 7323:     my ($symb,$courseid,$domain,$username)=@_;
 7324:     {
 7325: 	use integer;
 7326: 	# strings need to be an even # of cahracters long, it it is odd the
 7327:         # last characters gets thrown away
 7328: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7329: 	my $symbseed=numval2($symb) << 10;
 7330: 	my $namechck=unpack("%32S*",$username.' ');
 7331: 	
 7332: 	my $nameseed=numval2($username) << 21;
 7333: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7334: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7335: 	
 7336: 	my $num1=$symbchck+$symbseed+$namechck;
 7337: 	my $num2=$nameseed+$domainseed+$courseseed;
 7338: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7339: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7340: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7341: 	
 7342: 	return "$num1:$num2";
 7343:     }
 7344: }
 7345: 
 7346: sub rndseed_64bit4 {
 7347:     my ($symb,$courseid,$domain,$username)=@_;
 7348:     {
 7349: 	use integer;
 7350: 	# strings need to be an even # of cahracters long, it it is odd the
 7351:         # last characters gets thrown away
 7352: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7353: 	my $symbseed=numval3($symb) << 10;
 7354: 	my $namechck=unpack("%32S*",$username.' ');
 7355: 	
 7356: 	my $nameseed=numval3($username) << 21;
 7357: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7358: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7359: 	
 7360: 	my $num1=$symbchck+$symbseed+$namechck;
 7361: 	my $num2=$nameseed+$domainseed+$courseseed;
 7362: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7363: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7364: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7365: 	
 7366: 	return "$num1:$num2";
 7367:     }
 7368: }
 7369: 
 7370: sub rndseed_64bit5 {
 7371:     my ($symb,$courseid,$domain,$username)=@_;
 7372:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7373:     return "$num1:$num2";
 7374: }
 7375: 
 7376: sub rndseed_CODE_64bit {
 7377:     my ($symb,$courseid,$domain,$username)=@_;
 7378:     {
 7379: 	use integer;
 7380: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7381: 	my $symbseed=numval2($symb);
 7382: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7383: 	my $CODEseed=numval(&getCODE());
 7384: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7385: 	my $num1=$symbseed+$CODEchck;
 7386: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7387: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7388: 	#&logthis("rndseed :$num1:$num2:$symb");
 7389: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7390: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7391: 	return "$num1:$num2";
 7392:     }
 7393: }
 7394: 
 7395: sub rndseed_CODE_64bit4 {
 7396:     my ($symb,$courseid,$domain,$username)=@_;
 7397:     {
 7398: 	use integer;
 7399: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7400: 	my $symbseed=numval3($symb);
 7401: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7402: 	my $CODEseed=numval3(&getCODE());
 7403: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7404: 	my $num1=$symbseed+$CODEchck;
 7405: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7406: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7407: 	#&logthis("rndseed :$num1:$num2:$symb");
 7408: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7409: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7410: 	return "$num1:$num2";
 7411:     }
 7412: }
 7413: 
 7414: sub rndseed_CODE_64bit5 {
 7415:     my ($symb,$courseid,$domain,$username)=@_;
 7416:     my $code = &getCODE();
 7417:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7418:     return "$num1:$num2";
 7419: }
 7420: 
 7421: sub setup_random_from_rndseed {
 7422:     my ($rndseed)=@_;
 7423:     if ($rndseed =~/([,:])/) {
 7424: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7425: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7426:     } else {
 7427: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7428:     }
 7429: }
 7430: 
 7431: sub latest_receipt_algorithm_id {
 7432:     return 'receipt3';
 7433: }
 7434: 
 7435: sub recunique {
 7436:     my $fucourseid=shift;
 7437:     my $unique;
 7438:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7439: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7440: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7441:     } else {
 7442: 	$unique=$perlvar{'lonReceipt'};
 7443:     }
 7444:     return unpack("%32C*",$unique);
 7445: }
 7446: 
 7447: sub recprefix {
 7448:     my $fucourseid=shift;
 7449:     my $prefix;
 7450:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7451: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7452: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7453:     } else {
 7454: 	$prefix=$perlvar{'lonHostID'};
 7455:     }
 7456:     return unpack("%32C*",$prefix);
 7457: }
 7458: 
 7459: sub ireceipt {
 7460:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7461: 
 7462:     my $return =&recprefix($fucourseid).'-';
 7463: 
 7464:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7465: 	$env{'request.state'} eq 'construct') {
 7466: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7467: 	return $return;
 7468:     }
 7469: 
 7470:     my $cuname=unpack("%32C*",$funame);
 7471:     my $cudom=unpack("%32C*",$fudom);
 7472:     my $cucourseid=unpack("%32C*",$fucourseid);
 7473:     my $cusymb=unpack("%32C*",$fusymb);
 7474:     my $cunique=&recunique($fucourseid);
 7475:     my $cpart=unpack("%32S*",$part);
 7476:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7477: 
 7478: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7479: 			       
 7480: 	$return.= ($cunique%$cuname+
 7481: 		   $cunique%$cudom+
 7482: 		   $cusymb%$cuname+
 7483: 		   $cusymb%$cudom+
 7484: 		   $cucourseid%$cuname+
 7485: 		   $cucourseid%$cudom+
 7486: 		   $cpart%$cuname+
 7487: 		   $cpart%$cudom);
 7488:     } else {
 7489: 	$return.= ($cunique%$cuname+
 7490: 		   $cunique%$cudom+
 7491: 		   $cusymb%$cuname+
 7492: 		   $cusymb%$cudom+
 7493: 		   $cucourseid%$cuname+
 7494: 		   $cucourseid%$cudom);
 7495:     }
 7496:     return $return;
 7497: }
 7498: 
 7499: sub receipt {
 7500:     my ($part)=@_;
 7501:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7502:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7503: }
 7504: 
 7505: sub whichuser {
 7506:     my ($passedsymb)=@_;
 7507:     my ($symb,$courseid,$domain,$name,$publicuser);
 7508:     if (defined($env{'form.grade_symb'})) {
 7509: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7510: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7511: 	if (!$allowed &&
 7512: 	    exists($env{'request.course.sec'}) &&
 7513: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7514: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7515: 			      '/'.$env{'request.course.sec'});
 7516: 	}
 7517: 	if ($allowed) {
 7518: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7519: 	    $courseid=$tmp_courseid;
 7520: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7521: 	    ($name)=&get_env_multiple('form.grade_username');
 7522: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7523: 	}
 7524:     }
 7525:     if (!$passedsymb) {
 7526: 	$symb=&symbread();
 7527:     } else {
 7528: 	$symb=$passedsymb;
 7529:     }
 7530:     $courseid=$env{'request.course.id'};
 7531:     $domain=$env{'user.domain'};
 7532:     $name=$env{'user.name'};
 7533:     if ($name eq 'public' && $domain eq 'public') {
 7534: 	if (!defined($env{'form.username'})) {
 7535: 	    $env{'form.username'}.=time.rand(10000000);
 7536: 	}
 7537: 	$name.=$env{'form.username'};
 7538:     }
 7539:     return ($symb,$courseid,$domain,$name,$publicuser);
 7540: 
 7541: }
 7542: 
 7543: # ------------------------------------------------------------ Serves up a file
 7544: # returns either the contents of the file or 
 7545: # -1 if the file doesn't exist
 7546: #
 7547: # if the target is a file that was uploaded via DOCS, 
 7548: # a check will be made to see if a current copy exists on the local server,
 7549: # if it does this will be served, otherwise a copy will be retrieved from
 7550: # the home server for the course and stored in /home/httpd/html/userfiles on
 7551: # the local server.   
 7552: 
 7553: sub getfile {
 7554:     my ($file) = @_;
 7555:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7556:     &repcopy($file);
 7557:     return &readfile($file);
 7558: }
 7559: 
 7560: sub repcopy_userfile {
 7561:     my ($file)=@_;
 7562:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7563:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7564:     my ($cdom,$cnum,$filename) = 
 7565: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7566:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7567:     if (-e "$file") {
 7568: # we already have a local copy, check it out
 7569: 	my @fileinfo = stat($file);
 7570: 	my $rtncode;
 7571: 	my $info;
 7572: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7573: 	if ($lwpresp ne 'ok') {
 7574: # there is no such file anymore, even though we had a local copy
 7575: 	    if ($rtncode eq '404') {
 7576: 		unlink($file);
 7577: 	    }
 7578: 	    return -1;
 7579: 	}
 7580: 	if ($info < $fileinfo[9]) {
 7581: # nice, the file we have is up-to-date, just say okay
 7582: 	    return 'ok';
 7583: 	} else {
 7584: # the file is outdated, get rid of it
 7585: 	    unlink($file);
 7586: 	}
 7587:     }
 7588: # one way or the other, at this point, we don't have the file
 7589: # construct the correct path for the file
 7590:     my @parts = ($cdom,$cnum); 
 7591:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7592: 	push @parts, split(/\//,$1);
 7593:     }
 7594:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7595:     foreach my $part (@parts) {
 7596: 	$path .= '/'.$part;
 7597: 	if (!-e $path) {
 7598: 	    mkdir($path,0770);
 7599: 	}
 7600:     }
 7601: # now the path exists for sure
 7602: # get a user agent
 7603:     my $ua=new LWP::UserAgent;
 7604:     my $transferfile=$file.'.in.transfer';
 7605: # FIXME: this should flock
 7606:     if (-e $transferfile) { return 'ok'; }
 7607:     my $request;
 7608:     $uri=~s/^\///;
 7609:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7610:     my $response=$ua->request($request,$transferfile);
 7611: # did it work?
 7612:     if ($response->is_error()) {
 7613: 	unlink($transferfile);
 7614: 	&logthis("Userfile repcopy failed for $uri");
 7615: 	return -1;
 7616:     }
 7617: # worked, rename the transfer file
 7618:     rename($transferfile,$file);
 7619:     return 'ok';
 7620: }
 7621: 
 7622: sub tokenwrapper {
 7623:     my $uri=shift;
 7624:     $uri=~s|^http\://([^/]+)||;
 7625:     $uri=~s|^/||;
 7626:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7627:     my $token=$1;
 7628:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7629:     if ($udom && $uname && $file) {
 7630: 	$file=~s|(\?\.*)*$||;
 7631:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7632:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7633:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7634:                                '&tokenissued='.$perlvar{'lonHostID'};
 7635:     } else {
 7636:         return '/adm/notfound.html';
 7637:     }
 7638: }
 7639: 
 7640: # call with reqtype HEAD: get last modification time
 7641: # call with reqtype GET: get the file contents
 7642: # Do not call this with reqtype GET for large files! It loads everything into memory
 7643: #
 7644: sub getuploaded {
 7645:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7646:     $uri=~s/^\///;
 7647:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7648:     my $ua=new LWP::UserAgent;
 7649:     my $request=new HTTP::Request($reqtype,$uri);
 7650:     my $response=$ua->request($request);
 7651:     $$rtncode = $response->code;
 7652:     if (! $response->is_success()) {
 7653: 	return 'failed';
 7654:     }      
 7655:     if ($reqtype eq 'HEAD') {
 7656: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7657:     } elsif ($reqtype eq 'GET') {
 7658: 	$$info = $response->content;
 7659:     }
 7660:     return 'ok';
 7661: }
 7662: 
 7663: sub readfile {
 7664:     my $file = shift;
 7665:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7666:     my $fh;
 7667:     open($fh,"<$file");
 7668:     my $a='';
 7669:     while (my $line = <$fh>) { $a .= $line; }
 7670:     return $a;
 7671: }
 7672: 
 7673: sub filelocation {
 7674:     my ($dir,$file) = @_;
 7675:     my $location;
 7676:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7677: 
 7678:     if ($file =~ m-^/adm/-) {
 7679: 	$file=~s-^/adm/wrapper/-/-;
 7680: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7681:     }
 7682: 
 7683:     if ($file=~m:^/~:) { # is a contruction space reference
 7684:         $location = $file;
 7685:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7686:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7687: 	# is a correct contruction space reference
 7688:         $location = $file;
 7689:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7690:         my ($udom,$uname,$filename)=
 7691:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7692:         my $home=&homeserver($uname,$udom);
 7693:         my $is_me=0;
 7694:         my @ids=&current_machine_ids();
 7695:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7696:         if ($is_me) {
 7697:   	    $location=&propath($udom,$uname).
 7698:   	      '/userfiles/'.$filename;
 7699:         } else {
 7700:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7701:   	      $udom.'/'.$uname.'/'.$filename;
 7702:         }
 7703:     } elsif ($file =~ m-^/adm/-) {
 7704: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 7705:     } else {
 7706:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7707:         $file=~s:^/res/:/:;
 7708:         if ( !( $file =~ m:^/:) ) {
 7709:             $location = $dir. '/'.$file;
 7710:         } else {
 7711:             $location = '/home/httpd/html/res'.$file;
 7712:         }
 7713:     }
 7714:     $location=~s://+:/:g; # remove duplicate /
 7715:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7716:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7717:     return $location;
 7718: }
 7719: 
 7720: sub hreflocation {
 7721:     my ($dir,$file)=@_;
 7722:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7723: 	$file=filelocation($dir,$file);
 7724:     } elsif ($file=~m-^/adm/-) {
 7725: 	$file=~s-^/adm/wrapper/-/-;
 7726: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7727:     }
 7728:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7729: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7730:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7731: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7732:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7733: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7734: 	    -/uploaded/$1/$2/-x;
 7735:     }
 7736:     return $file;
 7737: }
 7738: 
 7739: sub current_machine_domains {
 7740:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7741: }
 7742: 
 7743: sub machine_domains {
 7744:     my ($hostname) = @_;
 7745:     my @domains;
 7746:     my %hostname = &all_hostnames();
 7747:     while( my($id, $name) = each(%hostname)) {
 7748: #	&logthis("-$id-$name-$hostname-");
 7749: 	if ($hostname eq $name) {
 7750: 	    push(@domains,&host_domain($id));
 7751: 	}
 7752:     }
 7753:     return @domains;
 7754: }
 7755: 
 7756: sub current_machine_ids {
 7757:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7758: }
 7759: 
 7760: sub machine_ids {
 7761:     my ($hostname) = @_;
 7762:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7763:     my @ids;
 7764:     my %name_to_host = &all_names();
 7765:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 7766: 	return @{ $name_to_host{$hostname} };
 7767:     }
 7768:     return;
 7769: }
 7770: 
 7771: sub additional_machine_domains {
 7772:     my @domains;
 7773:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7774:     while( my $line = <$fh>) {
 7775:         $line =~ s/\s//g;
 7776:         push(@domains,$line);
 7777:     }
 7778:     return @domains;
 7779: }
 7780: 
 7781: sub default_login_domain {
 7782:     my $domain = $perlvar{'lonDefDomain'};
 7783:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7784:     foreach my $posdom (&current_machine_domains(),
 7785:                         &additional_machine_domains()) {
 7786:         if (lc($posdom) eq lc($testdomain)) {
 7787:             $domain=$posdom;
 7788:             last;
 7789:         }
 7790:     }
 7791:     return $domain;
 7792: }
 7793: 
 7794: # ------------------------------------------------------------- Declutters URLs
 7795: 
 7796: sub declutter {
 7797:     my $thisfn=shift;
 7798:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7799:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7800:     $thisfn=~s/^\///;
 7801:     $thisfn=~s|^adm/wrapper/||;
 7802:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7803:     $thisfn=~s/^res\///;
 7804:     $thisfn=~s/\?.+$//;
 7805:     return $thisfn;
 7806: }
 7807: 
 7808: # ------------------------------------------------------------- Clutter up URLs
 7809: 
 7810: sub clutter {
 7811:     my $thisfn='/'.&declutter(shift);
 7812:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 7813: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 7814:        $thisfn='/res'.$thisfn; 
 7815:     }
 7816:     if ($thisfn !~m|/adm|) {
 7817: 	if ($thisfn =~ m|/ext/|) {
 7818: 	    $thisfn='/adm/wrapper'.$thisfn;
 7819: 	} else {
 7820: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7821: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7822: 	    if ($embstyle eq 'ssi'
 7823: 		|| ($embstyle eq 'hdn')
 7824: 		|| ($embstyle eq 'rat')
 7825: 		|| ($embstyle eq 'prv')
 7826: 		|| ($embstyle eq 'ign')) {
 7827: 		#do nothing with these
 7828: 	    } elsif (($embstyle eq 'img') 
 7829: 		|| ($embstyle eq 'emb')
 7830: 		|| ($embstyle eq 'wrp')) {
 7831: 		$thisfn='/adm/wrapper'.$thisfn;
 7832: 	    } elsif ($embstyle eq 'unk'
 7833: 		     && $thisfn!~/\.(sequence|page)$/) {
 7834: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7835: 	    } else {
 7836: #		&logthis("Got a blank emb style");
 7837: 	    }
 7838: 	}
 7839:     }
 7840:     return $thisfn;
 7841: }
 7842: 
 7843: sub clutter_with_no_wrapper {
 7844:     my $uri = &clutter(shift);
 7845:     if ($uri =~ m-^/adm/-) {
 7846: 	$uri =~ s-^/adm/wrapper/-/-;
 7847: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7848:     }
 7849:     return $uri;
 7850: }
 7851: 
 7852: sub freeze_escape {
 7853:     my ($value)=@_;
 7854:     if (ref($value)) {
 7855: 	$value=&nfreeze($value);
 7856: 	return '__FROZEN__'.&escape($value);
 7857:     }
 7858:     return &escape($value);
 7859: }
 7860: 
 7861: 
 7862: sub thaw_unescape {
 7863:     my ($value)=@_;
 7864:     if ($value =~ /^__FROZEN__/) {
 7865: 	substr($value,0,10,undef);
 7866: 	$value=&unescape($value);
 7867: 	return &thaw($value);
 7868:     }
 7869:     return &unescape($value);
 7870: }
 7871: 
 7872: sub correct_line_ends {
 7873:     my ($result)=@_;
 7874:     $$result =~s/\r\n/\n/mg;
 7875:     $$result =~s/\r/\n/mg;
 7876: }
 7877: # ================================================================ Main Program
 7878: 
 7879: sub goodbye {
 7880:    &logthis("Starting Shut down");
 7881: #not converted to using infrastruture and probably shouldn't be
 7882:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7883: #converted
 7884: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7885:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7886: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7887: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7888: #1.1 only
 7889: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7890: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7891: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7892: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7893:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7894:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7895:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7896:    &flushcourselogs();
 7897:    &logthis("Shutting down");
 7898: }
 7899: 
 7900: sub get_dns {
 7901:     my ($url,$func,$ignore_cache) = @_;
 7902:     if (!$ignore_cache) {
 7903: 	my ($content,$cached)=
 7904: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7905: 	if ($cached) {
 7906: 	    &$func($content);
 7907: 	    return;
 7908: 	}
 7909:     }
 7910: 
 7911:     my %alldns;
 7912:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7913:     foreach my $dns (<$config>) {
 7914: 	next if ($dns !~ /^\^(\S*)/x);
 7915: 	$alldns{$1} = 1;
 7916:     }
 7917:     while (%alldns) {
 7918: 	my ($dns) = keys(%alldns);
 7919: 	delete($alldns{$dns});
 7920: 	my $ua=new LWP::UserAgent;
 7921: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7922: 	my $response=$ua->request($request);
 7923: 	next if ($response->is_error());
 7924: 	my @content = split("\n",$response->content);
 7925: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7926: 	&$func(\@content);
 7927: 	return;
 7928:     }
 7929:     close($config);
 7930:     my $which = (split('/',$url))[3];
 7931:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 7932:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 7933:     my @content = <$config>;
 7934:     &$func(\@content);
 7935:     return;
 7936: }
 7937: # ------------------------------------------------------------ Read domain file
 7938: {
 7939:     my $loaded;
 7940:     my %domain;
 7941: 
 7942:     sub parse_domain_tab {
 7943: 	my ($lines) = @_;
 7944: 	foreach my $line (@$lines) {
 7945: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7946: 
 7947: 	    chomp($line);
 7948: 	    my ($name,@elements) = split(/:/,$line,9);
 7949: 	    my %this_domain;
 7950: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7951: 			       'lang_def', 'city', 'longi', 'lati',
 7952: 			       'primary') {
 7953: 		$this_domain{$field} = shift(@elements);
 7954: 	    }
 7955: 	    $domain{$name} = \%this_domain;
 7956: 	}
 7957:     }
 7958: 
 7959:     sub reset_domain_info {
 7960: 	undef($loaded);
 7961: 	undef(%domain);
 7962:     }
 7963: 
 7964:     sub load_domain_tab {
 7965: 	my ($ignore_cache) = @_;
 7966: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7967: 	my $fh;
 7968: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7969: 	    my @lines = <$fh>;
 7970: 	    &parse_domain_tab(\@lines);
 7971: 	}
 7972: 	close($fh);
 7973: 	$loaded = 1;
 7974:     }
 7975: 
 7976:     sub domain {
 7977: 	&load_domain_tab() if (!$loaded);
 7978: 
 7979: 	my ($name,$what) = @_;
 7980: 	return if ( !exists($domain{$name}) );
 7981: 
 7982: 	if (!$what) {
 7983: 	    return $domain{$name}{'description'};
 7984: 	}
 7985: 	return $domain{$name}{$what};
 7986:     }
 7987: }
 7988: 
 7989: 
 7990: # ------------------------------------------------------------- Read hosts file
 7991: {
 7992:     my %hostname;
 7993:     my %hostdom;
 7994:     my %libserv;
 7995:     my $loaded;
 7996:     my %name_to_host;
 7997: 
 7998:     sub parse_hosts_tab {
 7999: 	my ($file) = @_;
 8000: 	foreach my $configline (@$file) {
 8001: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8002: 	    next if ($configline =~ /^\^/);
 8003: 	    chomp($configline);
 8004: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8005: 	    $name=~s/\s//g;
 8006: 	    if ($id && $domain && $role && $name) {
 8007: 		$hostname{$id}=$name;
 8008: 		push(@{$name_to_host{$name}}, $id);
 8009: 		$hostdom{$id}=$domain;
 8010: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8011: 	    }
 8012: 	}
 8013:     }
 8014:     
 8015:     sub reset_hosts_info {
 8016: 	&purge_remembered();
 8017: 	&reset_domain_info();
 8018: 	&reset_hosts_ip_info();
 8019: 	undef(%name_to_host);
 8020: 	undef(%hostname);
 8021: 	undef(%hostdom);
 8022: 	undef(%libserv);
 8023: 	undef($loaded);
 8024:     }
 8025: 
 8026:     sub load_hosts_tab {
 8027: 	my ($ignore_cache) = @_;
 8028: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8029: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8030: 	my @config = <$config>;
 8031: 	&parse_hosts_tab(\@config);
 8032: 	close($config);
 8033: 	$loaded=1;
 8034:     }
 8035: 
 8036:     sub hostname {
 8037: 	&load_hosts_tab() if (!$loaded);
 8038: 
 8039: 	my ($lonid) = @_;
 8040: 	return $hostname{$lonid};
 8041:     }
 8042: 
 8043:     sub all_hostnames {
 8044: 	&load_hosts_tab() if (!$loaded);
 8045: 
 8046: 	return %hostname;
 8047:     }
 8048: 
 8049:     sub all_names {
 8050: 	&load_hosts_tab() if (!$loaded);
 8051: 
 8052: 	return %name_to_host;
 8053:     }
 8054: 
 8055:     sub is_library {
 8056: 	&load_hosts_tab() if (!$loaded);
 8057: 
 8058: 	return exists($libserv{$_[0]});
 8059:     }
 8060: 
 8061:     sub all_library {
 8062: 	&load_hosts_tab() if (!$loaded);
 8063: 
 8064: 	return %libserv;
 8065:     }
 8066: 
 8067:     sub get_servers {
 8068: 	&load_hosts_tab() if (!$loaded);
 8069: 
 8070: 	my ($domain,$type) = @_;
 8071: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8072: 	                                          : %hostname;
 8073: 	my %result;
 8074: 	if (ref($domain) eq 'ARRAY') {
 8075: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8076: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8077: 		    $result{$host} = $hostname;
 8078: 		}
 8079: 	    }
 8080: 	} else {
 8081: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8082: 		if ($hostdom{$host} eq $domain) {
 8083: 		    $result{$host} = $hostname;
 8084: 		}
 8085: 	    }
 8086: 	}
 8087: 	return %result;
 8088:     }
 8089: 
 8090:     sub host_domain {
 8091: 	&load_hosts_tab() if (!$loaded);
 8092: 
 8093: 	my ($lonid) = @_;
 8094: 	return $hostdom{$lonid};
 8095:     }
 8096: 
 8097:     sub all_domains {
 8098: 	&load_hosts_tab() if (!$loaded);
 8099: 
 8100: 	my %seen;
 8101: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8102: 	return @uniq;
 8103:     }
 8104: }
 8105: 
 8106: { 
 8107:     my %iphost;
 8108:     my %name_to_ip;
 8109:     my %lonid_to_ip;
 8110: 
 8111:     sub get_hosts_from_ip {
 8112: 	my ($ip) = @_;
 8113: 	my %iphosts = &get_iphost();
 8114: 	if (ref($iphosts{$ip})) {
 8115: 	    return @{$iphosts{$ip}};
 8116: 	}
 8117: 	return;
 8118:     }
 8119:     
 8120:     sub reset_hosts_ip_info {
 8121: 	undef(%iphost);
 8122: 	undef(%name_to_ip);
 8123: 	undef(%lonid_to_ip);
 8124:     }
 8125: 
 8126:     sub get_host_ip {
 8127: 	my ($lonid) = @_;
 8128: 	if (exists($lonid_to_ip{$lonid})) {
 8129: 	    return $lonid_to_ip{$lonid};
 8130: 	}
 8131: 	my $name=&hostname($lonid);
 8132:    	my $ip = gethostbyname($name);
 8133: 	return if (!$ip || length($ip) ne 4);
 8134: 	$ip=inet_ntoa($ip);
 8135: 	$name_to_ip{$name}   = $ip;
 8136: 	$lonid_to_ip{$lonid} = $ip;
 8137: 	return $ip;
 8138:     }
 8139:     
 8140:     sub get_iphost {
 8141: 	my ($ignore_cache) = @_;
 8142: 
 8143: 	if (!$ignore_cache) {
 8144: 	    if (%iphost) {
 8145: 		return %iphost;
 8146: 	    }
 8147: 	    my ($ip_info,$cached)=
 8148: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8149: 	    if ($cached) {
 8150: 		%iphost      = %{$ip_info->[0]};
 8151: 		%name_to_ip  = %{$ip_info->[1]};
 8152: 		%lonid_to_ip = %{$ip_info->[2]};
 8153: 		return %iphost;
 8154: 	    }
 8155: 	}
 8156: 
 8157: 	# get yesterday's info for fallback
 8158: 	my %old_name_to_ip;
 8159: 	my ($ip_info,$cached)=
 8160: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8161: 	if ($cached) {
 8162: 	    %old_name_to_ip = %{$ip_info->[1]};
 8163: 	}
 8164: 
 8165: 	my %name_to_host = &all_names();
 8166: 	foreach my $name (keys(%name_to_host)) {
 8167: 	    my $ip;
 8168: 	    if (!exists($name_to_ip{$name})) {
 8169: 		$ip = gethostbyname($name);
 8170: 		if (!$ip || length($ip) ne 4) {
 8171: 		    if (defined($old_name_to_ip{$name})) {
 8172: 			$ip = $old_name_to_ip{$name};
 8173: 			&logthis("Can't find $name defaulting to old $ip");
 8174: 		    } else {
 8175: 			&logthis("Name $name no IP found");
 8176: 			next;
 8177: 		    }
 8178: 		} else {
 8179: 		    $ip=inet_ntoa($ip);
 8180: 		}
 8181: 		$name_to_ip{$name} = $ip;
 8182: 	    } else {
 8183: 		$ip = $name_to_ip{$name};
 8184: 	    }
 8185: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8186: 		$lonid_to_ip{$id} = $ip;
 8187: 	    }
 8188: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8189: 	}
 8190: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8191: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8192: 				      48*60*60);
 8193: 
 8194: 	return %iphost;
 8195:     }
 8196: }
 8197: 
 8198: BEGIN {
 8199: 
 8200: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8201:     unless ($readit) {
 8202: {
 8203:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8204:     %perlvar = (%perlvar,%{$configvars});
 8205: }
 8206: 
 8207: 
 8208: # ------------------------------------------------------ Read spare server file
 8209: {
 8210:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8211: 
 8212:     while (my $configline=<$config>) {
 8213:        chomp($configline);
 8214:        if ($configline) {
 8215: 	   my ($host,$type) = split(':',$configline,2);
 8216: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8217: 	   push(@{ $spareid{$type} }, $host);
 8218:        }
 8219:     }
 8220:     close($config);
 8221: }
 8222: # ------------------------------------------------------------ Read permissions
 8223: {
 8224:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8225: 
 8226:     while (my $configline=<$config>) {
 8227: 	chomp($configline);
 8228: 	if ($configline) {
 8229: 	    my ($role,$perm)=split(/ /,$configline);
 8230: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8231: 	}
 8232:     }
 8233:     close($config);
 8234: }
 8235: 
 8236: # -------------------------------------------- Read plain texts for permissions
 8237: {
 8238:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8239: 
 8240:     while (my $configline=<$config>) {
 8241: 	chomp($configline);
 8242: 	if ($configline) {
 8243: 	    my ($short,@plain)=split(/:/,$configline);
 8244:             %{$prp{$short}} = ();
 8245: 	    if (@plain > 0) {
 8246:                 $prp{$short}{'std'} = $plain[0];
 8247:                 for (my $i=1; $i<@plain; $i++) {
 8248:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8249:                 }
 8250:             }
 8251: 	}
 8252:     }
 8253:     close($config);
 8254: }
 8255: 
 8256: # ---------------------------------------------------------- Read package table
 8257: {
 8258:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8259: 
 8260:     while (my $configline=<$config>) {
 8261: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8262: 	chomp($configline);
 8263: 	my ($short,$plain)=split(/:/,$configline);
 8264: 	my ($pack,$name)=split(/\&/,$short);
 8265: 	if ($plain ne '') {
 8266: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8267: 	    $packagetab{$short}=$plain; 
 8268: 	}
 8269:     }
 8270:     close($config);
 8271: }
 8272: 
 8273: # ------------- set up temporary directory
 8274: {
 8275:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8276: 
 8277: }
 8278: 
 8279: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8280: 				'compress_threshold'=> 20_000,
 8281:  			        });
 8282: 
 8283: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8284: $dumpcount=0;
 8285: 
 8286: &logtouch();
 8287: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8288: $readit=1;
 8289:     {
 8290: 	use integer;
 8291: 	my $test=(2**32)+1;
 8292: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8293: 	&logthis(" Detected 64bit platform ($_64bit)");
 8294:     }
 8295: }
 8296: }
 8297: 
 8298: 1;
 8299: __END__
 8300: 
 8301: =pod
 8302: 
 8303: =head1 NAME
 8304: 
 8305: Apache::lonnet - Subroutines to ask questions about things in the network.
 8306: 
 8307: =head1 SYNOPSIS
 8308: 
 8309: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8310: 
 8311:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8312: 
 8313: Common parameters:
 8314: 
 8315: =over 4
 8316: 
 8317: =item *
 8318: 
 8319: $uname : an internal username (if $cname expecting a course Id specifically)
 8320: 
 8321: =item *
 8322: 
 8323: $udom : a domain (if $cdom expecting a course's domain specifically)
 8324: 
 8325: =item *
 8326: 
 8327: $symb : a resource instance identifier
 8328: 
 8329: =item *
 8330: 
 8331: $namespace : the name of a .db file that contains the data needed or
 8332: being set.
 8333: 
 8334: =back
 8335: 
 8336: =head1 OVERVIEW
 8337: 
 8338: lonnet provides subroutines which interact with the
 8339: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8340: about classes, users, and resources.
 8341: 
 8342: For many of these objects you can also use this to store data about
 8343: them or modify them in various ways.
 8344: 
 8345: =head2 Symbs
 8346: 
 8347: To identify a specific instance of a resource, LON-CAPA uses symbols
 8348: or "symbs"X<symb>. These identifiers are built from the URL of the
 8349: map, the resource number of the resource in the map, and the URL of
 8350: the resource itself. The latter is somewhat redundant, but might help
 8351: if maps change.
 8352: 
 8353: An example is
 8354: 
 8355:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8356: 
 8357: The respective map entry is
 8358: 
 8359:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8360:   title="Problem 2">
 8361:  </resource>
 8362: 
 8363: Symbs are used by the random number generator, as well as to store and
 8364: restore data specific to a certain instance of for example a problem.
 8365: 
 8366: =head2 Storing And Retrieving Data
 8367: 
 8368: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8369: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8370: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8371: is is the non-critical message twin of cstore. These functions are for
 8372: handlers to store a perl hash to a user's permanent data space in an
 8373: easy manner, and to retrieve it again on another call. It is expected
 8374: that a handler would use this once at the beginning to retrieve data,
 8375: and then again once at the end to send only the new data back.
 8376: 
 8377: The data is stored in the user's data directory on the user's
 8378: homeserver under the ID of the course.
 8379: 
 8380: The hash that is returned by restore will have all of the previous
 8381: value for all of the elements of the hash.
 8382: 
 8383: Example:
 8384: 
 8385:  #creating a hash
 8386:  my %hash;
 8387:  $hash{'foo'}='bar';
 8388: 
 8389:  #storing it
 8390:  &Apache::lonnet::cstore(\%hash);
 8391: 
 8392:  #changing a value
 8393:  $hash{'foo'}='notbar';
 8394: 
 8395:  #adding a new value
 8396:  $hash{'bar'}='foo';
 8397:  &Apache::lonnet::cstore(\%hash);
 8398: 
 8399:  #retrieving the hash
 8400:  my %history=&Apache::lonnet::restore();
 8401: 
 8402:  #print the hash
 8403:  foreach my $key (sort(keys(%history))) {
 8404:    print("\%history{$key} = $history{$key}");
 8405:  }
 8406: 
 8407: Will print out:
 8408: 
 8409:  %history{1:foo} = bar
 8410:  %history{1:keys} = foo:timestamp
 8411:  %history{1:timestamp} = 990455579
 8412:  %history{2:bar} = foo
 8413:  %history{2:foo} = notbar
 8414:  %history{2:keys} = foo:bar:timestamp
 8415:  %history{2:timestamp} = 990455580
 8416:  %history{bar} = foo
 8417:  %history{foo} = notbar
 8418:  %history{timestamp} = 990455580
 8419:  %history{version} = 2
 8420: 
 8421: Note that the special hash entries C<keys>, C<version> and
 8422: C<timestamp> were added to the hash. C<version> will be equal to the
 8423: total number of versions of the data that have been stored. The
 8424: C<timestamp> attribute will be the UNIX time the hash was
 8425: stored. C<keys> is available in every historical section to list which
 8426: keys were added or changed at a specific historical revision of a
 8427: hash.
 8428: 
 8429: B<Warning>: do not store the hash that restore returns directly. This
 8430: will cause a mess since it will restore the historical keys as if the
 8431: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8432: 
 8433: Calling convention:
 8434: 
 8435:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8436:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8437: 
 8438: For more detailed information, see lonnet specific documentation.
 8439: 
 8440: =head1 RETURN MESSAGES
 8441: 
 8442: =over 4
 8443: 
 8444: =item * B<con_lost>: unable to contact remote host
 8445: 
 8446: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8447: when the connection is brought back up
 8448: 
 8449: =item * B<con_failed>: unable to contact remote host and unable to save message
 8450: for later delivery
 8451: 
 8452: =item * B<error:>: an error a occured, a description of the error follows the :
 8453: 
 8454: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8455: that was requested
 8456: 
 8457: =back
 8458: 
 8459: =head1 PUBLIC SUBROUTINES
 8460: 
 8461: =head2 Session Environment Functions
 8462: 
 8463: =over 4
 8464: 
 8465: =item * 
 8466: X<appenv()>
 8467: B<appenv(%hash)>: the value of %hash is written to
 8468: the user envirnoment file, and will be restored for each access this
 8469: user makes during this session, also modifies the %env for the current
 8470: process
 8471: 
 8472: =item *
 8473: X<delenv()>
 8474: B<delenv($regexp)>: removes all items from the session
 8475: environment file that matches the regular expression in $regexp. The
 8476: values are also delted from the current processes %env.
 8477: 
 8478: =item * get_env_multiple($name) 
 8479: 
 8480: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8481: values may be defined and end up as an array ref.
 8482: 
 8483: returns an array of values
 8484: 
 8485: =back
 8486: 
 8487: =head2 User Information
 8488: 
 8489: =over 4
 8490: 
 8491: =item *
 8492: X<queryauthenticate()>
 8493: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8494: authentication scheme
 8495: 
 8496: =item *
 8497: X<authenticate()>
 8498: B<authenticate($uname,$upass,$udom)>: try to
 8499: authenticate user from domain's lib servers (first use the current
 8500: one). C<$upass> should be the users password.
 8501: 
 8502: =item *
 8503: X<homeserver()>
 8504: B<homeserver($uname,$udom)>: find the server which has
 8505: the user's directory and files (there must be only one), this caches
 8506: the answer, and also caches if there is a borken connection.
 8507: 
 8508: =item *
 8509: X<idget()>
 8510: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8511: (IDs are a unique resource in a domain, there must be only 1 ID per
 8512: username, and only 1 username per ID in a specific domain) (returns
 8513: hash: id=>name,id=>name)
 8514: 
 8515: =item *
 8516: X<idrget()>
 8517: B<idrget($udom,@unames)>: find the IDs behind a list of
 8518: usernames (returns hash: name=>id,name=>id)
 8519: 
 8520: =item *
 8521: X<idput()>
 8522: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8523: 
 8524: =item *
 8525: X<rolesinit()>
 8526: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8527: 
 8528: =item *
 8529: X<getsection()>
 8530: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8531: course $cname, return section name/number or '' for "not in course"
 8532: and '-1' for "no section"
 8533: 
 8534: =item *
 8535: X<userenvironment()>
 8536: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8537: passed in @what from the requested user's environment, returns a hash
 8538: 
 8539: =item * 
 8540: X<userlog_query()>
 8541: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8542: activity.log file. %filters defines filters applied when parsing the
 8543: log file. These can be start or end timestamps, or the type of action
 8544: - log to look for Login or Logout events, check for Checkin or
 8545: Checkout, role for role selection. The response is in the form
 8546: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8547: escaped strings of the action recorded in the activity.log file.
 8548: 
 8549: =back
 8550: 
 8551: =head2 User Roles
 8552: 
 8553: =over 4
 8554: 
 8555: =item *
 8556: 
 8557: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8558:  F: full access
 8559:  U,I,K: authentication modes (cxx only)
 8560:  '': forbidden
 8561:  1: user needs to choose course
 8562:  2: browse allowed
 8563:  A: passphrase authentication needed
 8564: 
 8565: =item *
 8566: 
 8567: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8568: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8569: and course level
 8570: 
 8571: =item *
 8572: 
 8573: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8574: explanation of a user role term
 8575: 
 8576: =item *
 8577: 
 8578: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8579: All arguments are optional. Returns a hash of a roles, either for
 8580: co-author/assistant author roles for a user's Construction Space
 8581: (default), or if $context is 'userroles', roles for the user himself,
 8582: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8583: and value is set to colon-separated start and end times for the role.
 8584: If no username and domain are specified, will default to current
 8585: user/domain. Types, roles, and roledoms are references to arrays,
 8586: of role statuses (active, future or previous), roles 
 8587: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8588: to restrict the list of roles reported. If no array ref is 
 8589: provided for types, will default to return only active roles.
 8590: 
 8591: =back
 8592: 
 8593: =head2 User Modification
 8594: 
 8595: =over 4
 8596: 
 8597: =item *
 8598: 
 8599: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8600: user for the level given by URL.  Optional start and end dates (leave empty
 8601: string or zero for "no date")
 8602: 
 8603: =item *
 8604: 
 8605: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8606: change a users, password, possible return values are: ok,
 8607: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8608: refused
 8609: 
 8610: =item *
 8611: 
 8612: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8613: 
 8614: =item *
 8615: 
 8616: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8617: modify user
 8618: 
 8619: =item *
 8620: 
 8621: modifystudent
 8622: 
 8623: modify a students enrollment and identification information.
 8624: The course id is resolved based on the current users environment.  
 8625: This means the envoking user must be a course coordinator or otherwise
 8626: associated with a course.
 8627: 
 8628: This call is essentially a wrapper for lonnet::modifyuser and
 8629: lonnet::modify_student_enrollment
 8630: 
 8631: Inputs: 
 8632: 
 8633: =over 4
 8634: 
 8635: =item B<$udom> Students loncapa domain
 8636: 
 8637: =item B<$uname> Students loncapa login name
 8638: 
 8639: =item B<$uid> Students id/student number
 8640: 
 8641: =item B<$umode> Students authentication mode
 8642: 
 8643: =item B<$upass> Students password
 8644: 
 8645: =item B<$first> Students first name
 8646: 
 8647: =item B<$middle> Students middle name
 8648: 
 8649: =item B<$last> Students last name
 8650: 
 8651: =item B<$gene> Students generation
 8652: 
 8653: =item B<$usec> Students section in course
 8654: 
 8655: =item B<$end> Unix time of the roles expiration
 8656: 
 8657: =item B<$start> Unix time of the roles start date
 8658: 
 8659: =item B<$forceid> If defined, allow $uid to be changed
 8660: 
 8661: =item B<$desiredhome> server to use as home server for student
 8662: 
 8663: =back
 8664: 
 8665: =item *
 8666: 
 8667: modify_student_enrollment
 8668: 
 8669: Change a students enrollment status in a class.  The environment variable
 8670: 'role.request.course' must be defined for this function to proceed.
 8671: 
 8672: Inputs:
 8673: 
 8674: =over 4
 8675: 
 8676: =item $udom, students domain
 8677: 
 8678: =item $uname, students name
 8679: 
 8680: =item $uid, students user id
 8681: 
 8682: =item $first, students first name
 8683: 
 8684: =item $middle
 8685: 
 8686: =item $last
 8687: 
 8688: =item $gene
 8689: 
 8690: =item $usec
 8691: 
 8692: =item $end
 8693: 
 8694: =item $start
 8695: 
 8696: =back
 8697: 
 8698: 
 8699: =item *
 8700: 
 8701: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8702: custom role; give a custom role to a user for the level given by URL.  Specify
 8703: name and domain of role author, and role name
 8704: 
 8705: =item *
 8706: 
 8707: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8708: 
 8709: =item *
 8710: 
 8711: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8712: 
 8713: =back
 8714: 
 8715: =head2 Course Infomation
 8716: 
 8717: =over 4
 8718: 
 8719: =item *
 8720: 
 8721: coursedescription($courseid) : returns a hash of information about the
 8722: specified course id, including all environment settings for the
 8723: course, the description of the course will be in the hash under the
 8724: key 'description'
 8725: 
 8726: =item *
 8727: 
 8728: resdata($name,$domain,$type,@which) : request for current parameter
 8729: setting for a specific $type, where $type is either 'course' or 'user',
 8730: @what should be a list of parameters to ask about. This routine caches
 8731: answers for 5 minutes.
 8732: 
 8733: =item *
 8734: 
 8735: get_courseresdata($courseid, $domain) : dump the entire course resource
 8736: data base, returning a hash that is keyed by the resource name and has
 8737: values that are the resource value.  I believe that the timestamps and
 8738: versions are also returned.
 8739: 
 8740: 
 8741: =back
 8742: 
 8743: =head2 Course Modification
 8744: 
 8745: =over 4
 8746: 
 8747: =item *
 8748: 
 8749: writecoursepref($courseid,%prefs) : write preferences (environment
 8750: database) for a course
 8751: 
 8752: =item *
 8753: 
 8754: createcourse($udom,$description,$url) : make/modify course
 8755: 
 8756: =back
 8757: 
 8758: =head2 Resource Subroutines
 8759: 
 8760: =over 4
 8761: 
 8762: =item *
 8763: 
 8764: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8765: 
 8766: =item *
 8767: 
 8768: repcopy($filename) : subscribes to the requested file, and attempts to
 8769: replicate from the owning library server, Might return
 8770: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8771: 'bad_request', also attempts to grab the metadata for the
 8772: resource. Expects the local filesystem pathname
 8773: (/home/httpd/html/res/....)
 8774: 
 8775: =back
 8776: 
 8777: =head2 Resource Information
 8778: 
 8779: =over 4
 8780: 
 8781: =item *
 8782: 
 8783: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8784: a vairety of different possible values, $varname should be a request
 8785: string, and the other parameters can be used to specify who and what
 8786: one is asking about.
 8787: 
 8788: Possible values for $varname are environment.lastname (or other item
 8789: from the envirnment hash), user.name (or someother aspect about the
 8790: user), resource.0.maxtries (or some other part and parameter of a
 8791: resource)
 8792: 
 8793: =item *
 8794: 
 8795: directcondval($number) : get current value of a condition; reads from a state
 8796: string
 8797: 
 8798: =item *
 8799: 
 8800: condval($condidx) : value of condition index based on state
 8801: 
 8802: =item *
 8803: 
 8804: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8805: resource's metadata, $what should be either a specific key, or either
 8806: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8807: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8808: 
 8809: this function automatically caches all requests
 8810: 
 8811: =item *
 8812: 
 8813: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8814: network of library servers; returns file handle of where SQL and regex results
 8815: will be stored for query
 8816: 
 8817: =item *
 8818: 
 8819: symbread($filename) : return symbolic list entry (filename argument optional);
 8820: returns the data handle
 8821: 
 8822: =item *
 8823: 
 8824: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8825: a possible symb for the URL in $thisfn, and if is an encryypted
 8826: resource that the user accessed using /enc/ returns a 1 on success, 0
 8827: on failure, user must be in a course, as it assumes the existance of
 8828: the course initial hash, and uses $env('request.course.id'}
 8829: 
 8830: 
 8831: =item *
 8832: 
 8833: symbclean($symb) : removes versions numbers from a symb, returns the
 8834: cleaned symb
 8835: 
 8836: =item *
 8837: 
 8838: is_on_map($uri) : checks if the $uri is somewhere on the current
 8839: course map, user must be in a course for it to work.
 8840: 
 8841: =item *
 8842: 
 8843: numval($salt) : return random seed value (addend for rndseed)
 8844: 
 8845: =item *
 8846: 
 8847: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8848: a random seed, all arguments are optional, if they aren't sent it uses the
 8849: environment to derive them. Note: if symb isn't sent and it can't get one
 8850: from &symbread it will use the current time as its return value
 8851: 
 8852: =item *
 8853: 
 8854: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8855: unfakeable, receipt
 8856: 
 8857: =item *
 8858: 
 8859: receipt() : API to ireceipt working off of env values; given out to users
 8860: 
 8861: =item *
 8862: 
 8863: countacc($url) : count the number of accesses to a given URL
 8864: 
 8865: =item *
 8866: 
 8867: 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
 8868: 
 8869: =item *
 8870: 
 8871: 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)
 8872: 
 8873: =item *
 8874: 
 8875: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8876: 
 8877: =item *
 8878: 
 8879: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8880: forcing spreadsheet to reevaluate the resource scores next time.
 8881: 
 8882: =back
 8883: 
 8884: =head2 Storing/Retreiving Data
 8885: 
 8886: =over 4
 8887: 
 8888: =item *
 8889: 
 8890: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8891: for this url; hashref needs to be given and should be a \%hashname; the
 8892: remaining args aren't required and if they aren't passed or are '' they will
 8893: be derived from the env
 8894: 
 8895: =item *
 8896: 
 8897: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8898: uses critical subroutine
 8899: 
 8900: =item *
 8901: 
 8902: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8903: all args are optional
 8904: 
 8905: =item *
 8906: 
 8907: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8908: dumps the complete (or key matching regexp) namespace into a hash
 8909: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8910: normally &store()ed into
 8911: 
 8912: $range should be either an integer '100' (give me the first 100
 8913:                                            matching records)
 8914:               or be  two integers sperated by a - with no spaces
 8915:                  '30-50' (give me the 30th through the 50th matching
 8916:                           records)
 8917: 
 8918: 
 8919: =item *
 8920: 
 8921: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8922: replaces a &store() version of data with a replacement set of data
 8923: for a particular resource in a namespace passed in the $storehash hash 
 8924: reference
 8925: 
 8926: =item *
 8927: 
 8928: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8929: works very similar to store/cstore, but all data is stored in a
 8930: temporary location and can be reset using tmpreset, $storehash should
 8931: be a hash reference, returns nothing on success
 8932: 
 8933: =item *
 8934: 
 8935: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8936: similar to restore, but all data is stored in a temporary location and
 8937: can be reset using tmpreset. Returns a hash of values on success,
 8938: error string otherwise.
 8939: 
 8940: =item *
 8941: 
 8942: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8943: deltes all keys for $symb form the temporary storage hash.
 8944: 
 8945: =item *
 8946: 
 8947: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8948: reference filled in from namesp ($udom and $uname are optional)
 8949: 
 8950: =item *
 8951: 
 8952: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8953: namesp ($udom and $uname are optional)
 8954: 
 8955: =item *
 8956: 
 8957: dump($namespace,$udom,$uname,$regexp,$range) : 
 8958: dumps the complete (or key matching regexp) namespace into a hash
 8959: ($udom, $uname, $regexp, $range are optional)
 8960: 
 8961: $range should be either an integer '100' (give me the first 100
 8962:                                            matching records)
 8963:               or be  two integers sperated by a - with no spaces
 8964:                  '30-50' (give me the 30th through the 50th matching
 8965:                           records)
 8966: =item *
 8967: 
 8968: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8969: $store can be a scalar, an array reference, or if the amount to be 
 8970: incremented is > 1, a hash reference.
 8971: 
 8972: ($udom and $uname are optional)
 8973: 
 8974: =item *
 8975: 
 8976: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8977: ($udom and $uname are optional)
 8978: 
 8979: =item *
 8980: 
 8981: cput($namespace,$storehash,$udom,$uname) : critical put
 8982: ($udom and $uname are optional)
 8983: 
 8984: =item *
 8985: 
 8986: newput($namespace,$storehash,$udom,$uname) :
 8987: 
 8988: Attempts to store the items in the $storehash, but only if they don't
 8989: currently exist, if this succeeds you can be certain that you have 
 8990: successfully created a new key value pair in the $namespace db.
 8991: 
 8992: 
 8993: Args:
 8994:  $namespace: name of database to store values to
 8995:  $storehash: hashref to store to the db
 8996:  $udom: (optional) domain of user containing the db
 8997:  $uname: (optional) name of user caontaining the db
 8998: 
 8999: Returns:
 9000:  'ok' -> succeeded in storing all keys of $storehash
 9001:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9002:                         least <key> already existed in the db (other
 9003:                         requested keys may also already exist)
 9004:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9005:  'con_lost' -> unable to contact request server
 9006:  'refused' -> action was not allowed by remote machine
 9007: 
 9008: 
 9009: =item *
 9010: 
 9011: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9012: reference filled in from namesp (encrypts the return communication)
 9013: ($udom and $uname are optional)
 9014: 
 9015: =item *
 9016: 
 9017: log($udom,$name,$home,$message) : write to permanent log for user; use
 9018: critical subroutine
 9019: 
 9020: =item *
 9021: 
 9022: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9023: array reference filled in from namespace found in domain level on either
 9024: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9025: 
 9026: =item *
 9027: 
 9028: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9029: domain level either on specified domain server ($uhome) or primary domain 
 9030: server ($udom and $uhome are optional)
 9031: 
 9032: =back
 9033: 
 9034: =head2 Network Status Functions
 9035: 
 9036: =over 4
 9037: 
 9038: =item *
 9039: 
 9040: dirlist($uri) : return directory list based on URI
 9041: 
 9042: =item *
 9043: 
 9044: spareserver() : find server with least workload from spare.tab
 9045: 
 9046: =back
 9047: 
 9048: =head2 Apache Request
 9049: 
 9050: =over 4
 9051: 
 9052: =item *
 9053: 
 9054: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9055: localhost, posts hash
 9056: 
 9057: =back
 9058: 
 9059: =head2 Data to String to Data
 9060: 
 9061: =over 4
 9062: 
 9063: =item *
 9064: 
 9065: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9066: and '&' separators, supports elements that are arrayrefs and hashrefs
 9067: 
 9068: =item *
 9069: 
 9070: hashref2str($hashref) : convert a hashref into a string complete with
 9071: escaping and '=' and '&' separators, supports elements that are
 9072: arrayrefs and hashrefs
 9073: 
 9074: =item *
 9075: 
 9076: arrayref2str($arrayref) : convert an arrayref into a string complete
 9077: with escaping and '&' separators, supports elements that are arrayrefs
 9078: and hashrefs
 9079: 
 9080: =item *
 9081: 
 9082: str2hash($string) : convert string to hash using unescaping and
 9083: splitting on '=' and '&', supports elements that are arrayrefs and
 9084: hashrefs
 9085: 
 9086: =item *
 9087: 
 9088: str2array($string) : convert string to hash using unescaping and
 9089: splitting on '&', supports elements that are arrayrefs and hashrefs
 9090: 
 9091: =back
 9092: 
 9093: =head2 Logging Routines
 9094: 
 9095: =over 4
 9096: 
 9097: These routines allow one to make log messages in the lonnet.log and
 9098: lonnet.perm logfiles.
 9099: 
 9100: =item *
 9101: 
 9102: logtouch() : make sure the logfile, lonnet.log, exists
 9103: 
 9104: =item *
 9105: 
 9106: logthis() : append message to the normal lonnet.log file, it gets
 9107: preiodically rolled over and deleted.
 9108: 
 9109: =item *
 9110: 
 9111: logperm() : append a permanent message to lonnet.perm.log, this log
 9112: file never gets deleted by any automated portion of the system, only
 9113: messages of critical importance should go in here.
 9114: 
 9115: =back
 9116: 
 9117: =head2 General File Helper Routines
 9118: 
 9119: =over 4
 9120: 
 9121: =item *
 9122: 
 9123: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9124: (a) files in /uploaded
 9125:   (i) If a local copy of the file exists - 
 9126:       compares modification date of local copy with last-modified date for 
 9127:       definitive version stored on home server for course. If local copy is 
 9128:       stale, requests a new version from the home server and stores it. 
 9129:       If the original has been removed from the home server, then local copy 
 9130:       is unlinked.
 9131:   (ii) If local copy does not exist -
 9132:       requests the file from the home server and stores it. 
 9133:   
 9134:   If $caller is 'uploadrep':  
 9135:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9136:     for request for files originally uploaded via DOCS. 
 9137:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9138:   
 9139:   Otherwise:
 9140:      This indicates a call from the content generation phase of the request.
 9141:      -  returns the entire contents of the file or -1.
 9142:      
 9143: (b) files in /res
 9144:    - returns the entire contents of a file or -1; 
 9145:    it properly subscribes to and replicates the file if neccessary.
 9146: 
 9147: 
 9148: =item *
 9149: 
 9150: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9151:                   reference
 9152: 
 9153: returns either a stat() list of data about the file or an empty list
 9154: if the file doesn't exist or couldn't find out about it (connection
 9155: problems or user unknown)
 9156: 
 9157: =item *
 9158: 
 9159: filelocation($dir,$file) : returns file system location of a file
 9160: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9161: directory that relative $file lookups are to looked in ($dir of /a/dir
 9162: and a file of ../bob will become /a/bob)
 9163: 
 9164: =item *
 9165: 
 9166: hreflocation($dir,$file) : returns file system location or a URL; same as
 9167: filelocation except for hrefs
 9168: 
 9169: =item *
 9170: 
 9171: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9172: 
 9173: =back
 9174: 
 9175: =head2 Usererfile file routines (/uploaded*)
 9176: 
 9177: =over 4
 9178: 
 9179: =item *
 9180: 
 9181: userfileupload(): main rotine for putting a file in a user or course's
 9182:                   filespace, arguments are,
 9183: 
 9184:  formname - required - this is the name of the element in $env where the
 9185:            filename, and the contents of the file to create/modifed exist
 9186:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9187:            contents of the file is located in $env{'form.'.$formname}
 9188:  coursedoc - if true, store the file in the course of the active role
 9189:              of the current user
 9190:  subdir - required - subdirectory to put the file in under ../userfiles/
 9191:          if undefined, it will be placed in "unknown"
 9192: 
 9193:  (This routine calls clean_filename() to remove any dangerous
 9194:  characters from the filename, and then calls finuserfileupload() to
 9195:  complete the transaction)
 9196: 
 9197:  returns either the url of the uploaded file (/uploaded/....) if successful
 9198:  and /adm/notfound.html if unsuccessful
 9199: 
 9200: =item *
 9201: 
 9202: clean_filename(): routine for cleaing a filename up for storage in
 9203:                  userfile space, argument is:
 9204: 
 9205:  filename - proposed filename
 9206: 
 9207: returns: the new clean filename
 9208: 
 9209: =item *
 9210: 
 9211: finishuserfileupload(): routine that creaes and sends the file to
 9212: userspace, probably shouldn't be called directly
 9213: 
 9214:   docuname: username or courseid of destination for the file
 9215:   docudom: domain of user/course of destination for the file
 9216:   formname: same as for userfileupload()
 9217:   fname: filename (inculding subdirectories) for the file
 9218: 
 9219:  returns either the url of the uploaded file (/uploaded/....) if successful
 9220:  and /adm/notfound.html if unsuccessful
 9221: 
 9222: =item *
 9223: 
 9224: renameuserfile(): renames an existing userfile to a new name
 9225: 
 9226:   Args:
 9227:    docuname: username or courseid of destination for the file
 9228:    docudom: domain of user/course of destination for the file
 9229:    old: current file name (including any subdirs under userfiles)
 9230:    new: desired file name (including any subdirs under userfiles)
 9231: 
 9232: =item *
 9233: 
 9234: mkdiruserfile(): creates a directory is a userfiles dir
 9235: 
 9236:   Args:
 9237:    docuname: username or courseid of destination for the file
 9238:    docudom: domain of user/course of destination for the file
 9239:    dir: dir to create (including any subdirs under userfiles)
 9240: 
 9241: =item *
 9242: 
 9243: removeuserfile(): removes a file that exists in userfiles
 9244: 
 9245:   Args:
 9246:    docuname: username or courseid of destination for the file
 9247:    docudom: domain of user/course of destination for the file
 9248:    fname: filname to delete (including any subdirs under userfiles)
 9249: 
 9250: =item *
 9251: 
 9252: removeuploadedurl(): convience function for removeuserfile()
 9253: 
 9254:   Args:
 9255:    url:  a full /uploaded/... url to delete
 9256: 
 9257: =item * 
 9258: 
 9259: get_portfile_permissions():
 9260:   Args:
 9261:     domain: domain of user or course contain the portfolio files
 9262:     user: name of user or num of course contain the portfolio files
 9263:   Returns:
 9264:     hashref of a dump of the proper file_permissions.db
 9265:    
 9266: 
 9267: =item * 
 9268: 
 9269: get_access_controls():
 9270: 
 9271: Args:
 9272:   current_permissions: the hash ref returned from get_portfile_permissions()
 9273:   group: (optional) the group you want the files associated with
 9274:   file: (optional) the file you want access info on
 9275: 
 9276: Returns:
 9277:     a hash (keys are file names) of hashes containing
 9278:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9279:         values are XML containing access control settings (see below) 
 9280: 
 9281: Internal notes:
 9282: 
 9283:  access controls are stored in file_permissions.db as key=value pairs.
 9284:     key -> path to file/file_name\0uniqueID:scope_end_start
 9285:         where scope -> public,guest,course,group,domains or users.
 9286:               end -> UNIX time for end of access (0 -> no end date)
 9287:               start -> UNIX time for start of access
 9288: 
 9289:     value -> XML description of access control
 9290:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9291:             <start></start>
 9292:             <end></end>
 9293: 
 9294:             <password></password>  for scope type = guest
 9295: 
 9296:             <domain></domain>     for scope type = course or group
 9297:             <number></number>
 9298:             <roles id="">
 9299:              <role></role>
 9300:              <access></access>
 9301:              <section></section>
 9302:              <group></group>
 9303:             </roles>
 9304: 
 9305:             <dom></dom>         for scope type = domains
 9306: 
 9307:             <users>             for scope type = users
 9308:              <user>
 9309:               <uname></uname>
 9310:               <udom></udom>
 9311:              </user>
 9312:             </users>
 9313:            </scope> 
 9314:               
 9315:  Access data is also aggregated for each file in an additional key=value pair:
 9316:  key -> path to file/file_name\0accesscontrol 
 9317:  value -> reference to hash
 9318:           hash contains key = value pairs
 9319:           where key = uniqueID:scope_end_start
 9320:                 value = UNIX time record was last updated
 9321: 
 9322:           Used to improve speed of look-ups of access controls for each file.  
 9323:  
 9324:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9325: 
 9326: modify_access_controls():
 9327: 
 9328: Modifies access controls for a portfolio file
 9329: Args
 9330: 1. file name
 9331: 2. reference to hash of required changes,
 9332: 3. domain
 9333: 4. username
 9334:   where domain,username are the domain of the portfolio owner 
 9335:   (either a user or a course) 
 9336: 
 9337: Returns:
 9338: 1. result of additions or updates ('ok' or 'error', with error message). 
 9339: 2. result of deletions ('ok' or 'error', with error message).
 9340: 3. reference to hash of any new or updated access controls.
 9341: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9342:    key = integer (inbound ID)
 9343:    value = uniqueID  
 9344: 
 9345: =back
 9346: 
 9347: =head2 HTTP Helper Routines
 9348: 
 9349: =over 4
 9350: 
 9351: =item *
 9352: 
 9353: escape() : unpack non-word characters into CGI-compatible hex codes
 9354: 
 9355: =item *
 9356: 
 9357: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9358: 
 9359: =back
 9360: 
 9361: =head1 PRIVATE SUBROUTINES
 9362: 
 9363: =head2 Underlying communication routines (Shouldn't call)
 9364: 
 9365: =over 4
 9366: 
 9367: =item *
 9368: 
 9369: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9370: 
 9371: =item *
 9372: 
 9373: reply() : uses subreply to send a message to remote machine, logs all failures
 9374: 
 9375: =item *
 9376: 
 9377: critical() : passes a critical message to another server; if cannot
 9378: get through then place message in connection buffer directory and
 9379: returns con_delayed, if incapable of saving message, returns
 9380: con_failed
 9381: 
 9382: =item *
 9383: 
 9384: reconlonc() : tries to reconnect lonc client processes.
 9385: 
 9386: =back
 9387: 
 9388: =head2 Resource Access Logging
 9389: 
 9390: =over 4
 9391: 
 9392: =item *
 9393: 
 9394: flushcourselogs() : flush (save) buffer logs and access logs
 9395: 
 9396: =item *
 9397: 
 9398: courselog($what) : save message for course in hash
 9399: 
 9400: =item *
 9401: 
 9402: courseacclog($what) : save message for course using &courselog().  Perform
 9403: special processing for specific resource types (problems, exams, quizzes, etc).
 9404: 
 9405: =item *
 9406: 
 9407: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9408: as a PerlChildExitHandler
 9409: 
 9410: =back
 9411: 
 9412: =head2 Other
 9413: 
 9414: =over 4
 9415: 
 9416: =item *
 9417: 
 9418: symblist($mapname,%newhash) : update symbolic storage links
 9419: 
 9420: =back
 9421: 
 9422: =cut
 9423: 

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