File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.950: download - view: text, annotated - select for diffs
Sat Mar 22 15:47:41 2008 UTC (16 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Update comments for sub ssi().
- Remove $count and $status from sub ssi() - no longer used.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.950 2008/03/22 15:47:41 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: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  324: 	if (!$opened) {
  325: 	    return 0;
  326: 	}
  327: 	flock($idf,LOCK_SH);
  328: 	@profile=<$idf>;
  329: 	close($idf);
  330:     }
  331:     my %temp_env;
  332:     foreach my $line (@profile) {
  333: 	if ($line !~ m/=/) {
  334: 	    return 0;
  335: 	}
  336: 	chomp($line);
  337: 	my ($envname,$envvalue)=split(/=/,$line,2);
  338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  339:     }
  340:     unlink("$lonidsdir/$handle.id");
  341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  342: 	    0640)) {
  343: 	%disk_env = %temp_env;
  344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  345: 	untie(%disk_env);
  346:     }
  347:     return 1;
  348: }
  349: 
  350: # ------------------------------------------- Transfer profile into environment
  351: my $env_loaded;
  352: sub transfer_profile_to_env {
  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
  354:     if (!$force_transfer && $env_loaded) { return; } 
  355: 
  356:     if (!defined($lonidsdir)) {
  357: 	$lonidsdir = $perlvar{'lonIDsDir'};
  358:     }
  359:     if (!defined($handle)) {
  360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  361:     }
  362: 
  363:     my $convert;
  364:     {
  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  366: 	if (!$opened) {
  367: 	    return;
  368: 	}
  369: 	flock($idf,LOCK_SH);
  370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  371: 		&GDBM_READER(),0640)) {
  372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  373: 	    untie(%disk_env);
  374: 	} else {
  375: 	    $convert = 1;
  376: 	}
  377:     }
  378:     if ($convert) {
  379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  380: 	    &logthis("Failed to load session, or convert session.");
  381: 	}
  382:     }
  383: 
  384:     my %remove;
  385:     while ( my $envname = each(%env) ) {
  386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  387:             if ($time < time-300) {
  388:                 $remove{$key}++;
  389:             }
  390:         }
  391:     }
  392: 
  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  394:     $env_loaded=1;
  395:     foreach my $expired_key (keys(%remove)) {
  396:         &delenv($expired_key);
  397:     }
  398: }
  399: 
  400: # ---------------------------------------------------- Check for valid session 
  401: sub check_for_valid_session {
  402:     my ($r) = @_;
  403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  404:     my $lonid=$cookies{'lonID'};
  405:     return undef if (!$lonid);
  406: 
  407:     my $handle=&LONCAPA::clean_handle($lonid->value);
  408:     my $lonidsdir=$r->dir_config('lonIDsDir');
  409:     return undef if (!-e "$lonidsdir/$handle.id");
  410: 
  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  412:     return undef if (!$opened);
  413: 
  414:     flock($idf,LOCK_SH);
  415:     my %disk_env;
  416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  417: 	    &GDBM_READER(),0640)) {
  418: 	return undef;	
  419:     }
  420: 
  421:     if (!defined($disk_env{'user.name'})
  422: 	|| !defined($disk_env{'user.domain'})) {
  423: 	return undef;
  424:     }
  425:     return $handle;
  426: }
  427: 
  428: sub timed_flock {
  429:     my ($file,$lock_type) = @_;
  430:     my $failed=0;
  431:     eval {
  432: 	local $SIG{__DIE__}='DEFAULT';
  433: 	local $SIG{ALRM}=sub {
  434: 	    $failed=1;
  435: 	    die("failed lock");
  436: 	};
  437: 	alarm(13);
  438: 	flock($file,$lock_type);
  439: 	alarm(0);
  440:     };
  441:     if ($failed) {
  442: 	return undef;
  443:     } else {
  444: 	return 1;
  445:     }
  446: }
  447: 
  448: # ---------------------------------------------------------- Append Environment
  449: 
  450: sub appenv {
  451:     my ($newenv,$roles) = @_;
  452:     if (ref($newenv) eq 'HASH') {
  453:         foreach my $key (keys(%{$newenv})) {
  454:             my $refused = 0;
  455: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  456:                 $refused = 1;
  457:                 if (ref($roles) eq 'ARRAY') {
  458:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  459:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  460:                         $refused = 0;
  461:                     }
  462:                 }
  463:             }
  464:             if ($refused) {
  465:                 &logthis("<font color=\"blue\">WARNING: ".
  466:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  467:                          .'</font>');
  468: 	        delete($newenv->{$key});
  469:             } else {
  470:                 $env{$key}=$newenv->{$key};
  471:             }
  472:         }
  473:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  474:         if ($opened
  475: 	    && &timed_flock($env_file,LOCK_EX)
  476: 	    &&
  477: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  478: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  479: 	    while (my ($key,$value) = each(%{$newenv})) {
  480: 	        $disk_env{$key} = $value;
  481: 	    }
  482: 	    untie(%disk_env);
  483:         }
  484:     }
  485:     return 'ok';
  486: }
  487: # ----------------------------------------------------- Delete from Environment
  488: 
  489: sub delenv {
  490:     my $delthis=shift;
  491:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  492:         &logthis("<font color=\"blue\">WARNING: ".
  493:                 "Attempt to delete from environment ".$delthis);
  494:         return 'error';
  495:     }
  496:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  497:     if ($opened
  498: 	&& &timed_flock($env_file,LOCK_EX)
  499: 	&&
  500: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  501: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  502: 	foreach my $key (keys(%disk_env)) {
  503: 	    if ($key=~/^$delthis/) { 
  504: 		delete($env{$key});
  505: 		delete($disk_env{$key});
  506: 	    }
  507: 	}
  508: 	untie(%disk_env);
  509:     }
  510:     return 'ok';
  511: }
  512: 
  513: sub get_env_multiple {
  514:     my ($name) = @_;
  515:     my @values;
  516:     if (defined($env{$name})) {
  517:         # exists is it an array
  518:         if (ref($env{$name})) {
  519:             @values=@{ $env{$name} };
  520:         } else {
  521:             $values[0]=$env{$name};
  522:         }
  523:     }
  524:     return(@values);
  525: }
  526: 
  527: # ------------------------------------------ Find out current server userload
  528: sub userload {
  529:     my $numusers=0;
  530:     {
  531: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  532: 	my $filename;
  533: 	my $curtime=time;
  534: 	while ($filename=readdir(LONIDS)) {
  535: 	    next if ($filename eq '.' || $filename eq '..');
  536: 	    next if ($filename =~ /publicuser_\d+\.id/);
  537: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  538: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  539: 	}
  540: 	closedir(LONIDS);
  541:     }
  542:     my $userloadpercent=0;
  543:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  544:     if ($maxuserload) {
  545: 	$userloadpercent=100*$numusers/$maxuserload;
  546:     }
  547:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  548:     return $userloadpercent;
  549: }
  550: 
  551: # ------------------------------------------ Fight off request when overloaded
  552: 
  553: sub overloaderror {
  554:     my ($r,$checkserver)=@_;
  555:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  556:     my $loadavg;
  557:     if ($checkserver eq $perlvar{'lonHostID'}) {
  558:        open(my $loadfile,'/proc/loadavg');
  559:        $loadavg=<$loadfile>;
  560:        $loadavg =~ s/\s.*//g;
  561:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  562:        close($loadfile);
  563:     } else {
  564:        $loadavg=&reply('load',$checkserver);
  565:     }
  566:     my $overload=$loadavg-100;
  567:     if ($overload>0) {
  568: 	$r->err_headers_out->{'Retry-After'}=$overload;
  569:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  570:         return 413;
  571:     }    
  572:     return '';
  573: }
  574: 
  575: # ------------------------------ Find server with least workload from spare.tab
  576: 
  577: sub spareserver {
  578:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  579:     my $spare_server;
  580:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  581:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  582:                                                      :  $userloadpercent;
  583:     
  584:     foreach my $try_server (@{ $spareid{'primary'} }) {
  585: 	($spare_server, $lowest_load) =
  586: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  587:     }
  588: 
  589:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  590: 
  591:     if (!$found_server) {
  592: 	foreach my $try_server (@{ $spareid{'default'} }) {
  593: 	    ($spare_server, $lowest_load) =
  594: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  595: 	}
  596:     }
  597: 
  598:     if (!$want_server_name) {
  599: 	$spare_server="http://".&hostname($spare_server);
  600:     }
  601:     return $spare_server;
  602: }
  603: 
  604: sub compare_server_load {
  605:     my ($try_server, $spare_server, $lowest_load) = @_;
  606: 
  607:     my $loadans     = &reply('load',    $try_server);
  608:     my $userloadans = &reply('userload',$try_server);
  609: 
  610:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  611: 	next; #didn't get a number from the server
  612:     }
  613: 
  614:     my $load;
  615:     if ($loadans =~ /\d/) {
  616: 	if ($userloadans =~ /\d/) {
  617: 	    #both are numbers, pick the bigger one
  618: 	    $load = ($loadans > $userloadans) ? $loadans 
  619: 		                              : $userloadans;
  620: 	} else {
  621: 	    $load = $loadans;
  622: 	}
  623:     } else {
  624: 	$load = $userloadans;
  625:     }
  626: 
  627:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  628: 	$spare_server = $try_server;
  629: 	$lowest_load  = $load;
  630:     }
  631:     return ($spare_server,$lowest_load);
  632: }
  633: 
  634: # --------------------------- ask offload servers if user already has a session
  635: sub find_existing_session {
  636:     my ($udom,$uname) = @_;
  637:     foreach my $try_server (@{ $spareid{'primary'} },
  638: 			    @{ $spareid{'default'} }) {
  639: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  640:     }
  641:     return;
  642: }
  643: 
  644: # -------------------------------- ask if server already has a session for user
  645: sub has_user_session {
  646:     my ($lonid,$udom,$uname) = @_;
  647:     my $result = &reply(join(':','userhassession',
  648: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  649:     return 1 if ($result eq 'ok');
  650: 
  651:     return 0;
  652: }
  653: 
  654: # --------------------------------------------- Try to change a user's password
  655: 
  656: sub changepass {
  657:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  658:     $currentpass = &escape($currentpass);
  659:     $newpass     = &escape($newpass);
  660:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  661: 		       $server);
  662:     if (! $answer) {
  663: 	&logthis("No reply on password change request to $server ".
  664: 		 "by $uname in domain $udom.");
  665:     } elsif ($answer =~ "^ok") {
  666:         &logthis("$uname in $udom successfully changed their password ".
  667: 		 "on $server.");
  668:     } elsif ($answer =~ "^pwchange_failure") {
  669: 	&logthis("$uname in $udom was unable to change their password ".
  670: 		 "on $server.  The action was blocked by either lcpasswd ".
  671: 		 "or pwchange");
  672:     } elsif ($answer =~ "^non_authorized") {
  673:         &logthis("$uname in $udom did not get their password correct when ".
  674: 		 "attempting to change it on $server.");
  675:     } elsif ($answer =~ "^auth_mode_error") {
  676:         &logthis("$uname in $udom attempted to change their password despite ".
  677: 		 "not being locally or internally authenticated on $server.");
  678:     } elsif ($answer =~ "^unknown_user") {
  679:         &logthis("$uname in $udom attempted to change their password ".
  680: 		 "on $server but were unable to because $server is not ".
  681: 		 "their home server.");
  682:     } elsif ($answer =~ "^refused") {
  683: 	&logthis("$server refused to change $uname in $udom password because ".
  684: 		 "it was sent an unencrypted request to change the password.");
  685:     }
  686:     return $answer;
  687: }
  688: 
  689: # ----------------------- Try to determine user's current authentication scheme
  690: 
  691: sub queryauthenticate {
  692:     my ($uname,$udom)=@_;
  693:     my $uhome=&homeserver($uname,$udom);
  694:     if (!$uhome) {
  695: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  696: 	return 'no_host';
  697:     }
  698:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  699:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  700: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  701:     }
  702:     return $answer;
  703: }
  704: 
  705: # --------- Try to authenticate user from domain's lib servers (first this one)
  706: 
  707: sub authenticate {
  708:     my ($uname,$upass,$udom)=@_;
  709:     $upass=&escape($upass);
  710:     $uname= &LONCAPA::clean_username($uname);
  711:     my $uhome=&homeserver($uname,$udom,1);
  712:     if ((!$uhome) || ($uhome eq 'no_host')) {
  713: # Maybe the machine was offline and only re-appeared again recently?
  714:         &reconlonc();
  715: # One more
  716: 	my $uhome=&homeserver($uname,$udom,1);
  717: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  718: 	    &logthis("User $uname at $udom is unknown in authenticate");
  719: 	}
  720: 	return 'no_host';
  721:     }
  722:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  723:     if ($answer eq 'authorized') {
  724: 	&logthis("User $uname at $udom authorized by $uhome"); 
  725: 	return $uhome; 
  726:     }
  727:     if ($answer eq 'non_authorized') {
  728: 	&logthis("User $uname at $udom rejected by $uhome");
  729: 	return 'no_host'; 
  730:     }
  731:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  732:     return 'no_host';
  733: }
  734: 
  735: # ---------------------- Find the homebase for a user from domain's lib servers
  736: 
  737: my %homecache;
  738: sub homeserver {
  739:     my ($uname,$udom,$ignoreBadCache)=@_;
  740:     my $index="$uname:$udom";
  741: 
  742:     if (exists($homecache{$index})) { return $homecache{$index}; }
  743: 
  744:     my %servers = &get_servers($udom,'library');
  745:     foreach my $tryserver (keys(%servers)) {
  746:         next if ($ignoreBadCache ne 'true' && 
  747: 		 exists($badServerCache{$tryserver}));
  748: 
  749: 	my $answer=reply("home:$udom:$uname",$tryserver);
  750: 	if ($answer eq 'found') {
  751: 	    delete($badServerCache{$tryserver}); 
  752: 	    return $homecache{$index}=$tryserver;
  753: 	} elsif ($answer eq 'no_host') {
  754: 	    $badServerCache{$tryserver}=1;
  755: 	}
  756:     }    
  757:     return 'no_host';
  758: }
  759: 
  760: # ------------------------------------- Find the usernames behind a list of IDs
  761: 
  762: sub idget {
  763:     my ($udom,@ids)=@_;
  764:     my %returnhash=();
  765:     
  766:     my %servers = &get_servers($udom,'library');
  767:     foreach my $tryserver (keys(%servers)) {
  768: 	my $idlist=join('&',@ids);
  769: 	$idlist=~tr/A-Z/a-z/; 
  770: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  771: 	my @answer=();
  772: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  773: 	    @answer=split(/\&/,$reply);
  774: 	}                    ;
  775: 	my $i;
  776: 	for ($i=0;$i<=$#ids;$i++) {
  777: 	    if ($answer[$i]) {
  778: 		$returnhash{$ids[$i]}=$answer[$i];
  779: 	    } 
  780: 	}
  781:     } 
  782:     return %returnhash;
  783: }
  784: 
  785: # ------------------------------------- Find the IDs behind a list of usernames
  786: 
  787: sub idrget {
  788:     my ($udom,@unames)=@_;
  789:     my %returnhash=();
  790:     foreach my $uname (@unames) {
  791:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  792:     }
  793:     return %returnhash;
  794: }
  795: 
  796: # ------------------------------- Store away a list of names and associated IDs
  797: 
  798: sub idput {
  799:     my ($udom,%ids)=@_;
  800:     my %servers=();
  801:     foreach my $uname (keys(%ids)) {
  802: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  803:         my $uhom=&homeserver($uname,$udom);
  804:         if ($uhom ne 'no_host') {
  805:             my $id=&escape($ids{$uname});
  806:             $id=~tr/A-Z/a-z/;
  807:             my $esc_unam=&escape($uname);
  808: 	    if ($servers{$uhom}) {
  809: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  810:             } else {
  811:                 $servers{$uhom}=$id.'='.$esc_unam;
  812:             }
  813:         }
  814:     }
  815:     foreach my $server (keys(%servers)) {
  816:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  817:     }
  818: }
  819: 
  820: # ------------------------------------------- get items from domain db files   
  821: 
  822: sub get_dom {
  823:     my ($namespace,$storearr,$udom,$uhome)=@_;
  824:     my $items='';
  825:     foreach my $item (@$storearr) {
  826:         $items.=&escape($item).'&';
  827:     }
  828:     $items=~s/\&$//;
  829:     if (!$udom) {
  830:         $udom=$env{'user.domain'};
  831:         if (defined(&domain($udom,'primary'))) {
  832:             $uhome=&domain($udom,'primary');
  833:         } else {
  834:             undef($uhome);
  835:         }
  836:     } else {
  837:         if (!$uhome) {
  838:             if (defined(&domain($udom,'primary'))) {
  839:                 $uhome=&domain($udom,'primary');
  840:             }
  841:         }
  842:     }
  843:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  844:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  845:         my %returnhash;
  846:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  847:             return %returnhash;
  848:         }
  849:         my @pairs=split(/\&/,$rep);
  850:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  851:             return @pairs;
  852:         }
  853:         my $i=0;
  854:         foreach my $item (@$storearr) {
  855:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  856:             $i++;
  857:         }
  858:         return %returnhash;
  859:     } else {
  860:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  861:     }
  862: }
  863: 
  864: # -------------------------------------------- put items in domain db files 
  865: 
  866: sub put_dom {
  867:     my ($namespace,$storehash,$udom,$uhome)=@_;
  868:     if (!$udom) {
  869:         $udom=$env{'user.domain'};
  870:         if (defined(&domain($udom,'primary'))) {
  871:             $uhome=&domain($udom,'primary');
  872:         } else {
  873:             undef($uhome);
  874:         }
  875:     } else {
  876:         if (!$uhome) {
  877:             if (defined(&domain($udom,'primary'))) {
  878:                 $uhome=&domain($udom,'primary');
  879:             }
  880:         }
  881:     } 
  882:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  883:         my $items='';
  884:         foreach my $item (keys(%$storehash)) {
  885:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  886:         }
  887:         $items=~s/\&$//;
  888:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  889:     } else {
  890:         &logthis("put_dom failed - no homeserver and/or domain");
  891:     }
  892: }
  893: 
  894: sub retrieve_inst_usertypes {
  895:     my ($udom) = @_;
  896:     my (%returnhash,@order);
  897:     if (defined(&domain($udom,'primary'))) {
  898:         my $uhome=&domain($udom,'primary');
  899:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  900:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  901:         my @pairs=split(/\&/,$hashitems);
  902:         foreach my $item (@pairs) {
  903:             my ($key,$value)=split(/=/,$item,2);
  904:             $key = &unescape($key);
  905:             next if ($key =~ /^error: 2 /);
  906:             $returnhash{$key}=&thaw_unescape($value);
  907:         }
  908:         my @esc_order = split(/\&/,$orderitems);
  909:         foreach my $item (@esc_order) {
  910:             push(@order,&unescape($item));
  911:         }
  912:     } else {
  913:         &logthis("get_dom failed - no primary domain server for $udom");
  914:     }
  915:     return (\%returnhash,\@order);
  916: }
  917: 
  918: sub is_domainimage {
  919:     my ($url) = @_;
  920:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  921:         if (&domain($1) ne '') {
  922:             return '1';
  923:         }
  924:     }
  925:     return;
  926: }
  927: 
  928: sub inst_directory_query {
  929:     my ($srch) = @_;
  930:     my $udom = $srch->{'srchdomain'};
  931:     my %results;
  932:     my $homeserver = &domain($udom,'primary');
  933:     my $outcome;
  934:     if ($homeserver ne '') {
  935: 	my $queryid=&reply("querysend:instdirsearch:".
  936: 			   &escape($srch->{'srchby'}).':'.
  937: 			   &escape($srch->{'srchterm'}).':'.
  938: 			   &escape($srch->{'srchtype'}),$homeserver);
  939: 	my $host=&hostname($homeserver);
  940: 	if ($queryid !~/^\Q$host\E\_/) {
  941: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  942: 	    return;
  943: 	}
  944: 	my $response = &get_query_reply($queryid);
  945: 	my $maxtries = 5;
  946: 	my $tries = 1;
  947: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  948: 	    $response = &get_query_reply($queryid);
  949: 	    $tries ++;
  950: 	}
  951: 
  952:         if (!&error($response) && $response ne 'refused') {
  953:             if ($response eq 'unavailable') {
  954:                 $outcome = $response;
  955:             } else {
  956:                 $outcome = 'ok';
  957:                 my @matches = split(/\n/,$response);
  958:                 foreach my $match (@matches) {
  959:                     my ($key,$value) = split(/=/,$match);
  960:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  961:                 }
  962:             }
  963:         }
  964:     }
  965:     return ($outcome,%results);
  966: }
  967: 
  968: sub usersearch {
  969:     my ($srch) = @_;
  970:     my $dom = $srch->{'srchdomain'};
  971:     my %results;
  972:     my %libserv = &all_library();
  973:     my $query = 'usersearch';
  974:     foreach my $tryserver (keys(%libserv)) {
  975:         if (&host_domain($tryserver) eq $dom) {
  976:             my $host=&hostname($tryserver);
  977:             my $queryid=
  978:                 &reply("querysend:".&escape($query).':'.
  979:                        &escape($srch->{'srchby'}).':'.
  980:                        &escape($srch->{'srchtype'}).':'.
  981:                        &escape($srch->{'srchterm'}),$tryserver);
  982:             if ($queryid !~/^\Q$host\E\_/) {
  983:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  984:                 next;
  985:             }
  986:             my $reply = &get_query_reply($queryid);
  987:             my $maxtries = 1;
  988:             my $tries = 1;
  989:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
  990:                 $reply = &get_query_reply($queryid);
  991:                 $tries ++;
  992:             }
  993:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
  994:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
  995:             } else {
  996:                 my @matches;
  997:                 if ($reply =~ /\n/) {
  998:                     @matches = split(/\n/,$reply);
  999:                 } else {
 1000:                     @matches = split(/\&/,$reply);
 1001:                 }
 1002:                 foreach my $match (@matches) {
 1003:                     my ($uname,$udom,%userhash);
 1004:                     foreach my $entry (split(/:/,$match)) {
 1005:                         my ($key,$value) =
 1006:                             map {&unescape($_);} split(/=/,$entry);
 1007:                         $userhash{$key} = $value;
 1008:                         if ($key eq 'username') {
 1009:                             $uname = $value;
 1010:                         } elsif ($key eq 'domain') {
 1011:                             $udom = $value;
 1012:                         }
 1013:                     }
 1014:                     $results{$uname.':'.$udom} = \%userhash;
 1015:                 }
 1016:             }
 1017:         }
 1018:     }
 1019:     return %results;
 1020: }
 1021: 
 1022: sub get_instuser {
 1023:     my ($udom,$uname,$id) = @_;
 1024:     my $homeserver = &domain($udom,'primary');
 1025:     my ($outcome,%results);
 1026:     if ($homeserver ne '') {
 1027:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1028:                            &escape($id).':'.&escape($udom),$homeserver);
 1029:         my $host=&hostname($homeserver);
 1030:         if ($queryid !~/^\Q$host\E\_/) {
 1031:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1032:             return;
 1033:         }
 1034:         my $response = &get_query_reply($queryid);
 1035:         my $maxtries = 5;
 1036:         my $tries = 1;
 1037:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1038:             $response = &get_query_reply($queryid);
 1039:             $tries ++;
 1040:         }
 1041:         if (!&error($response) && $response ne 'refused') {
 1042:             if ($response eq 'unavailable') {
 1043:                 $outcome = $response;
 1044:             } else {
 1045:                 $outcome = 'ok';
 1046:                 my @matches = split(/\n/,$response);
 1047:                 foreach my $match (@matches) {
 1048:                     my ($key,$value) = split(/=/,$match);
 1049:                     $results{&unescape($key)} = &thaw_unescape($value);
 1050:                 }
 1051:             }
 1052:         }
 1053:     }
 1054:     my %userinfo;
 1055:     if (ref($results{$uname}) eq 'HASH') {
 1056:         %userinfo = %{$results{$uname}};
 1057:     } 
 1058:     return ($outcome,%userinfo);
 1059: }
 1060: 
 1061: sub inst_rulecheck {
 1062:     my ($udom,$uname,$id,$item,$rules) = @_;
 1063:     my %returnhash;
 1064:     if ($udom ne '') {
 1065:         if (ref($rules) eq 'ARRAY') {
 1066:             @{$rules} = map {&escape($_);} (@{$rules});
 1067:             my $rulestr = join(':',@{$rules});
 1068:             my $homeserver=&domain($udom,'primary');
 1069:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1070:                 my $response;
 1071:                 if ($item eq 'username') {                
 1072:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1073:                                               ':'.&escape($uname).':'.$rulestr,
 1074:                                               $homeserver));
 1075:                 } elsif ($item eq 'id') {
 1076:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1077:                                               ':'.&escape($id).':'.$rulestr,
 1078:                                               $homeserver));
 1079:                 } elsif ($item eq 'selfcreate') {
 1080:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1081:                                                &escape($udom).':'.&escape($uname).
 1082:                                               ':'.$rulestr,$homeserver));
 1083:                 }
 1084:                 if ($response ne 'refused') {
 1085:                     my @pairs=split(/\&/,$response);
 1086:                     foreach my $item (@pairs) {
 1087:                         my ($key,$value)=split(/=/,$item,2);
 1088:                         $key = &unescape($key);
 1089:                         next if ($key =~ /^error: 2 /);
 1090:                         $returnhash{$key}=&thaw_unescape($value);
 1091:                     }
 1092:                 }
 1093:             }
 1094:         }
 1095:     }
 1096:     return %returnhash;
 1097: }
 1098: 
 1099: sub inst_userrules {
 1100:     my ($udom,$check) = @_;
 1101:     my (%ruleshash,@ruleorder);
 1102:     if ($udom ne '') {
 1103:         my $homeserver=&domain($udom,'primary');
 1104:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1105:             my $response;
 1106:             if ($check eq 'id') {
 1107:                 $response=&reply('instidrules:'.&escape($udom),
 1108:                                  $homeserver);
 1109:             } elsif ($check eq 'email') {
 1110:                 $response=&reply('instemailrules:'.&escape($udom),
 1111:                                  $homeserver);
 1112:             } else {
 1113:                 $response=&reply('instuserrules:'.&escape($udom),
 1114:                                  $homeserver);
 1115:             }
 1116:             if (($response ne 'refused') && ($response ne 'error') && 
 1117:                 ($response ne 'unknown_cmd') && 
 1118:                 ($response ne 'no_such_host')) {
 1119:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1120:                 my @pairs=split(/\&/,$hashitems);
 1121:                 foreach my $item (@pairs) {
 1122:                     my ($key,$value)=split(/=/,$item,2);
 1123:                     $key = &unescape($key);
 1124:                     next if ($key =~ /^error: 2 /);
 1125:                     $ruleshash{$key}=&thaw_unescape($value);
 1126:                 }
 1127:                 my @esc_order = split(/\&/,$orderitems);
 1128:                 foreach my $item (@esc_order) {
 1129:                     push(@ruleorder,&unescape($item));
 1130:                 }
 1131:             }
 1132:         }
 1133:     }
 1134:     return (\%ruleshash,\@ruleorder);
 1135: }
 1136: 
 1137: # ------------------------- Get Authentication and Language Defaults for Domain
 1138: 
 1139: sub get_domain_defaults {
 1140:     my ($domain) = @_;
 1141:     my $cachetime = 60*60*24;
 1142:     my ($defauthtype,$defautharg,$deflang);
 1143:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1144:     if (defined($cached)) {
 1145:         if (ref($result) eq 'HASH') {
 1146:             return %{$result};
 1147:         }
 1148:     }
 1149:     my %domdefaults;
 1150:     my %domconfig =
 1151:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
 1152:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1153:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1154:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1155:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1156:     } else {
 1157:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1158:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1159:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1160:     }
 1161:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1162:                                   $cachetime);
 1163:     return %domdefaults;
 1164: }
 1165: 
 1166: # --------------------------------------------------- Assign a key to a student
 1167: 
 1168: sub assign_access_key {
 1169: #
 1170: # a valid key looks like uname:udom#comments
 1171: # comments are being appended
 1172: #
 1173:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1174:     $kdom=
 1175:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1176:     $knum=
 1177:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1178:     $cdom=
 1179:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1180:     $cnum=
 1181:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1182:     $udom=$env{'user.name'} unless (defined($udom));
 1183:     $uname=$env{'user.domain'} unless (defined($uname));
 1184:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1185:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1186:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1187:                                                   # assigned to this person
 1188:                                                   # - this should not happen,
 1189:                                                   # unless something went wrong
 1190:                                                   # the first time around
 1191: # ready to assign
 1192:         $logentry=$1.'; '.$logentry;
 1193:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1194:                                                  $kdom,$knum) eq 'ok') {
 1195: # key now belongs to user
 1196: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1197:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1198:                 &appenv({'environment.'.$envkey => $ckey});
 1199:                 return 'ok';
 1200:             } else {
 1201:                 return 
 1202:   'error: Count not permanently assign key, will need to be re-entered later.';
 1203: 	    }
 1204:         } else {
 1205:             return 'error: Could not assign key, try again later.';
 1206:         }
 1207:     } elsif (!$existing{$ckey}) {
 1208: # the key does not exist
 1209: 	return 'error: The key does not exist';
 1210:     } else {
 1211: # the key is somebody else's
 1212: 	return 'error: The key is already in use';
 1213:     }
 1214: }
 1215: 
 1216: # ------------------------------------------ put an additional comment on a key
 1217: 
 1218: sub comment_access_key {
 1219: #
 1220: # a valid key looks like uname:udom#comments
 1221: # comments are being appended
 1222: #
 1223:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1224:     $cdom=
 1225:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1226:     $cnum=
 1227:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1228:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1229:     if ($existing{$ckey}) {
 1230:         $existing{$ckey}.='; '.$logentry;
 1231: # ready to assign
 1232:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1233:                                                  $cdom,$cnum) eq 'ok') {
 1234: 	    return 'ok';
 1235:         } else {
 1236: 	    return 'error: Count not store comment.';
 1237:         }
 1238:     } else {
 1239: # the key does not exist
 1240: 	return 'error: The key does not exist';
 1241:     }
 1242: }
 1243: 
 1244: # ------------------------------------------------------ Generate a set of keys
 1245: 
 1246: sub generate_access_keys {
 1247:     my ($number,$cdom,$cnum,$logentry)=@_;
 1248:     $cdom=
 1249:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1250:     $cnum=
 1251:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1252:     unless (&allowed('mky',$cdom)) { return 0; }
 1253:     unless (($cdom) && ($cnum)) { return 0; }
 1254:     if ($number>10000) { return 0; }
 1255:     sleep(2); # make sure don't get same seed twice
 1256:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1257:     my $total=0;
 1258:     for (my $i=1;$i<=$number;$i++) {
 1259:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1260:                   sprintf("%lx",int(100000*rand)).'-'.
 1261:                   sprintf("%lx",int(100000*rand));
 1262:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1263:        $newkey=~s/0/h/g; # and also 0 and O
 1264:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1265:        if ($existing{$newkey}) {
 1266:            $i--;
 1267:        } else {
 1268: 	  if (&put('accesskeys',
 1269:               { $newkey => '# generated '.localtime().
 1270:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1271:                            '; '.$logentry },
 1272: 		   $cdom,$cnum) eq 'ok') {
 1273:               $total++;
 1274: 	  }
 1275:        }
 1276:     }
 1277:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1278:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1279:     return $total;
 1280: }
 1281: 
 1282: # ------------------------------------------------------- Validate an accesskey
 1283: 
 1284: sub validate_access_key {
 1285:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1286:     $cdom=
 1287:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1288:     $cnum=
 1289:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1290:     $udom=$env{'user.domain'} unless (defined($udom));
 1291:     $uname=$env{'user.name'} unless (defined($uname));
 1292:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1293:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1294: }
 1295: 
 1296: # ------------------------------------- Find the section of student in a course
 1297: sub devalidate_getsection_cache {
 1298:     my ($udom,$unam,$courseid)=@_;
 1299:     my $hashid="$udom:$unam:$courseid";
 1300:     &devalidate_cache_new('getsection',$hashid);
 1301: }
 1302: 
 1303: sub courseid_to_courseurl {
 1304:     my ($courseid) = @_;
 1305:     #already url style courseid
 1306:     return $courseid if ($courseid =~ m{^/});
 1307: 
 1308:     if (exists($env{'course.'.$courseid.'.num'})) {
 1309: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1310: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1311: 	return "/$cdom/$cnum";
 1312:     }
 1313: 
 1314:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1315:     if (exists($courseinfo{'num'})) {
 1316: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1317:     }
 1318: 
 1319:     return undef;
 1320: }
 1321: 
 1322: sub getsection {
 1323:     my ($udom,$unam,$courseid)=@_;
 1324:     my $cachetime=1800;
 1325: 
 1326:     my $hashid="$udom:$unam:$courseid";
 1327:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1328:     if (defined($cached)) { return $result; }
 1329: 
 1330:     my %Pending; 
 1331:     my %Expired;
 1332:     #
 1333:     # Each role can either have not started yet (pending), be active, 
 1334:     #    or have expired.
 1335:     #
 1336:     # If there is an active role, we are done.
 1337:     #
 1338:     # If there is more than one role which has not started yet, 
 1339:     #     choose the one which will start sooner
 1340:     # If there is one role which has not started yet, return it.
 1341:     #
 1342:     # If there is more than one expired role, choose the one which ended last.
 1343:     # If there is a role which has expired, return it.
 1344:     #
 1345:     $courseid = &courseid_to_courseurl($courseid);
 1346:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1347:     foreach my $key (keys(%roleshash)) {
 1348:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1349:         my $section=$1;
 1350:         if ($key eq $courseid.'_st') { $section=''; }
 1351:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1352:         my $now=time;
 1353:         if (defined($end) && $end && ($now > $end)) {
 1354:             $Expired{$end}=$section;
 1355:             next;
 1356:         }
 1357:         if (defined($start) && $start && ($now < $start)) {
 1358:             $Pending{$start}=$section;
 1359:             next;
 1360:         }
 1361:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1362:     }
 1363:     #
 1364:     # Presumedly there will be few matching roles from the above
 1365:     # loop and the sorting time will be negligible.
 1366:     if (scalar(keys(%Pending))) {
 1367:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1368:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1369:     } 
 1370:     if (scalar(keys(%Expired))) {
 1371:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1372:         my $time = pop(@sorted);
 1373:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1374:     }
 1375:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1376: }
 1377: 
 1378: sub save_cache {
 1379:     &purge_remembered();
 1380:     #&Apache::loncommon::validate_page();
 1381:     undef(%env);
 1382:     undef($env_loaded);
 1383: }
 1384: 
 1385: my $to_remember=-1;
 1386: my %remembered;
 1387: my %accessed;
 1388: my $kicks=0;
 1389: my $hits=0;
 1390: sub make_key {
 1391:     my ($name,$id) = @_;
 1392:     if (length($id) > 65 
 1393: 	&& length(&escape($id)) > 200) {
 1394: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1395:     }
 1396:     return &escape($name.':'.$id);
 1397: }
 1398: 
 1399: sub devalidate_cache_new {
 1400:     my ($name,$id,$debug) = @_;
 1401:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1402:     $id=&make_key($name,$id);
 1403:     $memcache->delete($id);
 1404:     delete($remembered{$id});
 1405:     delete($accessed{$id});
 1406: }
 1407: 
 1408: sub is_cached_new {
 1409:     my ($name,$id,$debug) = @_;
 1410:     $id=&make_key($name,$id);
 1411:     if (exists($remembered{$id})) {
 1412: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1413: 	$accessed{$id}=[&gettimeofday()];
 1414: 	$hits++;
 1415: 	return ($remembered{$id},1);
 1416:     }
 1417:     my $value = $memcache->get($id);
 1418:     if (!(defined($value))) {
 1419: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1420: 	return (undef,undef);
 1421:     }
 1422:     if ($value eq '__undef__') {
 1423: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1424: 	$value=undef;
 1425:     }
 1426:     &make_room($id,$value,$debug);
 1427:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1428:     return ($value,1);
 1429: }
 1430: 
 1431: sub do_cache_new {
 1432:     my ($name,$id,$value,$time,$debug) = @_;
 1433:     $id=&make_key($name,$id);
 1434:     my $setvalue=$value;
 1435:     if (!defined($setvalue)) {
 1436: 	$setvalue='__undef__';
 1437:     }
 1438:     if (!defined($time) ) {
 1439: 	$time=600;
 1440:     }
 1441:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1442:     my $result = $memcache->set($id,$setvalue,$time);
 1443:     if (! $result) {
 1444: 	&logthis("caching of id -> $id  failed");
 1445: 	$memcache->disconnect_all();
 1446:     }
 1447:     # need to make a copy of $value
 1448:     &make_room($id,$value,$debug);
 1449:     return $value;
 1450: }
 1451: 
 1452: sub make_room {
 1453:     my ($id,$value,$debug)=@_;
 1454: 
 1455:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1456:                                     : $value;
 1457:     if ($to_remember<0) { return; }
 1458:     $accessed{$id}=[&gettimeofday()];
 1459:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1460:     my $to_kick;
 1461:     my $max_time=0;
 1462:     foreach my $other (keys(%accessed)) {
 1463: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1464: 	    $to_kick=$other;
 1465: 	    $max_time=&tv_interval($accessed{$other});
 1466: 	}
 1467:     }
 1468:     delete($remembered{$to_kick});
 1469:     delete($accessed{$to_kick});
 1470:     $kicks++;
 1471:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1472:     return;
 1473: }
 1474: 
 1475: sub purge_remembered {
 1476:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1477:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1478:     undef(%remembered);
 1479:     undef(%accessed);
 1480: }
 1481: # ------------------------------------- Read an entry from a user's environment
 1482: 
 1483: sub userenvironment {
 1484:     my ($udom,$unam,@what)=@_;
 1485:     my %returnhash=();
 1486:     my @answer=split(/\&/,
 1487:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1488:                       &homeserver($unam,$udom)));
 1489:     my $i;
 1490:     for ($i=0;$i<=$#what;$i++) {
 1491: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1492:     }
 1493:     return %returnhash;
 1494: }
 1495: 
 1496: # ---------------------------------------------------------- Get a studentphoto
 1497: sub studentphoto {
 1498:     my ($udom,$unam,$ext) = @_;
 1499:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1500:     if (defined($env{'request.course.id'})) {
 1501:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1502:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1503:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1504:             } else {
 1505:                 my ($result,$perm_reqd)=
 1506: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1507:                 if ($result eq 'ok') {
 1508:                     if (!($perm_reqd eq 'yes')) {
 1509:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1510:                     }
 1511:                 }
 1512:             }
 1513:         }
 1514:     } else {
 1515:         my ($result,$perm_reqd) = 
 1516: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1517:         if ($result eq 'ok') {
 1518:             if (!($perm_reqd eq 'yes')) {
 1519:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1520:             }
 1521:         }
 1522:     }
 1523:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1524: }
 1525: 
 1526: sub retrievestudentphoto {
 1527:     my ($udom,$unam,$ext,$type) = @_;
 1528:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1529:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1530:     if ($ret eq 'ok') {
 1531:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1532:         if ($type eq 'thumbnail') {
 1533:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1534:         }
 1535:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1536:         return $tokenurl;
 1537:     } else {
 1538:         if ($type eq 'thumbnail') {
 1539:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1540:         } else { 
 1541:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1542:         }
 1543:     }
 1544: }
 1545: 
 1546: # -------------------------------------------------------------------- New chat
 1547: 
 1548: sub chatsend {
 1549:     my ($newentry,$anon,$group)=@_;
 1550:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1551:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1552:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1553:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1554: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1555: 		   &escape($newentry)).':'.$group,$chome);
 1556: }
 1557: 
 1558: # ------------------------------------------ Find current version of a resource
 1559: 
 1560: sub getversion {
 1561:     my $fname=&clutter(shift);
 1562:     unless ($fname=~/^\/res\//) { return -1; }
 1563:     return &currentversion(&filelocation('',$fname));
 1564: }
 1565: 
 1566: sub currentversion {
 1567:     my $fname=shift;
 1568:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1569:     if (defined($cached)) { return $result; }
 1570:     my $author=$fname;
 1571:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1572:     my ($udom,$uname)=split(/\//,$author);
 1573:     my $home=homeserver($uname,$udom);
 1574:     if ($home eq 'no_host') { 
 1575:         return -1; 
 1576:     }
 1577:     my $answer=reply("currentversion:$fname",$home);
 1578:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1579: 	return -1;
 1580:     }
 1581:     return &do_cache_new('resversion',$fname,$answer,600);
 1582: }
 1583: 
 1584: # ----------------------------- Subscribe to a resource, return URL if possible
 1585: 
 1586: sub subscribe {
 1587:     my $fname=shift;
 1588:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1589:     $fname=~s/[\n\r]//g;
 1590:     my $author=$fname;
 1591:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1592:     my ($udom,$uname)=split(/\//,$author);
 1593:     my $home=homeserver($uname,$udom);
 1594:     if ($home eq 'no_host') {
 1595:         return 'not_found';
 1596:     }
 1597:     my $answer=reply("sub:$fname",$home);
 1598:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1599: 	$answer.=' by '.$home;
 1600:     }
 1601:     return $answer;
 1602: }
 1603:     
 1604: # -------------------------------------------------------------- Replicate file
 1605: 
 1606: sub repcopy {
 1607:     my $filename=shift;
 1608:     $filename=~s/\/+/\//g;
 1609:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1610:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1611:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1612: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1613: 	return &repcopy_userfile($filename);
 1614:     }
 1615:     $filename=~s/[\n\r]//g;
 1616:     my $transname="$filename.in.transfer";
 1617: # FIXME: this should flock
 1618:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1619:     my $remoteurl=subscribe($filename);
 1620:     if ($remoteurl =~ /^con_lost by/) {
 1621: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1622:            return 'unavailable';
 1623:     } elsif ($remoteurl eq 'not_found') {
 1624: 	   #&logthis("Subscribe returned not_found: $filename");
 1625: 	   return 'not_found';
 1626:     } elsif ($remoteurl =~ /^rejected by/) {
 1627: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1628:            return 'forbidden';
 1629:     } elsif ($remoteurl eq 'directory') {
 1630:            return 'ok';
 1631:     } else {
 1632:         my $author=$filename;
 1633:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1634:         my ($udom,$uname)=split(/\//,$author);
 1635:         my $home=homeserver($uname,$udom);
 1636:         unless ($home eq $perlvar{'lonHostID'}) {
 1637:            my @parts=split(/\//,$filename);
 1638:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1639:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1640:                &logthis("Malconfiguration for replication: $filename");
 1641: 	       return 'bad_request';
 1642:            }
 1643:            my $count;
 1644:            for ($count=5;$count<$#parts;$count++) {
 1645:                $path.="/$parts[$count]";
 1646:                if ((-e $path)!=1) {
 1647: 		   mkdir($path,0777);
 1648:                }
 1649:            }
 1650:            my $ua=new LWP::UserAgent;
 1651:            my $request=new HTTP::Request('GET',"$remoteurl");
 1652:            my $response=$ua->request($request,$transname);
 1653:            if ($response->is_error()) {
 1654: 	       unlink($transname);
 1655:                my $message=$response->status_line;
 1656:                &logthis("<font color=\"blue\">WARNING:"
 1657:                        ." LWP get: $message: $filename</font>");
 1658:                return 'unavailable';
 1659:            } else {
 1660: 	       if ($remoteurl!~/\.meta$/) {
 1661:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1662:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1663:                   if ($mresponse->is_error()) {
 1664: 		      unlink($filename.'.meta');
 1665:                       &logthis(
 1666:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1667:                   }
 1668: 	       }
 1669:                rename($transname,$filename);
 1670:                return 'ok';
 1671:            }
 1672:        }
 1673:     }
 1674: }
 1675: 
 1676: # ------------------------------------------------ Get server side include body
 1677: sub ssi_body {
 1678:     my ($filelink,%form)=@_;
 1679:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1680:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1681:     }
 1682:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1683:                                      &ssi($filelink,%form));
 1684:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1685:     $output=~s/^.*?\<body[^\>]*\>//si;
 1686:     $output=~s/\<\/body\s*\>.*?$//si;
 1687:     return $output;
 1688: }
 1689: 
 1690: # --------------------------------------------------------- Server Side Include
 1691: 
 1692: sub absolute_url {
 1693:     my ($host_name) = @_;
 1694:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1695:     if ($host_name eq '') {
 1696: 	$host_name = $ENV{'SERVER_NAME'};
 1697:     }
 1698:     return $protocol.$host_name;
 1699: }
 1700: 
 1701: #
 1702: #   Server side include.
 1703: # Parameters:
 1704: #  fn     Possibly encrypted resource name/id.
 1705: #  form   Hash that describes how the rendering should be done
 1706: #         and other things.
 1707: # Returns:
 1708: #   Scalar context: The content of the response.
 1709: #   Array context:  2 element list of the content and the full response object.
 1710: #     
 1711: sub ssi {
 1712: 
 1713:     my ($fn,%form)=@_;
 1714:     my $ua=new LWP::UserAgent;
 1715:     my $request;
 1716: 
 1717:     $form{'no_update_last_known'}=1;
 1718:     &Apache::lonenc::check_encrypt(\$fn);
 1719:     if (%form) {
 1720:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1721:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1722:     } else {
 1723:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1724:     }
 1725: 
 1726:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1727:     my $response=$ua->request($request);
 1728: 
 1729:     if (wantarray) {
 1730: 	return ($response->content, $response);
 1731:     } else {
 1732: 	return $response->content;
 1733:     }
 1734: }
 1735: 
 1736: sub externalssi {
 1737:     my ($url)=@_;
 1738:     my $ua=new LWP::UserAgent;
 1739:     my $request=new HTTP::Request('GET',$url);
 1740:     my $response=$ua->request($request);
 1741:     return $response->content;
 1742: }
 1743: 
 1744: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1745: 
 1746: sub allowuploaded {
 1747:     my ($srcurl,$url)=@_;
 1748:     $url=&clutter(&declutter($url));
 1749:     my $dir=$url;
 1750:     $dir=~s/\/[^\/]+$//;
 1751:     my %httpref=();
 1752:     my $httpurl=&hreflocation('',$url);
 1753:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1754:     &Apache::lonnet::appenv(\%httpref);
 1755: }
 1756: 
 1757: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1758: # input: action, courseID, current domain, intended
 1759: #        path to file, source of file, instruction to parse file for objects,
 1760: #        ref to hash for embedded objects,
 1761: #        ref to hash for codebase of java objects.
 1762: #
 1763: # output: url to file (if action was uploaddoc), 
 1764: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1765: #
 1766: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1767: # course.
 1768: #
 1769: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1770: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1771: #          course's home server.
 1772: #
 1773: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1774: #          be copied from $source (current location) to 
 1775: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1776: #         and will then be copied to
 1777: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1778: #         course's home server.
 1779: #
 1780: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1781: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1782: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1783: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1784: #         in course's home server.
 1785: #
 1786: 
 1787: sub process_coursefile {
 1788:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1789:     my $fetchresult;
 1790:     my $home=&homeserver($docuname,$docudom);
 1791:     if ($action eq 'propagate') {
 1792:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1793: 			     $home);
 1794:     } else {
 1795:         my $fpath = '';
 1796:         my $fname = $file;
 1797:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1798:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1799:         my $filepath = &build_filepath($fpath);
 1800:         if ($action eq 'copy') {
 1801:             if ($source eq '') {
 1802:                 $fetchresult = 'no source file';
 1803:                 return $fetchresult;
 1804:             } else {
 1805:                 my $destination = $filepath.'/'.$fname;
 1806:                 rename($source,$destination);
 1807:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1808:                                  $home);
 1809:             }
 1810:         } elsif ($action eq 'uploaddoc') {
 1811:             open(my $fh,'>'.$filepath.'/'.$fname);
 1812:             print $fh $env{'form.'.$source};
 1813:             close($fh);
 1814:             if ($parser eq 'parse') {
 1815:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1816:                 unless ($parse_result eq 'ok') {
 1817:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1818:                 }
 1819:             }
 1820:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1821:                                  $home);
 1822:             if ($fetchresult eq 'ok') {
 1823:                 return '/uploaded/'.$fpath.'/'.$fname;
 1824:             } else {
 1825:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1826:                         ' to host '.$home.': '.$fetchresult);
 1827:                 return '/adm/notfound.html';
 1828:             }
 1829:         }
 1830:     }
 1831:     unless ( $fetchresult eq 'ok') {
 1832:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1833:              ' to host '.$home.': '.$fetchresult);
 1834:     }
 1835:     return $fetchresult;
 1836: }
 1837: 
 1838: sub build_filepath {
 1839:     my ($fpath) = @_;
 1840:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1841:     unless ($fpath eq '') {
 1842:         my @parts=split('/',$fpath);
 1843:         foreach my $part (@parts) {
 1844:             $filepath.= '/'.$part;
 1845:             if ((-e $filepath)!=1) {
 1846:                 mkdir($filepath,0777);
 1847:             }
 1848:         }
 1849:     }
 1850:     return $filepath;
 1851: }
 1852: 
 1853: sub store_edited_file {
 1854:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1855:     my $file = $primary_url;
 1856:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1857:     my $fpath = '';
 1858:     my $fname = $file;
 1859:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1860:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1861:     my $filepath = &build_filepath($fpath);
 1862:     open(my $fh,'>'.$filepath.'/'.$fname);
 1863:     print $fh $content;
 1864:     close($fh);
 1865:     my $home=&homeserver($docuname,$docudom);
 1866:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1867: 			  $home);
 1868:     if ($$fetchresult eq 'ok') {
 1869:         return '/uploaded/'.$fpath.'/'.$fname;
 1870:     } else {
 1871:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1872: 		 ' to host '.$home.': '.$$fetchresult);
 1873:         return '/adm/notfound.html';
 1874:     }
 1875: }
 1876: 
 1877: sub clean_filename {
 1878:     my ($fname,$args)=@_;
 1879: # Replace Windows backslashes by forward slashes
 1880:     $fname=~s/\\/\//g;
 1881:     if (!$args->{'keep_path'}) {
 1882:         # Get rid of everything but the actual filename
 1883: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1884:     }
 1885: # Replace spaces by underscores
 1886:     $fname=~s/\s+/\_/g;
 1887: # Replace all other weird characters by nothing
 1888:     $fname=~s{[^/\w\.\-]}{}g;
 1889: # Replace all .\d. sequences with _\d. so they no longer look like version
 1890: # numbers
 1891:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1892:     return $fname;
 1893: }
 1894: 
 1895: # --------------- Take an uploaded file and put it into the userfiles directory
 1896: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1897: #                    the desired filenam is in $env{"form.$formname.filename"}
 1898: #        $coursedoc - if true up to the current course
 1899: #                     if false
 1900: #        $subdir - directory in userfile to store the file into
 1901: #        $parser - instruction to parse file for objects ($parser = parse)    
 1902: #        $allfiles - reference to hash for embedded objects
 1903: #        $codebase - reference to hash for codebase of java objects
 1904: #        $desuname - username for permanent storage of uploaded file
 1905: #        $dsetudom - domain for permanaent storage of uploaded file
 1906: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1907: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1908: # 
 1909: # output: url of file in userspace, or error: <message> 
 1910: #             or /adm/notfound.html if failure to upload occurse
 1911: 
 1912: 
 1913: sub userfileupload {
 1914:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1915:         $destudom,$thumbwidth,$thumbheight)=@_;
 1916:     if (!defined($subdir)) { $subdir='unknown'; }
 1917:     my $fname=$env{'form.'.$formname.'.filename'};
 1918:     $fname=&clean_filename($fname);
 1919: # See if there is anything left
 1920:     unless ($fname) { return 'error: no uploaded file'; }
 1921:     chop($env{'form.'.$formname});
 1922:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1923:         my $now = time;
 1924:         my $filepath = 'tmp/helprequests/'.$now;
 1925:         my @parts=split(/\//,$filepath);
 1926:         my $fullpath = $perlvar{'lonDaemons'};
 1927:         for (my $i=0;$i<@parts;$i++) {
 1928:             $fullpath .= '/'.$parts[$i];
 1929:             if ((-e $fullpath)!=1) {
 1930:                 mkdir($fullpath,0777);
 1931:             }
 1932:         }
 1933:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1934:         print $fh $env{'form.'.$formname};
 1935:         close($fh);
 1936:         return $fullpath.'/'.$fname;
 1937:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1938:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1939:                        '_'.$env{'user.domain'}.'/pending';
 1940:         my @parts=split(/\//,$filepath);
 1941:         my $fullpath = $perlvar{'lonDaemons'};
 1942:         for (my $i=0;$i<@parts;$i++) {
 1943:             $fullpath .= '/'.$parts[$i];
 1944:             if ((-e $fullpath)!=1) {
 1945:                 mkdir($fullpath,0777);
 1946:             }
 1947:         }
 1948:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1949:         print $fh $env{'form.'.$formname};
 1950:         close($fh);
 1951:         return $fullpath.'/'.$fname;
 1952:     }
 1953:     
 1954: # Create the directory if not present
 1955:     $fname="$subdir/$fname";
 1956:     if ($coursedoc) {
 1957: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1958: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1959:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1960:             return &finishuserfileupload($docuname,$docudom,
 1961: 					 $formname,$fname,$parser,$allfiles,
 1962: 					 $codebase,$thumbwidth,$thumbheight);
 1963:         } else {
 1964:             $fname=$env{'form.folder'}.'/'.$fname;
 1965:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1966: 				       $fname,$formname,$parser,
 1967: 				       $allfiles,$codebase);
 1968:         }
 1969:     } elsif (defined($destuname)) {
 1970:         my $docuname=$destuname;
 1971:         my $docudom=$destudom;
 1972: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1973: 				     $parser,$allfiles,$codebase,
 1974:                                      $thumbwidth,$thumbheight);
 1975:         
 1976:     } else {
 1977:         my $docuname=$env{'user.name'};
 1978:         my $docudom=$env{'user.domain'};
 1979:         if (exists($env{'form.group'})) {
 1980:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1981:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1982:         }
 1983: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1984: 				     $parser,$allfiles,$codebase,
 1985:                                      $thumbwidth,$thumbheight);
 1986:     }
 1987: }
 1988: 
 1989: sub finishuserfileupload {
 1990:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1991:         $thumbwidth,$thumbheight) = @_;
 1992:     my $path=$docudom.'/'.$docuname.'/';
 1993:     my $filepath=$perlvar{'lonDocRoot'};
 1994:     my ($fnamepath,$file,$fetchthumb);
 1995:     $file=$fname;
 1996:     if ($fname=~m|/|) {
 1997:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1998: 	$path.=$fnamepath.'/';
 1999:     }
 2000:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2001:     my $count;
 2002:     for ($count=4;$count<=$#parts;$count++) {
 2003:         $filepath.="/$parts[$count]";
 2004:         if ((-e $filepath)!=1) {
 2005: 	    mkdir($filepath,0777);
 2006:         }
 2007:     }
 2008: # Save the file
 2009:     {
 2010: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2011: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2012: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2013: 	    return '/adm/notfound.html';
 2014: 	}
 2015: 	if (!print FH ($env{'form.'.$formname})) {
 2016: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2017: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2018: 	    return '/adm/notfound.html';
 2019: 	}
 2020: 	close(FH);
 2021:     }
 2022:     if ($parser eq 'parse') {
 2023:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 2024: 						   $codebase);
 2025:         unless ($parse_result eq 'ok') {
 2026:             &logthis('Failed to parse '.$filepath.$file.
 2027: 		     ' for embedded media: '.$parse_result); 
 2028:         }
 2029:     }
 2030:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2031:         my $input = $filepath.'/'.$file;
 2032:         my $output = $filepath.'/'.'tn-'.$file;
 2033:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2034:         system("convert -sample $thumbsize $input $output");
 2035:         if (-e $filepath.'/'.'tn-'.$file) {
 2036:             $fetchthumb  = 1; 
 2037:         }
 2038:     }
 2039:  
 2040: # Notify homeserver to grep it
 2041: #
 2042:     my $docuhome=&homeserver($docuname,$docudom);
 2043:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2044:     if ($fetchresult eq 'ok') {
 2045:         if ($fetchthumb) {
 2046:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2047:             if ($thumbresult ne 'ok') {
 2048:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2049:                          $docuhome.': '.$thumbresult);
 2050:             }
 2051:         }
 2052: #
 2053: # Return the URL to it
 2054:         return '/uploaded/'.$path.$file;
 2055:     } else {
 2056:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2057: 		 ': '.$fetchresult);
 2058:         return '/adm/notfound.html';
 2059:     }
 2060: }
 2061: 
 2062: sub extract_embedded_items {
 2063:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2064:     my @state = ();
 2065:     my %javafiles = (
 2066:                       codebase => '',
 2067:                       code => '',
 2068:                       archive => ''
 2069:                     );
 2070:     my %mediafiles = (
 2071:                       src => '',
 2072:                       movie => '',
 2073:                      );
 2074:     my $p;
 2075:     if ($content) {
 2076:         $p = HTML::LCParser->new($content);
 2077:     } else {
 2078:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2079:     }
 2080:     while (my $t=$p->get_token()) {
 2081: 	if ($t->[0] eq 'S') {
 2082: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2083: 	    push(@state, $tagname);
 2084:             if (lc($tagname) eq 'allow') {
 2085:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2086:             }
 2087: 	    if (lc($tagname) eq 'img') {
 2088: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2089: 	    }
 2090: 	    if (lc($tagname) eq 'a') {
 2091: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2092: 	    }
 2093:             if (lc($tagname) eq 'script') {
 2094:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2095:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2096:                 } else {
 2097:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2098:                 }
 2099:             }
 2100:             if (lc($tagname) eq 'link') {
 2101:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2102:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2103:                 }
 2104:             }
 2105: 	    if (lc($tagname) eq 'object' ||
 2106: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2107: 		foreach my $item (keys(%javafiles)) {
 2108: 		    $javafiles{$item} = '';
 2109: 		}
 2110: 	    }
 2111: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2112: 		my $name = lc($attr->{'name'});
 2113: 		foreach my $item (keys(%javafiles)) {
 2114: 		    if ($name eq $item) {
 2115: 			$javafiles{$item} = $attr->{'value'};
 2116: 			last;
 2117: 		    }
 2118: 		}
 2119: 		foreach my $item (keys(%mediafiles)) {
 2120: 		    if ($name eq $item) {
 2121: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2122: 			last;
 2123: 		    }
 2124: 		}
 2125: 	    }
 2126: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2127: 		foreach my $item (keys(%javafiles)) {
 2128: 		    if ($attr->{$item}) {
 2129: 			$javafiles{$item} = $attr->{$item};
 2130: 			last;
 2131: 		    }
 2132: 		}
 2133: 		foreach my $item (keys(%mediafiles)) {
 2134: 		    if ($attr->{$item}) {
 2135: 			&add_filetype($allfiles,$attr->{$item},$item);
 2136: 			last;
 2137: 		    }
 2138: 		}
 2139: 	    }
 2140: 	} elsif ($t->[0] eq 'E') {
 2141: 	    my ($tagname) = ($t->[1]);
 2142: 	    if ($javafiles{'codebase'} ne '') {
 2143: 		$javafiles{'codebase'} .= '/';
 2144: 	    }  
 2145: 	    if (lc($tagname) eq 'applet' ||
 2146: 		lc($tagname) eq 'object' ||
 2147: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2148: 		) {
 2149: 		foreach my $item (keys(%javafiles)) {
 2150: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2151: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2152: 			&add_filetype($allfiles,$file,$item);
 2153: 		    }
 2154: 		}
 2155: 	    } 
 2156: 	    pop @state;
 2157: 	}
 2158:     }
 2159:     return 'ok';
 2160: }
 2161: 
 2162: sub add_filetype {
 2163:     my ($allfiles,$file,$type)=@_;
 2164:     if (exists($allfiles->{$file})) {
 2165: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2166: 	    push(@{$allfiles->{$file}}, &escape($type));
 2167: 	}
 2168:     } else {
 2169: 	@{$allfiles->{$file}} = (&escape($type));
 2170:     }
 2171: }
 2172: 
 2173: sub removeuploadedurl {
 2174:     my ($url)=@_;
 2175:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2176:     return &removeuserfile($uname,$udom,$fname);
 2177: }
 2178: 
 2179: sub removeuserfile {
 2180:     my ($docuname,$docudom,$fname)=@_;
 2181:     my $home=&homeserver($docuname,$docudom);
 2182:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2183:     if ($result eq 'ok') {
 2184:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2185:             my $metafile = $fname.'.meta';
 2186:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2187: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2188:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2189:             my $sqlresult = 
 2190:                 &update_portfolio_table($docuname,$docudom,$file,
 2191:                                         'portfolio_metadata',$group,
 2192:                                         'delete');
 2193:         }
 2194:     }
 2195:     return $result;
 2196: }
 2197: 
 2198: sub mkdiruserfile {
 2199:     my ($docuname,$docudom,$dir)=@_;
 2200:     my $home=&homeserver($docuname,$docudom);
 2201:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2202: }
 2203: 
 2204: sub renameuserfile {
 2205:     my ($docuname,$docudom,$old,$new)=@_;
 2206:     my $home=&homeserver($docuname,$docudom);
 2207:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2208:                         &escape("$old").':'.&escape("$new"),$home);
 2209:     if ($result eq 'ok') {
 2210:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2211:             my $oldmeta = $old.'.meta';
 2212:             my $newmeta = $new.'.meta';
 2213:             my $metaresult = 
 2214:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2215: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2216:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2217:             my $sqlresult = 
 2218:                 &update_portfolio_table($docuname,$docudom,$file,
 2219:                                         'portfolio_metadata',$group,
 2220:                                         'delete');
 2221:         }
 2222:     }
 2223:     return $result;
 2224: }
 2225: 
 2226: # ------------------------------------------------------------------------- Log
 2227: 
 2228: sub log {
 2229:     my ($dom,$nam,$hom,$what)=@_;
 2230:     return critical("log:$dom:$nam:$what",$hom);
 2231: }
 2232: 
 2233: # ------------------------------------------------------------------ Course Log
 2234: #
 2235: # This routine flushes several buffers of non-mission-critical nature
 2236: #
 2237: 
 2238: sub flushcourselogs {
 2239:     &logthis('Flushing log buffers');
 2240: #
 2241: # course logs
 2242: # This is a log of all transactions in a course, which can be used
 2243: # for data mining purposes
 2244: #
 2245: # It also collects the courseid database, which lists last transaction
 2246: # times and course titles for all courseids
 2247: #
 2248:     my %courseidbuffer=();
 2249:     foreach my $crsid (keys(%courselogs)) {
 2250:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2251: 		          &escape($courselogs{$crsid}),
 2252: 		          $coursehombuf{$crsid}) eq 'ok') {
 2253: 	    delete $courselogs{$crsid};
 2254:         } else {
 2255:             &logthis('Failed to flush log buffer for '.$crsid);
 2256:             if (length($courselogs{$crsid})>40000) {
 2257:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2258:                         " exceeded maximum size, deleting.</font>");
 2259:                delete $courselogs{$crsid};
 2260:             }
 2261:         }
 2262:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2263:             'description' => $coursedescrbuf{$crsid},
 2264:             'inst_code'    => $courseinstcodebuf{$crsid},
 2265:             'type'        => $coursetypebuf{$crsid},
 2266:             'owner'       => $courseownerbuf{$crsid},
 2267:         };
 2268:     }
 2269: #
 2270: # Write course id database (reverse lookup) to homeserver of courses 
 2271: # Is used in pickcourse
 2272: #
 2273:     foreach my $crs_home (keys(%courseidbuffer)) {
 2274:         my $response = &courseidput(&host_domain($crs_home),
 2275:                                     $courseidbuffer{$crs_home},
 2276:                                     $crs_home,'timeonly');
 2277:     }
 2278: #
 2279: # File accesses
 2280: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2281: #
 2282:     foreach my $entry (keys(%accesshash)) {
 2283:         if ($entry =~ /___count$/) {
 2284:             my ($dom,$name);
 2285:             ($dom,$name,undef)=
 2286: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2287:             if (! defined($dom) || $dom eq '' || 
 2288:                 ! defined($name) || $name eq '') {
 2289:                 my $cid = $env{'request.course.id'};
 2290:                 $dom  = $env{'request.'.$cid.'.domain'};
 2291:                 $name = $env{'request.'.$cid.'.num'};
 2292:             }
 2293:             my $value = $accesshash{$entry};
 2294:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2295:             my %temphash=($url => $value);
 2296:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2297:             if ($result eq 'ok') {
 2298:                 delete $accesshash{$entry};
 2299:             } elsif ($result eq 'unknown_cmd') {
 2300:                 # Target server has old code running on it.
 2301:                 my %temphash=($entry => $value);
 2302:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2303:                     delete $accesshash{$entry};
 2304:                 }
 2305:             }
 2306:         } else {
 2307:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2308:             my %temphash=($entry => $accesshash{$entry});
 2309:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2310:                 delete $accesshash{$entry};
 2311:             }
 2312:         }
 2313:     }
 2314: #
 2315: # Roles
 2316: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2317: #
 2318:     foreach my $entry (keys(%userrolehash)) {
 2319:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2320: 	    split(/\:/,$entry);
 2321:         if (&Apache::lonnet::put('nohist_userroles',
 2322:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2323:                 $rudom,$runame) eq 'ok') {
 2324: 	    delete $userrolehash{$entry};
 2325:         }
 2326:     }
 2327: #
 2328: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2329: #
 2330:     my %domrolebuffer = ();
 2331:     foreach my $entry (keys %domainrolehash) {
 2332:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2333:         if ($domrolebuffer{$rudom}) {
 2334:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2335:                       '='.&escape($domainrolehash{$entry});
 2336:         } else {
 2337:             $domrolebuffer{$rudom}.=&escape($entry).
 2338:                       '='.&escape($domainrolehash{$entry});
 2339:         }
 2340:         delete $domainrolehash{$entry};
 2341:     }
 2342:     foreach my $dom (keys(%domrolebuffer)) {
 2343: 	my %servers = &get_servers($dom,'library');
 2344: 	foreach my $tryserver (keys(%servers)) {
 2345: 	    unless (&reply('domroleput:'.$dom.':'.
 2346: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2347: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2348: 	    }
 2349:         }
 2350:     }
 2351:     $dumpcount++;
 2352: }
 2353: 
 2354: sub courselog {
 2355:     my $what=shift;
 2356:     $what=time.':'.$what;
 2357:     unless ($env{'request.course.id'}) { return ''; }
 2358:     $coursedombuf{$env{'request.course.id'}}=
 2359:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2360:     $coursenumbuf{$env{'request.course.id'}}=
 2361:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2362:     $coursehombuf{$env{'request.course.id'}}=
 2363:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2364:     $coursedescrbuf{$env{'request.course.id'}}=
 2365:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2366:     $courseinstcodebuf{$env{'request.course.id'}}=
 2367:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2368:     $courseownerbuf{$env{'request.course.id'}}=
 2369:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2370:     $coursetypebuf{$env{'request.course.id'}}=
 2371:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2372:     if (defined $courselogs{$env{'request.course.id'}}) {
 2373: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2374:     } else {
 2375: 	$courselogs{$env{'request.course.id'}}.=$what;
 2376:     }
 2377:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2378: 	&flushcourselogs();
 2379:     }
 2380: }
 2381: 
 2382: sub courseacclog {
 2383:     my $fnsymb=shift;
 2384:     unless ($env{'request.course.id'}) { return ''; }
 2385:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2386:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2387:         $what.=':POST';
 2388:         # FIXME: Probably ought to escape things....
 2389: 	foreach my $key (keys(%env)) {
 2390:             if ($key=~/^form\.(.*)/) {
 2391: 		$what.=':'.$1.'='.$env{$key};
 2392:             }
 2393:         }
 2394:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2395:         # FIXME: We should not be depending on a form parameter that someone
 2396:         # editing lonsearchcat.pm might change in the future.
 2397:         if ($env{'form.phase'} eq 'course_search') {
 2398:             $what.= ':POST';
 2399:             # FIXME: Probably ought to escape things....
 2400:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2401:                                  'crsdiscuss') {
 2402:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2403:             }
 2404:         }
 2405:     }
 2406:     &courselog($what);
 2407: }
 2408: 
 2409: sub countacc {
 2410:     my $url=&declutter(shift);
 2411:     return if (! defined($url) || $url eq '');
 2412:     unless ($env{'request.course.id'}) { return ''; }
 2413:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2414:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2415:     $accesshash{$key}++;
 2416: }
 2417: 
 2418: sub linklog {
 2419:     my ($from,$to)=@_;
 2420:     $from=&declutter($from);
 2421:     $to=&declutter($to);
 2422:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2423:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2424: }
 2425:   
 2426: sub userrolelog {
 2427:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2428:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2429:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2430:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2431:         ($trole=~/^ta/)) {
 2432:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2433:        $userrolehash
 2434:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2435:                     =$tend.':'.$tstart;
 2436:     }
 2437:     if (($env{'request.role'} =~ /dc\./) &&
 2438: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2439: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2440: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2441:        $userrolehash
 2442:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2443:                     =$tend.':'.$tstart;
 2444:     }
 2445:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2446:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2447:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2448:         ($trole=~/^sc/)) {
 2449:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2450:        $domainrolehash
 2451:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2452:                     = $tend.':'.$tstart;
 2453:     }
 2454: }
 2455: 
 2456: sub get_course_adv_roles {
 2457:     my ($cid,$codes) = @_;
 2458:     $cid=$env{'request.course.id'} unless (defined($cid));
 2459:     my %coursehash=&coursedescription($cid);
 2460:     my %nothide=();
 2461:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2462:         if ($user !~ /:/) {
 2463: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2464:         } else {
 2465:             $nothide{$user}=1;
 2466:         }
 2467:     }
 2468:     my %returnhash=();
 2469:     my %dumphash=
 2470:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2471:     my $now=time;
 2472:     foreach my $entry (keys %dumphash) {
 2473: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2474:         if (($tstart) && ($tstart<0)) { next; }
 2475:         if (($tend) && ($tend<$now)) { next; }
 2476:         if (($tstart) && ($now<$tstart)) { next; }
 2477:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2478: 	if ($username eq '' || $domain eq '') { next; }
 2479: 	if ((&privileged($username,$domain)) && 
 2480: 	    (!$nothide{$username.':'.$domain})) { next; }
 2481: 	if ($role eq 'cr') { next; }
 2482:         if ($codes) {
 2483:             if ($section) { $role .= ':'.$section; }
 2484:             if ($returnhash{$role}) {
 2485:                 $returnhash{$role}.=','.$username.':'.$domain;
 2486:             } else {
 2487:                 $returnhash{$role}=$username.':'.$domain;
 2488:             }
 2489:         } else {
 2490:             my $key=&plaintext($role);
 2491:             if ($section) { $key.=' (Section '.$section.')'; }
 2492:             if ($returnhash{$key}) {
 2493: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2494:             } else {
 2495:                 $returnhash{$key}=$username.':'.$domain;
 2496:             }
 2497:         }
 2498:     }
 2499:     return %returnhash;
 2500: }
 2501: 
 2502: sub get_my_roles {
 2503:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2504:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2505:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2506:     my (%dumphash,%nothide);
 2507:     if ($context eq 'userroles') { 
 2508:         %dumphash = &dump('roles',$udom,$uname);
 2509:     } else {
 2510:         %dumphash=
 2511:             &dump('nohist_userroles',$udom,$uname);
 2512:         if ($hidepriv) {
 2513:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2514:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2515:                 if ($user !~ /:/) {
 2516:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2517:                 } else {
 2518:                     $nothide{$user} = 1;
 2519:                 }
 2520:             }
 2521:         }
 2522:     }
 2523:     my %returnhash=();
 2524:     my $now=time;
 2525:     foreach my $entry (keys(%dumphash)) {
 2526:         my ($role,$tend,$tstart);
 2527:         if ($context eq 'userroles') {
 2528: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2529:         } else {
 2530:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2531:         }
 2532:         if (($tstart) && ($tstart<0)) { next; }
 2533:         my $status = 'active';
 2534:         if (($tend) && ($tend<=$now)) {
 2535:             $status = 'previous';
 2536:         } 
 2537:         if (($tstart) && ($now<$tstart)) {
 2538:             $status = 'future';
 2539:         }
 2540:         if (ref($types) eq 'ARRAY') {
 2541:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2542:                 next;
 2543:             } 
 2544:         } else {
 2545:             if ($status ne 'active') {
 2546:                 next;
 2547:             }
 2548:         }
 2549:         my ($rolecode,$username,$domain,$section,$area);
 2550:         if ($context eq 'userroles') {
 2551:             ($area,$rolecode) = split(/_/,$entry);
 2552:             (undef,$domain,$username,$section) = split(/\//,$area);
 2553:         } else {
 2554:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2555:         }
 2556:         if (ref($roledoms) eq 'ARRAY') {
 2557:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2558:                 next;
 2559:             }
 2560:         }
 2561:         if (ref($roles) eq 'ARRAY') {
 2562:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2563:                 if ($role =~ /^cr\//) {
 2564:                     if (!grep(/^cr$/,@{$roles})) {
 2565:                         next;
 2566:                     }
 2567:                 } else {
 2568:                     next;
 2569:                 }
 2570:             }
 2571:         }
 2572:         if ($hidepriv) {
 2573:             if ((&privileged($username,$domain)) &&
 2574:                 (!$nothide{$username.':'.$domain})) { 
 2575:                 next;
 2576:             }
 2577:         }
 2578:         if ($withsec) {
 2579:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2580:                 $tstart.':'.$tend;
 2581:         } else {
 2582:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2583:         }
 2584:     }
 2585:     return %returnhash;
 2586: }
 2587: 
 2588: # ----------------------------------------------------- Frontpage Announcements
 2589: #
 2590: #
 2591: 
 2592: sub postannounce {
 2593:     my ($server,$text)=@_;
 2594:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2595:     unless ($text=~/\w/) { $text=''; }
 2596:     return &reply('setannounce:'.&escape($text),$server);
 2597: }
 2598: 
 2599: sub getannounce {
 2600: 
 2601:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2602: 	my $announcement='';
 2603: 	while (my $line = <$fh>) { $announcement .= $line; }
 2604: 	close($fh);
 2605: 	if ($announcement=~/\w/) { 
 2606: 	    return 
 2607:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2608:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2609: 	} else {
 2610: 	    return '';
 2611: 	}
 2612:     } else {
 2613: 	return '';
 2614:     }
 2615: }
 2616: 
 2617: # ---------------------------------------------------------- Course ID routines
 2618: # Deal with domain's nohist_courseid.db files
 2619: #
 2620: 
 2621: sub courseidput {
 2622:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2623:     my $outcome;
 2624:     if ($caller eq 'timeonly') {
 2625:         my $cids = '';
 2626:         foreach my $item (keys(%$storehash)) {
 2627:             $cids.=&escape($item).'&';
 2628:         }
 2629:         $cids=~s/\&$//;
 2630:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2631:                           $coursehome);       
 2632:     } else {
 2633:         my $items = '';
 2634:         foreach my $item (keys(%$storehash)) {
 2635:             $items.= &escape($item).'='.
 2636:                      &freeze_escape($$storehash{$item}).'&';
 2637:         }
 2638:         $items=~s/\&$//;
 2639:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2640:                           $coursehome);
 2641:     }
 2642:     if ($outcome eq 'unknown_cmd') {
 2643:         my $what;
 2644:         foreach my $cid (keys(%$storehash)) {
 2645:             $what .= &escape($cid).'=';
 2646:             foreach my $item ('description','inst_code','owner','type') {
 2647:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2648:             }
 2649:             $what =~ s/\:$/&/;
 2650:         }
 2651:         $what =~ s/\&$//;  
 2652:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2653:     } else {
 2654:         return $outcome;
 2655:     }
 2656: }
 2657: 
 2658: sub courseiddump {
 2659:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2660:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2661:         $selfenrollonly)=@_;
 2662:     my $as_hash = 1;
 2663:     my %returnhash;
 2664:     if (!$domfilter) { $domfilter=''; }
 2665:     my %libserv = &all_library();
 2666:     foreach my $tryserver (keys(%libserv)) {
 2667:         if ( (  $hostidflag == 1 
 2668: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2669: 	     || (!defined($hostidflag)) ) {
 2670: 
 2671: 	    if (($domfilter eq '') ||
 2672: 		(&host_domain($tryserver) eq $domfilter)) {
 2673:                 my $rep = 
 2674:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2675:                          $sincefilter.':'.&escape($descfilter).':'.
 2676:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2677:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2678:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2679:                          &escape($selfenrollonly),$tryserver);
 2680:                 my @pairs=split(/\&/,$rep);
 2681:                 foreach my $item (@pairs) {
 2682:                     my ($key,$value)=split(/\=/,$item,2);
 2683:                     $key = &unescape($key);
 2684:                     next if ($key =~ /^error: 2 /);
 2685:                     my $result = &thaw_unescape($value);
 2686:                     if (ref($result) eq 'HASH') {
 2687:                         $returnhash{$key}=$result;
 2688:                     } else {
 2689:                         my @responses = split(/:/,$value);
 2690:                         my @items = ('description','inst_code','owner','type');
 2691:                         for (my $i=0; $i<@responses; $i++) {
 2692:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2693:                         }
 2694:                     } 
 2695:                 }
 2696:             }
 2697:         }
 2698:     }
 2699:     return %returnhash;
 2700: }
 2701: 
 2702: # ---------------------------------------------------------- DC e-mail
 2703: 
 2704: sub dcmailput {
 2705:     my ($domain,$msgid,$message,$server)=@_;
 2706:     my $status = &Apache::lonnet::critical(
 2707:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2708:        &escape($message),$server);
 2709:     return $status;
 2710: }
 2711: 
 2712: sub dcmaildump {
 2713:     my ($dom,$startdate,$enddate,$senders) = @_;
 2714:     my %returnhash=();
 2715: 
 2716:     if (defined(&domain($dom,'primary'))) {
 2717:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2718:                                                          &escape($enddate).':';
 2719: 	my @esc_senders=map { &escape($_)} @$senders;
 2720: 	$cmd.=&escape(join('&',@esc_senders));
 2721: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2722:             my ($key,$value) = split(/\=/,$line,2);
 2723:             if (($key) && ($value)) {
 2724:                 $returnhash{&unescape($key)} = &unescape($value);
 2725:             }
 2726:         }
 2727:     }
 2728:     return %returnhash;
 2729: }
 2730: # ---------------------------------------------------------- Domain roles
 2731: 
 2732: sub get_domain_roles {
 2733:     my ($dom,$roles,$startdate,$enddate)=@_;
 2734:     if (undef($startdate) || $startdate eq '') {
 2735:         $startdate = '.';
 2736:     }
 2737:     if (undef($enddate) || $enddate eq '') {
 2738:         $enddate = '.';
 2739:     }
 2740:     my $rolelist;
 2741:     if (ref($roles) eq 'ARRAY') {
 2742:         $rolelist = join(':',@{$roles});
 2743:     }
 2744:     my %personnel = ();
 2745: 
 2746:     my %servers = &get_servers($dom,'library');
 2747:     foreach my $tryserver (keys(%servers)) {
 2748: 	%{$personnel{$tryserver}}=();
 2749: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2750: 					    &escape($startdate).':'.
 2751: 					    &escape($enddate).':'.
 2752: 					    &escape($rolelist), $tryserver))) {
 2753: 	    my ($key,$value) = split(/\=/,$line,2);
 2754: 	    if (($key) && ($value)) {
 2755: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2756: 	    }
 2757: 	}
 2758:     }
 2759:     return %personnel;
 2760: }
 2761: 
 2762: # ----------------------------------------------------------- Check out an item
 2763: 
 2764: sub get_first_access {
 2765:     my ($type,$argsymb)=@_;
 2766:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2767:     if ($argsymb) { $symb=$argsymb; }
 2768:     my ($map,$id,$res)=&decode_symb($symb);
 2769:     if ($type eq 'course') {
 2770: 	$res='course';
 2771:     } elsif ($type eq 'map') {
 2772: 	$res=&symbread($map);
 2773:     } else {
 2774: 	$res=$symb;
 2775:     }
 2776:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2777:     return $times{"$courseid\0$res"};
 2778: }
 2779: 
 2780: sub set_first_access {
 2781:     my ($type)=@_;
 2782:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2783:     my ($map,$id,$res)=&decode_symb($symb);
 2784:     if ($type eq 'course') {
 2785: 	$res='course';
 2786:     } elsif ($type eq 'map') {
 2787: 	$res=&symbread($map);
 2788:     } else {
 2789: 	$res=$symb;
 2790:     }
 2791:     my $firstaccess=&get_first_access($type,$symb);
 2792:     if (!$firstaccess) {
 2793: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2794:     }
 2795:     return 'already_set';
 2796: }
 2797: 
 2798: sub checkout {
 2799:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2800:     my $now=time;
 2801:     my $lonhost=$perlvar{'lonHostID'};
 2802:     my $infostr=&escape(
 2803:                  'CHECKOUTTOKEN&'.
 2804:                  $tuname.'&'.
 2805:                  $tudom.'&'.
 2806:                  $tcrsid.'&'.
 2807:                  $symb.'&'.
 2808: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2809:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2810:     if ($token=~/^error\:/) { 
 2811:         &logthis("<font color=\"blue\">WARNING: ".
 2812:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2813:                  "</font>");
 2814:         return ''; 
 2815:     }
 2816: 
 2817:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2818:     $token=~tr/a-z/A-Z/;
 2819: 
 2820:     my %infohash=('resource.0.outtoken' => $token,
 2821:                   'resource.0.checkouttime' => $now,
 2822:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2823: 
 2824:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2825:        return '';
 2826:     } else {
 2827:         &logthis("<font color=\"blue\">WARNING: ".
 2828:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2829:                  "</font>");
 2830:     }    
 2831: 
 2832:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2833:                          &escape('Checkout '.$infostr.' - '.
 2834:                                                  $token)) ne 'ok') {
 2835: 	return '';
 2836:     } else {
 2837:         &logthis("<font color=\"blue\">WARNING: ".
 2838:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2839:                  "</font>");
 2840:     }
 2841:     return $token;
 2842: }
 2843: 
 2844: # ------------------------------------------------------------ Check in an item
 2845: 
 2846: sub checkin {
 2847:     my $token=shift;
 2848:     my $now=time;
 2849:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2850:     $lonhost=~tr/A-Z/a-z/;
 2851:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2852:     $dtoken=~s/\W/\_/g;
 2853:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2854:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2855: 
 2856:     unless (($tuname) && ($tudom)) {
 2857:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2858:         return '';
 2859:     }
 2860:     
 2861:     unless (&allowed('mgr',$tcrsid)) {
 2862:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2863:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2864:         return '';
 2865:     }
 2866: 
 2867:     my %infohash=('resource.0.intoken' => $token,
 2868:                   'resource.0.checkintime' => $now,
 2869:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2870: 
 2871:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2872:        return '';
 2873:     }    
 2874: 
 2875:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2876:                          &escape('Checkin - '.$token)) ne 'ok') {
 2877: 	return '';
 2878:     }
 2879: 
 2880:     return ($symb,$tuname,$tudom,$tcrsid);    
 2881: }
 2882: 
 2883: # --------------------------------------------- Set Expire Date for Spreadsheet
 2884: 
 2885: sub expirespread {
 2886:     my ($uname,$udom,$stype,$usymb)=@_;
 2887:     my $cid=$env{'request.course.id'}; 
 2888:     if ($cid) {
 2889:        my $now=time;
 2890:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2891:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2892:                             $env{'course.'.$cid.'.num'}.
 2893: 	        	    ':nohist_expirationdates:'.
 2894:                             &escape($key).'='.$now,
 2895:                             $env{'course.'.$cid.'.home'})
 2896:     }
 2897:     return 'ok';
 2898: }
 2899: 
 2900: # ----------------------------------------------------- Devalidate Spreadsheets
 2901: 
 2902: sub devalidate {
 2903:     my ($symb,$uname,$udom)=@_;
 2904:     my $cid=$env{'request.course.id'}; 
 2905:     if ($cid) {
 2906:         # delete the stored spreadsheets for
 2907:         # - the student level sheet of this user in course's homespace
 2908:         # - the assessment level sheet for this resource 
 2909:         #   for this user in user's homespace
 2910: 	# - current conditional state info
 2911: 	my $key=$uname.':'.$udom.':';
 2912:         my $status=
 2913: 	    &del('nohist_calculatedsheets',
 2914: 		 [$key.'studentcalc:'],
 2915: 		 $env{'course.'.$cid.'.domain'},
 2916: 		 $env{'course.'.$cid.'.num'})
 2917: 		.' '.
 2918: 	    &del('nohist_calculatedsheets_'.$cid,
 2919: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2920:         unless ($status eq 'ok ok') {
 2921:            &logthis('Could not devalidate spreadsheet '.
 2922:                     $uname.' at '.$udom.' for '.
 2923: 		    $symb.': '.$status);
 2924:         }
 2925: 	&delenv('user.state.'.$cid);
 2926:     }
 2927: }
 2928: 
 2929: sub get_scalar {
 2930:     my ($string,$end) = @_;
 2931:     my $value;
 2932:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2933: 	$value = $1;
 2934:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2935: 	$value = $1;
 2936:     }
 2937:     return &unescape($value);
 2938: }
 2939: 
 2940: sub array2str {
 2941:   my (@array) = @_;
 2942:   my $result=&arrayref2str(\@array);
 2943:   $result=~s/^__ARRAY_REF__//;
 2944:   $result=~s/__END_ARRAY_REF__$//;
 2945:   return $result;
 2946: }
 2947: 
 2948: sub arrayref2str {
 2949:   my ($arrayref) = @_;
 2950:   my $result='__ARRAY_REF__';
 2951:   foreach my $elem (@$arrayref) {
 2952:     if(ref($elem) eq 'ARRAY') {
 2953:       $result.=&arrayref2str($elem).'&';
 2954:     } elsif(ref($elem) eq 'HASH') {
 2955:       $result.=&hashref2str($elem).'&';
 2956:     } elsif(ref($elem)) {
 2957:       #print("Got a ref of ".(ref($elem))." skipping.");
 2958:     } else {
 2959:       $result.=&escape($elem).'&';
 2960:     }
 2961:   }
 2962:   $result=~s/\&$//;
 2963:   $result .= '__END_ARRAY_REF__';
 2964:   return $result;
 2965: }
 2966: 
 2967: sub hash2str {
 2968:   my (%hash) = @_;
 2969:   my $result=&hashref2str(\%hash);
 2970:   $result=~s/^__HASH_REF__//;
 2971:   $result=~s/__END_HASH_REF__$//;
 2972:   return $result;
 2973: }
 2974: 
 2975: sub hashref2str {
 2976:   my ($hashref)=@_;
 2977:   my $result='__HASH_REF__';
 2978:   foreach my $key (sort(keys(%$hashref))) {
 2979:     if (ref($key) eq 'ARRAY') {
 2980:       $result.=&arrayref2str($key).'=';
 2981:     } elsif (ref($key) eq 'HASH') {
 2982:       $result.=&hashref2str($key).'=';
 2983:     } elsif (ref($key)) {
 2984:       $result.='=';
 2985:       #print("Got a ref of ".(ref($key))." skipping.");
 2986:     } else {
 2987: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2988:     }
 2989: 
 2990:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2991:       $result.=&arrayref2str($hashref->{$key}).'&';
 2992:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2993:       $result.=&hashref2str($hashref->{$key}).'&';
 2994:     } elsif(ref($hashref->{$key})) {
 2995:        $result.='&';
 2996:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2997:     } else {
 2998:       $result.=&escape($hashref->{$key}).'&';
 2999:     }
 3000:   }
 3001:   $result=~s/\&$//;
 3002:   $result .= '__END_HASH_REF__';
 3003:   return $result;
 3004: }
 3005: 
 3006: sub str2hash {
 3007:     my ($string)=@_;
 3008:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3009:     return %$hash;
 3010: }
 3011: 
 3012: sub str2hashref {
 3013:   my ($string) = @_;
 3014: 
 3015:   my %hash;
 3016: 
 3017:   if($string !~ /^__HASH_REF__/) {
 3018:       if (! ($string eq '' || !defined($string))) {
 3019: 	  $hash{'error'}='Not hash reference';
 3020:       }
 3021:       return (\%hash, $string);
 3022:   }
 3023: 
 3024:   $string =~ s/^__HASH_REF__//;
 3025: 
 3026:   while($string !~ /^__END_HASH_REF__/) {
 3027:       #key
 3028:       my $key='';
 3029:       if($string =~ /^__HASH_REF__/) {
 3030:           ($key, $string)=&str2hashref($string);
 3031:           if(defined($key->{'error'})) {
 3032:               $hash{'error'}='Bad data';
 3033:               return (\%hash, $string);
 3034:           }
 3035:       } elsif($string =~ /^__ARRAY_REF__/) {
 3036:           ($key, $string)=&str2arrayref($string);
 3037:           if($key->[0] eq 'Array reference error') {
 3038:               $hash{'error'}='Bad data';
 3039:               return (\%hash, $string);
 3040:           }
 3041:       } else {
 3042:           $string =~ s/^(.*?)=//;
 3043: 	  $key=&unescape($1);
 3044:       }
 3045:       $string =~ s/^=//;
 3046: 
 3047:       #value
 3048:       my $value='';
 3049:       if($string =~ /^__HASH_REF__/) {
 3050:           ($value, $string)=&str2hashref($string);
 3051:           if(defined($value->{'error'})) {
 3052:               $hash{'error'}='Bad data';
 3053:               return (\%hash, $string);
 3054:           }
 3055:       } elsif($string =~ /^__ARRAY_REF__/) {
 3056:           ($value, $string)=&str2arrayref($string);
 3057:           if($value->[0] eq 'Array reference error') {
 3058:               $hash{'error'}='Bad data';
 3059:               return (\%hash, $string);
 3060:           }
 3061:       } else {
 3062: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3063:       }
 3064:       $string =~ s/^&//;
 3065: 
 3066:       $hash{$key}=$value;
 3067:   }
 3068: 
 3069:   $string =~ s/^__END_HASH_REF__//;
 3070: 
 3071:   return (\%hash, $string);
 3072: }
 3073: 
 3074: sub str2array {
 3075:     my ($string)=@_;
 3076:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3077:     return @$array;
 3078: }
 3079: 
 3080: sub str2arrayref {
 3081:   my ($string) = @_;
 3082:   my @array;
 3083: 
 3084:   if($string !~ /^__ARRAY_REF__/) {
 3085:       if (! ($string eq '' || !defined($string))) {
 3086: 	  $array[0]='Array reference error';
 3087:       }
 3088:       return (\@array, $string);
 3089:   }
 3090: 
 3091:   $string =~ s/^__ARRAY_REF__//;
 3092: 
 3093:   while($string !~ /^__END_ARRAY_REF__/) {
 3094:       my $value='';
 3095:       if($string =~ /^__HASH_REF__/) {
 3096:           ($value, $string)=&str2hashref($string);
 3097:           if(defined($value->{'error'})) {
 3098:               $array[0] ='Array reference error';
 3099:               return (\@array, $string);
 3100:           }
 3101:       } elsif($string =~ /^__ARRAY_REF__/) {
 3102:           ($value, $string)=&str2arrayref($string);
 3103:           if($value->[0] eq 'Array reference error') {
 3104:               $array[0] ='Array reference error';
 3105:               return (\@array, $string);
 3106:           }
 3107:       } else {
 3108: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3109:       }
 3110:       $string =~ s/^&//;
 3111: 
 3112:       push(@array, $value);
 3113:   }
 3114: 
 3115:   $string =~ s/^__END_ARRAY_REF__//;
 3116: 
 3117:   return (\@array, $string);
 3118: }
 3119: 
 3120: # -------------------------------------------------------------------Temp Store
 3121: 
 3122: sub tmpreset {
 3123:   my ($symb,$namespace,$domain,$stuname) = @_;
 3124:   if (!$symb) {
 3125:     $symb=&symbread();
 3126:     if (!$symb) { $symb= $env{'request.url'}; }
 3127:   }
 3128:   $symb=escape($symb);
 3129: 
 3130:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3131:   $namespace=~s/\//\_/g;
 3132:   $namespace=~s/\W//g;
 3133: 
 3134:   if (!$domain) { $domain=$env{'user.domain'}; }
 3135:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3136:   if ($domain eq 'public' && $stuname eq 'public') {
 3137:       $stuname=$ENV{'REMOTE_ADDR'};
 3138:   }
 3139:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3140:   my %hash;
 3141:   if (tie(%hash,'GDBM_File',
 3142: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3143: 	  &GDBM_WRCREAT(),0640)) {
 3144:     foreach my $key (keys %hash) {
 3145:       if ($key=~ /:$symb/) {
 3146: 	delete($hash{$key});
 3147:       }
 3148:     }
 3149:   }
 3150: }
 3151: 
 3152: sub tmpstore {
 3153:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3154: 
 3155:   if (!$symb) {
 3156:     $symb=&symbread();
 3157:     if (!$symb) { $symb= $env{'request.url'}; }
 3158:   }
 3159:   $symb=escape($symb);
 3160: 
 3161:   if (!$namespace) {
 3162:     # I don't think we would ever want to store this for a course.
 3163:     # it seems this will only be used if we don't have a course.
 3164:     #$namespace=$env{'request.course.id'};
 3165:     #if (!$namespace) {
 3166:       $namespace=$env{'request.state'};
 3167:     #}
 3168:   }
 3169:   $namespace=~s/\//\_/g;
 3170:   $namespace=~s/\W//g;
 3171:   if (!$domain) { $domain=$env{'user.domain'}; }
 3172:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3173:   if ($domain eq 'public' && $stuname eq 'public') {
 3174:       $stuname=$ENV{'REMOTE_ADDR'};
 3175:   }
 3176:   my $now=time;
 3177:   my %hash;
 3178:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3179:   if (tie(%hash,'GDBM_File',
 3180: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3181: 	  &GDBM_WRCREAT(),0640)) {
 3182:     $hash{"version:$symb"}++;
 3183:     my $version=$hash{"version:$symb"};
 3184:     my $allkeys=''; 
 3185:     foreach my $key (keys(%$storehash)) {
 3186:       $allkeys.=$key.':';
 3187:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3188:     }
 3189:     $hash{"$version:$symb:timestamp"}=$now;
 3190:     $allkeys.='timestamp';
 3191:     $hash{"$version:keys:$symb"}=$allkeys;
 3192:     if (untie(%hash)) {
 3193:       return 'ok';
 3194:     } else {
 3195:       return "error:$!";
 3196:     }
 3197:   } else {
 3198:     return "error:$!";
 3199:   }
 3200: }
 3201: 
 3202: # -----------------------------------------------------------------Temp Restore
 3203: 
 3204: sub tmprestore {
 3205:   my ($symb,$namespace,$domain,$stuname) = @_;
 3206: 
 3207:   if (!$symb) {
 3208:     $symb=&symbread();
 3209:     if (!$symb) { $symb= $env{'request.url'}; }
 3210:   }
 3211:   $symb=escape($symb);
 3212: 
 3213:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3214: 
 3215:   if (!$domain) { $domain=$env{'user.domain'}; }
 3216:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3217:   if ($domain eq 'public' && $stuname eq 'public') {
 3218:       $stuname=$ENV{'REMOTE_ADDR'};
 3219:   }
 3220:   my %returnhash;
 3221:   $namespace=~s/\//\_/g;
 3222:   $namespace=~s/\W//g;
 3223:   my %hash;
 3224:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3225:   if (tie(%hash,'GDBM_File',
 3226: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3227: 	  &GDBM_READER(),0640)) {
 3228:     my $version=$hash{"version:$symb"};
 3229:     $returnhash{'version'}=$version;
 3230:     my $scope;
 3231:     for ($scope=1;$scope<=$version;$scope++) {
 3232:       my $vkeys=$hash{"$scope:keys:$symb"};
 3233:       my @keys=split(/:/,$vkeys);
 3234:       my $key;
 3235:       $returnhash{"$scope:keys"}=$vkeys;
 3236:       foreach $key (@keys) {
 3237: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3238: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3239:       }
 3240:     }
 3241:     if (!(untie(%hash))) {
 3242:       return "error:$!";
 3243:     }
 3244:   } else {
 3245:     return "error:$!";
 3246:   }
 3247:   return %returnhash;
 3248: }
 3249: 
 3250: # ----------------------------------------------------------------------- Store
 3251: 
 3252: sub store {
 3253:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3254:     my $home='';
 3255: 
 3256:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3257: 
 3258:     $symb=&symbclean($symb);
 3259:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3260: 
 3261:     if (!$domain) { $domain=$env{'user.domain'}; }
 3262:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3263: 
 3264:     &devalidate($symb,$stuname,$domain);
 3265: 
 3266:     $symb=escape($symb);
 3267:     if (!$namespace) { 
 3268:        unless ($namespace=$env{'request.course.id'}) { 
 3269:           return ''; 
 3270:        } 
 3271:     }
 3272:     if (!$home) { $home=$env{'user.home'}; }
 3273: 
 3274:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3275:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3276: 
 3277:     my $namevalue='';
 3278:     foreach my $key (keys(%$storehash)) {
 3279:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3280:     }
 3281:     $namevalue=~s/\&$//;
 3282:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3283:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3284: }
 3285: 
 3286: # -------------------------------------------------------------- Critical Store
 3287: 
 3288: sub cstore {
 3289:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3290:     my $home='';
 3291: 
 3292:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3293: 
 3294:     $symb=&symbclean($symb);
 3295:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3296: 
 3297:     if (!$domain) { $domain=$env{'user.domain'}; }
 3298:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3299: 
 3300:     &devalidate($symb,$stuname,$domain);
 3301: 
 3302:     $symb=escape($symb);
 3303:     if (!$namespace) { 
 3304:        unless ($namespace=$env{'request.course.id'}) { 
 3305:           return ''; 
 3306:        } 
 3307:     }
 3308:     if (!$home) { $home=$env{'user.home'}; }
 3309: 
 3310:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3311:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3312: 
 3313:     my $namevalue='';
 3314:     foreach my $key (keys(%$storehash)) {
 3315:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3316:     }
 3317:     $namevalue=~s/\&$//;
 3318:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3319:     return critical
 3320:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3321: }
 3322: 
 3323: # --------------------------------------------------------------------- Restore
 3324: 
 3325: sub restore {
 3326:     my ($symb,$namespace,$domain,$stuname) = @_;
 3327:     my $home='';
 3328: 
 3329:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3330: 
 3331:     if (!$symb) {
 3332:       unless ($symb=escape(&symbread())) { return ''; }
 3333:     } else {
 3334:       $symb=&escape(&symbclean($symb));
 3335:     }
 3336:     if (!$namespace) { 
 3337:        unless ($namespace=$env{'request.course.id'}) { 
 3338:           return ''; 
 3339:        } 
 3340:     }
 3341:     if (!$domain) { $domain=$env{'user.domain'}; }
 3342:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3343:     if (!$home) { $home=$env{'user.home'}; }
 3344:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3345: 
 3346:     my %returnhash=();
 3347:     foreach my $line (split(/\&/,$answer)) {
 3348: 	my ($name,$value)=split(/\=/,$line);
 3349:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3350:     }
 3351:     my $version;
 3352:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3353:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3354:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3355:        }
 3356:     }
 3357:     return %returnhash;
 3358: }
 3359: 
 3360: # ---------------------------------------------------------- Course Description
 3361: 
 3362: sub coursedescription {
 3363:     my ($courseid,$args)=@_;
 3364:     $courseid=~s/^\///;
 3365:     $courseid=~s/\_/\//g;
 3366:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3367:     my $chome=&homeserver($cnum,$cdomain);
 3368:     my $normalid=$cdomain.'_'.$cnum;
 3369:     # need to always cache even if we get errors otherwise we keep 
 3370:     # trying and trying and trying to get the course description.
 3371:     my %envhash=();
 3372:     my %returnhash=();
 3373:     
 3374:     my $expiretime=600;
 3375:     if ($env{'request.course.id'} eq $normalid) {
 3376: 	$expiretime=120;
 3377:     }
 3378: 
 3379:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3380:     if (!$args->{'freshen_cache'}
 3381: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3382: 	foreach my $key (keys(%env)) {
 3383: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3384: 	    my ($setting) = $1;
 3385: 	    $returnhash{$setting} = $env{$key};
 3386: 	}
 3387: 	return %returnhash;
 3388:     }
 3389: 
 3390:     # get the data agin
 3391:     if (!$args->{'one_time'}) {
 3392: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3393:     }
 3394: 
 3395:     if ($chome ne 'no_host') {
 3396:        %returnhash=&dump('environment',$cdomain,$cnum);
 3397:        if (!exists($returnhash{'con_lost'})) {
 3398:            $returnhash{'home'}= $chome;
 3399: 	   $returnhash{'domain'} = $cdomain;
 3400: 	   $returnhash{'num'} = $cnum;
 3401:            if (!defined($returnhash{'type'})) {
 3402:                $returnhash{'type'} = 'Course';
 3403:            }
 3404:            while (my ($name,$value) = each %returnhash) {
 3405:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3406:            }
 3407:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3408:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3409: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3410:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3411:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3412:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3413:        }
 3414:     }
 3415:     if (!$args->{'one_time'}) {
 3416: 	&appenv(\%envhash);
 3417:     }
 3418:     return %returnhash;
 3419: }
 3420: 
 3421: # -------------------------------------------------See if a user is privileged
 3422: 
 3423: sub privileged {
 3424:     my ($username,$domain)=@_;
 3425:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3426: 			&homeserver($username,$domain));
 3427:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3428:     my $now=time;
 3429:     if ($rolesdump ne '') {
 3430:         foreach my $entry (split(/&/,$rolesdump)) {
 3431: 	    if ($entry!~/^rolesdef_/) {
 3432: 		my ($area,$role)=split(/=/,$entry);
 3433: 		$area=~s/\_\w\w$//;
 3434: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3435: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3436: 		    my $active=1;
 3437: 		    if ($tend) {
 3438: 			if ($tend<$now) { $active=0; }
 3439: 		    }
 3440: 		    if ($tstart) {
 3441: 			if ($tstart>$now) { $active=0; }
 3442: 		    }
 3443: 		    if ($active) { return 1; }
 3444: 		}
 3445: 	    }
 3446: 	}
 3447:     }
 3448:     return 0;
 3449: }
 3450: 
 3451: # -------------------------------------------------------- Get user privileges
 3452: 
 3453: sub rolesinit {
 3454:     my ($domain,$username,$authhost)=@_;
 3455:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3456:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3457:     my %allroles=();
 3458:     my %allgroups=();   
 3459:     my $now=time;
 3460:     my %userroles = ('user.login.time' => $now);
 3461:     my $group_privs;
 3462: 
 3463:     if ($rolesdump ne '') {
 3464:         foreach my $entry (split(/&/,$rolesdump)) {
 3465: 	  if ($entry!~/^rolesdef_/) {
 3466:             my ($area,$role)=split(/=/,$entry);
 3467: 	    $area=~s/\_\w\w$//;
 3468:             my ($trole,$tend,$tstart,$group_privs);
 3469: 	    if ($role=~/^cr/) { 
 3470: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3471: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3472: 		    ($tend,$tstart)=split('_',$trest);
 3473: 		} else {
 3474: 		    $trole=$role;
 3475: 		}
 3476:             } elsif ($role =~ m|^gr/|) {
 3477:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3478:                 ($trole,$group_privs) = split(/\//,$trole);
 3479:                 $group_privs = &unescape($group_privs);
 3480: 	    } else {
 3481: 		($trole,$tend,$tstart)=split(/_/,$role);
 3482: 	    }
 3483: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3484: 					 $username);
 3485: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3486:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3487:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3488:             if (($area ne '') && ($trole ne '')) {
 3489: 		my $spec=$trole.'.'.$area;
 3490: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3491: 		if ($trole =~ /^cr\//) {
 3492:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3493:                 } elsif ($trole eq 'gr') {
 3494:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3495: 		} else {
 3496:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3497: 		}
 3498:             }
 3499:           }
 3500:         }
 3501:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3502:         $userroles{'user.adv'}    = $adv;
 3503: 	$userroles{'user.author'} = $author;
 3504:         $env{'user.adv'}=$adv;
 3505:     }
 3506:     return \%userroles;  
 3507: }
 3508: 
 3509: sub set_arearole {
 3510:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3511: # log the associated role with the area
 3512:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3513:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3514: }
 3515: 
 3516: sub custom_roleprivs {
 3517:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3518:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3519:     my $homsvr=homeserver($rauthor,$rdomain);
 3520:     if (&hostname($homsvr) ne '') {
 3521:         my ($rdummy,$roledef)=
 3522:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3523:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3524:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3525:             if (defined($syspriv)) {
 3526:                 $$allroles{'cm./'}.=':'.$syspriv;
 3527:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3528:             }
 3529:             if ($tdomain ne '') {
 3530:                 if (defined($dompriv)) {
 3531:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3532:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3533:                 }
 3534:                 if (($trest ne '') && (defined($coursepriv))) {
 3535:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3536:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3537:                 }
 3538:             }
 3539:         }
 3540:     }
 3541: }
 3542: 
 3543: sub group_roleprivs {
 3544:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3545:     my $access = 1;
 3546:     my $now = time;
 3547:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3548:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3549:     if ($access) {
 3550:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3551:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3552:     }
 3553: }
 3554: 
 3555: sub standard_roleprivs {
 3556:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3557:     if (defined($pr{$trole.':s'})) {
 3558:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3559:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3560:     }
 3561:     if ($tdomain ne '') {
 3562:         if (defined($pr{$trole.':d'})) {
 3563:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3564:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3565:         }
 3566:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3567:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3568:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3569:         }
 3570:     }
 3571: }
 3572: 
 3573: sub set_userprivs {
 3574:     my ($userroles,$allroles,$allgroups) = @_; 
 3575:     my $author=0;
 3576:     my $adv=0;
 3577:     my %grouproles = ();
 3578:     if (keys(%{$allgroups}) > 0) {
 3579:         foreach my $role (keys %{$allroles}) {
 3580:             my ($trole,$area,$sec,$extendedarea);
 3581:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3582:                 $trole = $1;
 3583:                 $area = $2;
 3584:                 $sec = $3;
 3585:                 $extendedarea = $area.$sec;
 3586:                 if (exists($$allgroups{$area})) {
 3587:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3588:                         my $spec = $trole.'.'.$extendedarea;
 3589:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3590:                                                 $$allgroups{$area}{$group};
 3591:                     }
 3592:                 }
 3593:             }
 3594:         }
 3595:     }
 3596:     foreach my $group (keys(%grouproles)) {
 3597:         $$allroles{$group} = $grouproles{$group};
 3598:     }
 3599:     foreach my $role (keys(%{$allroles})) {
 3600:         my %thesepriv;
 3601:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3602:         foreach my $item (split(/:/,$$allroles{$role})) {
 3603:             if ($item ne '') {
 3604:                 my ($privilege,$restrictions)=split(/&/,$item);
 3605:                 if ($restrictions eq '') {
 3606:                     $thesepriv{$privilege}='F';
 3607:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3608:                     $thesepriv{$privilege}.=$restrictions;
 3609:                 }
 3610:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3611:             }
 3612:         }
 3613:         my $thesestr='';
 3614:         foreach my $priv (keys(%thesepriv)) {
 3615: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3616: 	}
 3617:         $userroles->{'user.priv.'.$role} = $thesestr;
 3618:     }
 3619:     return ($author,$adv);
 3620: }
 3621: 
 3622: # --------------------------------------------------------------- get interface
 3623: 
 3624: sub get {
 3625:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3626:    my $items='';
 3627:    foreach my $item (@$storearr) {
 3628:        $items.=&escape($item).'&';
 3629:    }
 3630:    $items=~s/\&$//;
 3631:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3632:    if (!$uname) { $uname=$env{'user.name'}; }
 3633:    my $uhome=&homeserver($uname,$udomain);
 3634: 
 3635:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3636:    my @pairs=split(/\&/,$rep);
 3637:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3638:      return @pairs;
 3639:    }
 3640:    my %returnhash=();
 3641:    my $i=0;
 3642:    foreach my $item (@$storearr) {
 3643:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3644:       $i++;
 3645:    }
 3646:    return %returnhash;
 3647: }
 3648: 
 3649: # --------------------------------------------------------------- del interface
 3650: 
 3651: sub del {
 3652:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3653:    my $items='';
 3654:    foreach my $item (@$storearr) {
 3655:        $items.=&escape($item).'&';
 3656:    }
 3657:    $items=~s/\&$//;
 3658:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3659:    if (!$uname) { $uname=$env{'user.name'}; }
 3660:    my $uhome=&homeserver($uname,$udomain);
 3661: 
 3662:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3663: }
 3664: 
 3665: # -------------------------------------------------------------- dump interface
 3666: 
 3667: sub dump {
 3668:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3669:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3670:     if (!$uname) { $uname=$env{'user.name'}; }
 3671:     my $uhome=&homeserver($uname,$udomain);
 3672:     if ($regexp) {
 3673: 	$regexp=&escape($regexp);
 3674:     } else {
 3675: 	$regexp='.';
 3676:     }
 3677:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3678:     my @pairs=split(/\&/,$rep);
 3679:     my %returnhash=();
 3680:     foreach my $item (@pairs) {
 3681: 	my ($key,$value)=split(/=/,$item,2);
 3682: 	$key = &unescape($key);
 3683: 	next if ($key =~ /^error: 2 /);
 3684: 	$returnhash{$key}=&thaw_unescape($value);
 3685:     }
 3686:     return %returnhash;
 3687: }
 3688: 
 3689: # --------------------------------------------------------- dumpstore interface
 3690: 
 3691: sub dumpstore {
 3692:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3693:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3694:    if (!$uname) { $uname=$env{'user.name'}; }
 3695:    my $uhome=&homeserver($uname,$udomain);
 3696:    if ($regexp) {
 3697:        $regexp=&escape($regexp);
 3698:    } else {
 3699:        $regexp='.';
 3700:    }
 3701:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3702:    my @pairs=split(/\&/,$rep);
 3703:    my %returnhash=();
 3704:    foreach my $item (@pairs) {
 3705:        my ($key,$value)=split(/=/,$item,2);
 3706:        next if ($key =~ /^error: 2 /);
 3707:        $returnhash{$key}=&thaw_unescape($value);
 3708:    }
 3709:    return %returnhash;
 3710: }
 3711: 
 3712: # -------------------------------------------------------------- keys interface
 3713: 
 3714: sub getkeys {
 3715:    my ($namespace,$udomain,$uname)=@_;
 3716:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3717:    if (!$uname) { $uname=$env{'user.name'}; }
 3718:    my $uhome=&homeserver($uname,$udomain);
 3719:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3720:    my @keyarray=();
 3721:    foreach my $key (split(/\&/,$rep)) {
 3722:       next if ($key =~ /^error: 2 /);
 3723:       push(@keyarray,&unescape($key));
 3724:    }
 3725:    return @keyarray;
 3726: }
 3727: 
 3728: # --------------------------------------------------------------- currentdump
 3729: sub currentdump {
 3730:    my ($courseid,$sdom,$sname)=@_;
 3731:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3732:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3733:    $sname    = $env{'user.name'}         if (! defined($sname));
 3734:    my $uhome = &homeserver($sname,$sdom);
 3735:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3736:    return if ($rep =~ /^(error:|no_such_host)/);
 3737:    #
 3738:    my %returnhash=();
 3739:    #
 3740:    if ($rep eq "unknown_cmd") { 
 3741:        # an old lond will not know currentdump
 3742:        # Do a dump and make it look like a currentdump
 3743:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3744:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3745:        my %hash = @tmp;
 3746:        @tmp=();
 3747:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3748:    } else {
 3749:        my @pairs=split(/\&/,$rep);
 3750:        foreach my $pair (@pairs) {
 3751:            my ($key,$value)=split(/=/,$pair,2);
 3752:            my ($symb,$param) = split(/:/,$key);
 3753:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3754:                                                         &thaw_unescape($value);
 3755:        }
 3756:    }
 3757:    return %returnhash;
 3758: }
 3759: 
 3760: sub convert_dump_to_currentdump{
 3761:     my %hash = %{shift()};
 3762:     my %returnhash;
 3763:     # Code ripped from lond, essentially.  The only difference
 3764:     # here is the unescaping done by lonnet::dump().  Conceivably
 3765:     # we might run in to problems with parameter names =~ /^v\./
 3766:     while (my ($key,$value) = each(%hash)) {
 3767:         my ($v,$symb,$param) = split(/:/,$key);
 3768: 	$symb  = &unescape($symb);
 3769: 	$param = &unescape($param);
 3770:         next if ($v eq 'version' || $symb eq 'keys');
 3771:         next if (exists($returnhash{$symb}) &&
 3772:                  exists($returnhash{$symb}->{$param}) &&
 3773:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3774:         $returnhash{$symb}->{$param}=$value;
 3775:         $returnhash{$symb}->{'v.'.$param}=$v;
 3776:     }
 3777:     #
 3778:     # Remove all of the keys in the hashes which keep track of
 3779:     # the version of the parameter.
 3780:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3781:         # use a foreach because we are going to delete from the hash.
 3782:         foreach my $key (keys(%$param_hash)) {
 3783:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3784:         }
 3785:     }
 3786:     return \%returnhash;
 3787: }
 3788: 
 3789: # ------------------------------------------------------ critical inc interface
 3790: 
 3791: sub cinc {
 3792:     return &inc(@_,'critical');
 3793: }
 3794: 
 3795: # --------------------------------------------------------------- inc interface
 3796: 
 3797: sub inc {
 3798:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3799:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3800:     if (!$uname) { $uname=$env{'user.name'}; }
 3801:     my $uhome=&homeserver($uname,$udomain);
 3802:     my $items='';
 3803:     if (! ref($store)) {
 3804:         # got a single value, so use that instead
 3805:         $items = &escape($store).'=&';
 3806:     } elsif (ref($store) eq 'SCALAR') {
 3807:         $items = &escape($$store).'=&';        
 3808:     } elsif (ref($store) eq 'ARRAY') {
 3809:         $items = join('=&',map {&escape($_);} @{$store});
 3810:     } elsif (ref($store) eq 'HASH') {
 3811:         while (my($key,$value) = each(%{$store})) {
 3812:             $items.= &escape($key).'='.&escape($value).'&';
 3813:         }
 3814:     }
 3815:     $items=~s/\&$//;
 3816:     if ($critical) {
 3817: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3818:     } else {
 3819: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3820:     }
 3821: }
 3822: 
 3823: # --------------------------------------------------------------- put interface
 3824: 
 3825: sub put {
 3826:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3827:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3828:    if (!$uname) { $uname=$env{'user.name'}; }
 3829:    my $uhome=&homeserver($uname,$udomain);
 3830:    my $items='';
 3831:    foreach my $item (keys(%$storehash)) {
 3832:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3833:    }
 3834:    $items=~s/\&$//;
 3835:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3836: }
 3837: 
 3838: # ------------------------------------------------------------ newput interface
 3839: 
 3840: sub newput {
 3841:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3842:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3843:    if (!$uname) { $uname=$env{'user.name'}; }
 3844:    my $uhome=&homeserver($uname,$udomain);
 3845:    my $items='';
 3846:    foreach my $key (keys(%$storehash)) {
 3847:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3848:    }
 3849:    $items=~s/\&$//;
 3850:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3851: }
 3852: 
 3853: # ---------------------------------------------------------  putstore interface
 3854: 
 3855: sub putstore {
 3856:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3857:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3858:    if (!$uname) { $uname=$env{'user.name'}; }
 3859:    my $uhome=&homeserver($uname,$udomain);
 3860:    my $items='';
 3861:    foreach my $key (keys(%$storehash)) {
 3862:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3863:    }
 3864:    $items=~s/\&$//;
 3865:    my $esc_symb=&escape($symb);
 3866:    my $esc_v=&escape($version);
 3867:    my $reply =
 3868:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3869: 	      $uhome);
 3870:    if ($reply eq 'unknown_cmd') {
 3871:        # gfall back to way things use to be done
 3872:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3873: 			    $uname);
 3874:    }
 3875:    return $reply;
 3876: }
 3877: 
 3878: sub old_putstore {
 3879:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3880:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3881:     if (!$uname) { $uname=$env{'user.name'}; }
 3882:     my $uhome=&homeserver($uname,$udomain);
 3883:     my %newstorehash;
 3884:     foreach my $item (keys(%$storehash)) {
 3885: 	my $key = $version.':'.&escape($symb).':'.$item;
 3886: 	$newstorehash{$key} = $storehash->{$item};
 3887:     }
 3888:     my $items='';
 3889:     my %allitems = ();
 3890:     foreach my $item (keys(%newstorehash)) {
 3891: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3892: 	    my $key = $1.':keys:'.$2;
 3893: 	    $allitems{$key} .= $3.':';
 3894: 	}
 3895: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3896:     }
 3897:     foreach my $item (keys(%allitems)) {
 3898: 	$allitems{$item} =~ s/\:$//;
 3899: 	$items.= $item.'='.$allitems{$item}.'&';
 3900:     }
 3901:     $items=~s/\&$//;
 3902:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3903: }
 3904: 
 3905: # ------------------------------------------------------ critical put interface
 3906: 
 3907: sub cput {
 3908:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3909:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3910:    if (!$uname) { $uname=$env{'user.name'}; }
 3911:    my $uhome=&homeserver($uname,$udomain);
 3912:    my $items='';
 3913:    foreach my $item (keys(%$storehash)) {
 3914:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3915:    }
 3916:    $items=~s/\&$//;
 3917:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3918: }
 3919: 
 3920: # -------------------------------------------------------------- eget interface
 3921: 
 3922: sub eget {
 3923:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3924:    my $items='';
 3925:    foreach my $item (@$storearr) {
 3926:        $items.=&escape($item).'&';
 3927:    }
 3928:    $items=~s/\&$//;
 3929:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3930:    if (!$uname) { $uname=$env{'user.name'}; }
 3931:    my $uhome=&homeserver($uname,$udomain);
 3932:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3933:    my @pairs=split(/\&/,$rep);
 3934:    my %returnhash=();
 3935:    my $i=0;
 3936:    foreach my $item (@$storearr) {
 3937:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3938:       $i++;
 3939:    }
 3940:    return %returnhash;
 3941: }
 3942: 
 3943: # ------------------------------------------------------------ tmpput interface
 3944: sub tmpput {
 3945:     my ($storehash,$server,$context)=@_;
 3946:     my $items='';
 3947:     foreach my $item (keys(%$storehash)) {
 3948: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3949:     }
 3950:     $items=~s/\&$//;
 3951:     if (defined($context)) {
 3952:         $items .= ':'.&escape($context);
 3953:     }
 3954:     return &reply("tmpput:$items",$server);
 3955: }
 3956: 
 3957: # ------------------------------------------------------------ tmpget interface
 3958: sub tmpget {
 3959:     my ($token,$server)=@_;
 3960:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3961:     my $rep=&reply("tmpget:$token",$server);
 3962:     my %returnhash;
 3963:     foreach my $item (split(/\&/,$rep)) {
 3964: 	my ($key,$value)=split(/=/,$item);
 3965: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3966:     }
 3967:     return %returnhash;
 3968: }
 3969: 
 3970: # ------------------------------------------------------------ tmpget interface
 3971: sub tmpdel {
 3972:     my ($token,$server)=@_;
 3973:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3974:     return &reply("tmpdel:$token",$server);
 3975: }
 3976: 
 3977: # -------------------------------------------------- portfolio access checking
 3978: 
 3979: sub portfolio_access {
 3980:     my ($requrl) = @_;
 3981:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3982:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3983:     if ($result) {
 3984:         my %setters;
 3985:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3986:             my ($startblock,$endblock) =
 3987:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3988:             if ($startblock && $endblock) {
 3989:                 return 'B';
 3990:             }
 3991:         } else {
 3992:             my ($startblock,$endblock) =
 3993:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3994:             if ($startblock && $endblock) {
 3995:                 return 'B';
 3996:             }
 3997:         }
 3998:     }
 3999:     if ($result eq 'ok') {
 4000:        return 'F';
 4001:     } elsif ($result =~ /^[^:]+:guest_/) {
 4002:        return 'A';
 4003:     }
 4004:     return '';
 4005: }
 4006: 
 4007: sub get_portfolio_access {
 4008:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4009: 
 4010:     if (!ref($access_hash)) {
 4011: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4012: 	my %access_controls = &get_access_controls($current_perms,$group,
 4013: 						   $file_name);
 4014: 	$access_hash = $access_controls{$file_name};
 4015:     }
 4016: 
 4017:     my ($public,$guest,@domains,@users,@courses,@groups);
 4018:     my $now = time;
 4019:     if (ref($access_hash) eq 'HASH') {
 4020:         foreach my $key (keys(%{$access_hash})) {
 4021:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4022:             if ($start > $now) {
 4023:                 next;
 4024:             }
 4025:             if ($end && $end<$now) {
 4026:                 next;
 4027:             }
 4028:             if ($scope eq 'public') {
 4029:                 $public = $key;
 4030:                 last;
 4031:             } elsif ($scope eq 'guest') {
 4032:                 $guest = $key;
 4033:             } elsif ($scope eq 'domains') {
 4034:                 push(@domains,$key);
 4035:             } elsif ($scope eq 'users') {
 4036:                 push(@users,$key);
 4037:             } elsif ($scope eq 'course') {
 4038:                 push(@courses,$key);
 4039:             } elsif ($scope eq 'group') {
 4040:                 push(@groups,$key);
 4041:             }
 4042:         }
 4043:         if ($public) {
 4044:             return 'ok';
 4045:         }
 4046:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4047:             if ($guest) {
 4048:                 return $guest;
 4049:             }
 4050:         } else {
 4051:             if (@domains > 0) {
 4052:                 foreach my $domkey (@domains) {
 4053:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4054:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4055:                             return 'ok';
 4056:                         }
 4057:                     }
 4058:                 }
 4059:             }
 4060:             if (@users > 0) {
 4061:                 foreach my $userkey (@users) {
 4062:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4063:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4064:                             if (ref($item) eq 'HASH') {
 4065:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4066:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4067:                                     return 'ok';
 4068:                                 }
 4069:                             }
 4070:                         }
 4071:                     } 
 4072:                 }
 4073:             }
 4074:             my %roleshash;
 4075:             my @courses_and_groups = @courses;
 4076:             push(@courses_and_groups,@groups); 
 4077:             if (@courses_and_groups > 0) {
 4078:                 my (%allgroups,%allroles); 
 4079:                 my ($start,$end,$role,$sec,$group);
 4080:                 foreach my $envkey (%env) {
 4081:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4082:                         my $cid = $2.'_'.$3; 
 4083:                         if ($1 eq 'gr') {
 4084:                             $group = $4;
 4085:                             $allgroups{$cid}{$group} = $env{$envkey};
 4086:                         } else {
 4087:                             if ($4 eq '') {
 4088:                                 $sec = 'none';
 4089:                             } else {
 4090:                                 $sec = $4;
 4091:                             }
 4092:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4093:                         }
 4094:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4095:                         my $cid = $2.'_'.$3;
 4096:                         if ($4 eq '') {
 4097:                             $sec = 'none';
 4098:                         } else {
 4099:                             $sec = $4;
 4100:                         }
 4101:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4102:                     }
 4103:                 }
 4104:                 if (keys(%allroles) == 0) {
 4105:                     return;
 4106:                 }
 4107:                 foreach my $key (@courses_and_groups) {
 4108:                     my %content = %{$$access_hash{$key}};
 4109:                     my $cnum = $content{'number'};
 4110:                     my $cdom = $content{'domain'};
 4111:                     my $cid = $cdom.'_'.$cnum;
 4112:                     if (!exists($allroles{$cid})) {
 4113:                         next;
 4114:                     }    
 4115:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4116:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4117:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4118:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4119:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4120:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4121:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4122:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4123:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4124:                                         if (grep/^all$/,@sections) {
 4125:                                             return 'ok';
 4126:                                         } else {
 4127:                                             if (grep/^$sec$/,@sections) {
 4128:                                                 return 'ok';
 4129:                                             }
 4130:                                         }
 4131:                                     }
 4132:                                 }
 4133:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4134:                                     if (grep/^none$/,@groups) {
 4135:                                         return 'ok';
 4136:                                     }
 4137:                                 } else {
 4138:                                     if (grep/^all$/,@groups) {
 4139:                                         return 'ok';
 4140:                                     } 
 4141:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4142:                                         if (grep/^$group$/,@groups) {
 4143:                                             return 'ok';
 4144:                                         }
 4145:                                     }
 4146:                                 } 
 4147:                             }
 4148:                         }
 4149:                     }
 4150:                 }
 4151:             }
 4152:             if ($guest) {
 4153:                 return $guest;
 4154:             }
 4155:         }
 4156:     }
 4157:     return;
 4158: }
 4159: 
 4160: sub course_group_datechecker {
 4161:     my ($dates,$now,$status) = @_;
 4162:     my ($start,$end) = split(/\./,$dates);
 4163:     if (!$start && !$end) {
 4164:         return 'ok';
 4165:     }
 4166:     if (grep/^active$/,@{$status}) {
 4167:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4168:             return 'ok';
 4169:         }
 4170:     }
 4171:     if (grep/^previous$/,@{$status}) {
 4172:         if ($end > $now ) {
 4173:             return 'ok';
 4174:         }
 4175:     }
 4176:     if (grep/^future$/,@{$status}) {
 4177:         if ($start > $now) {
 4178:             return 'ok';
 4179:         }
 4180:     }
 4181:     return; 
 4182: }
 4183: 
 4184: sub parse_portfolio_url {
 4185:     my ($url) = @_;
 4186: 
 4187:     my ($type,$udom,$unum,$group,$file_name);
 4188:     
 4189:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4190: 	$type = 1;
 4191:         $udom = $1;
 4192:         $unum = $2;
 4193:         $file_name = $3;
 4194:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4195: 	$type = 2;
 4196:         $udom = $1;
 4197:         $unum = $2;
 4198:         $group = $3;
 4199:         $file_name = $3.'/'.$4;
 4200:     }
 4201:     if (wantarray) {
 4202: 	return ($type,$udom,$unum,$file_name,$group);
 4203:     }
 4204:     return $type;
 4205: }
 4206: 
 4207: sub is_portfolio_url {
 4208:     my ($url) = @_;
 4209:     return scalar(&parse_portfolio_url($url));
 4210: }
 4211: 
 4212: sub is_portfolio_file {
 4213:     my ($file) = @_;
 4214:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4215:         return 1;
 4216:     }
 4217:     return;
 4218: }
 4219: 
 4220: 
 4221: # ---------------------------------------------- Custom access rule evaluation
 4222: 
 4223: sub customaccess {
 4224:     my ($priv,$uri)=@_;
 4225:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4226:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4227:     $udom = &LONCAPA::clean_domain($udom);
 4228:     $ucrs = &LONCAPA::clean_username($ucrs);
 4229:     my $access=0;
 4230:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4231: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4232: 	if ($type eq 'user') {
 4233: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4234: 		my ($tdom,$tuname)=split(m{/},$scope);
 4235: 		if ($tdom) {
 4236: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4237: 		}
 4238: 		if ($tuname) {
 4239: 		    if ($tuname ne $env{'user.name'}) { next; }
 4240: 		}
 4241: 		$access=($effect eq 'allow');
 4242: 		last;
 4243: 	    }
 4244: 	} else {
 4245: 	    if ($role) {
 4246: 		if ($role ne $urole) { next; }
 4247: 	    }
 4248: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4249: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4250: 		if ($tdom) {
 4251: 		    if ($tdom ne $udom) { next; }
 4252: 		}
 4253: 		if ($tcrs) {
 4254: 		    if ($tcrs ne $ucrs) { next; }
 4255: 		}
 4256: 		if ($tsec) {
 4257: 		    if ($tsec ne $usec) { next; }
 4258: 		}
 4259: 		$access=($effect eq 'allow');
 4260: 		last;
 4261: 	    }
 4262: 	    if ($realm eq '' && $role eq '') {
 4263: 		$access=($effect eq 'allow');
 4264: 	    }
 4265: 	}
 4266:     }
 4267:     return $access;
 4268: }
 4269: 
 4270: # ------------------------------------------------- Check for a user privilege
 4271: 
 4272: sub allowed {
 4273:     my ($priv,$uri,$symb,$role)=@_;
 4274:     my $ver_orguri=$uri;
 4275:     $uri=&deversion($uri);
 4276:     my $orguri=$uri;
 4277:     $uri=&declutter($uri);
 4278: 
 4279:     if ($priv eq 'evb') {
 4280: # Evade communication block restrictions for specified role in a course
 4281:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4282:             return $1;
 4283:         } else {
 4284:             return;
 4285:         }
 4286:     }
 4287: 
 4288:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4289: # Free bre access to adm and meta resources
 4290:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4291: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4292: 	&& ($priv eq 'bre')) {
 4293: 	return 'F';
 4294:     }
 4295: 
 4296: # Free bre access to user's own portfolio contents
 4297:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4298:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4299: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4300:         my %setters;
 4301:         my ($startblock,$endblock) = 
 4302:             &Apache::loncommon::blockcheck(\%setters,'port');
 4303:         if ($startblock && $endblock) {
 4304:             return 'B';
 4305:         } else {
 4306:             return 'F';
 4307:         }
 4308:     }
 4309: 
 4310: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4311:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4312:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4313:         if (exists($env{'request.course.id'})) {
 4314:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4315:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4316:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4317:                 my $courseprivid=$env{'request.course.id'};
 4318:                 $courseprivid=~s/\_/\//;
 4319:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4320:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4321:                     return $1; 
 4322:                 } else {
 4323:                     if ($env{'request.course.sec'}) {
 4324:                         $courseprivid.='/'.$env{'request.course.sec'};
 4325:                     }
 4326:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4327:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4328:                         return $2;
 4329:                     }
 4330:                 }
 4331:             }
 4332:         }
 4333:     }
 4334: 
 4335: # Free bre to public access
 4336: 
 4337:     if ($priv eq 'bre') {
 4338:         my $copyright=&metadata($uri,'copyright');
 4339: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4340:            return 'F'; 
 4341:         }
 4342:         if ($copyright eq 'priv') {
 4343:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4344: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4345: 		return '';
 4346:             }
 4347:         }
 4348:         if ($copyright eq 'domain') {
 4349:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4350: 	    unless (($env{'user.domain'} eq $1) ||
 4351:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4352: 		return '';
 4353:             }
 4354:         }
 4355:         if ($env{'request.role'}=~ /li\.\//) {
 4356:             # Library role, so allow browsing of resources in this domain.
 4357:             return 'F';
 4358:         }
 4359:         if ($copyright eq 'custom') {
 4360: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4361:         }
 4362:     }
 4363:     # Domain coordinator is trying to create a course
 4364:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4365:         # uri is the requested domain in this case.
 4366:         # comparison to 'request.role.domain' shows if the user has selected
 4367:         # a role of dc for the domain in question.
 4368:         return 'F' if ($uri eq $env{'request.role.domain'});
 4369:     }
 4370: 
 4371:     my $thisallowed='';
 4372:     my $statecond=0;
 4373:     my $courseprivid='';
 4374: 
 4375: # Course
 4376: 
 4377:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4378:        $thisallowed.=$1;
 4379:     }
 4380: 
 4381: # Domain
 4382: 
 4383:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4384:        =~/\Q$priv\E\&([^\:]*)/) {
 4385:        $thisallowed.=$1;
 4386:     }
 4387: 
 4388: # Course: uri itself is a course
 4389:     my $courseuri=$uri;
 4390:     $courseuri=~s/\_(\d)/\/$1/;
 4391:     $courseuri=~s/^([^\/])/\/$1/;
 4392: 
 4393:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4394:        =~/\Q$priv\E\&([^\:]*)/) {
 4395:        $thisallowed.=$1;
 4396:     }
 4397: 
 4398: # URI is an uploaded document for this course, default permissions don't matter
 4399: # not allowing 'edit' access (editupload) to uploaded course docs
 4400:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4401: 	$thisallowed='';
 4402:         my ($match)=&is_on_map($uri);
 4403:         if ($match) {
 4404:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4405:                   =~/\Q$priv\E\&([^\:]*)/) {
 4406:                 $thisallowed.=$1;
 4407:             }
 4408:         } else {
 4409:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4410:             if ($refuri) {
 4411:                 if ($refuri =~ m|^/adm/|) {
 4412:                     $thisallowed='F';
 4413:                 } else {
 4414:                     $refuri=&declutter($refuri);
 4415:                     my ($match) = &is_on_map($refuri);
 4416:                     if ($match) {
 4417:                         $thisallowed='F';
 4418:                     }
 4419:                 }
 4420:             }
 4421:         }
 4422:     }
 4423: 
 4424:     if ($priv eq 'bre'
 4425: 	&& $thisallowed ne 'F' 
 4426: 	&& $thisallowed ne '2'
 4427: 	&& &is_portfolio_url($uri)) {
 4428: 	$thisallowed = &portfolio_access($uri);
 4429:     }
 4430:     
 4431: # Full access at system, domain or course-wide level? Exit.
 4432: 
 4433:     if ($thisallowed=~/F/) {
 4434: 	return 'F';
 4435:     }
 4436: 
 4437: # If this is generating or modifying users, exit with special codes
 4438: 
 4439:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4440: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4441: 	    my ($audom,$auname)=split('/',$uri);
 4442: # no author name given, so this just checks on the general right to make a co-author in this domain
 4443: 	    unless ($auname) { return $thisallowed; }
 4444: # an author name is given, so we are about to actually make a co-author for a certain account
 4445: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4446: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4447: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4448: 	}
 4449: 	return $thisallowed;
 4450:     }
 4451: #
 4452: # Gathered so far: system, domain and course wide privileges
 4453: #
 4454: # Course: See if uri or referer is an individual resource that is part of 
 4455: # the course
 4456: 
 4457:     if ($env{'request.course.id'}) {
 4458: 
 4459:        $courseprivid=$env{'request.course.id'};
 4460:        if ($env{'request.course.sec'}) {
 4461:           $courseprivid.='/'.$env{'request.course.sec'};
 4462:        }
 4463:        $courseprivid=~s/\_/\//;
 4464:        my $checkreferer=1;
 4465:        my ($match,$cond)=&is_on_map($uri);
 4466:        if ($match) {
 4467:            $statecond=$cond;
 4468:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4469:                =~/\Q$priv\E\&([^\:]*)/) {
 4470:                $thisallowed.=$1;
 4471:                $checkreferer=0;
 4472:            }
 4473:        }
 4474:        
 4475:        if ($checkreferer) {
 4476: 	  my $refuri=$env{'httpref.'.$orguri};
 4477:             unless ($refuri) {
 4478:                 foreach my $key (keys(%env)) {
 4479: 		    if ($key=~/^httpref\..*\*/) {
 4480: 			my $pattern=$key;
 4481:                         $pattern=~s/^httpref\.\/res\///;
 4482:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4483:                         $pattern=~s/\//\\\//g;
 4484:                         if ($orguri=~/$pattern/) {
 4485: 			    $refuri=$env{$key};
 4486:                         }
 4487:                     }
 4488:                 }
 4489:             }
 4490: 
 4491:          if ($refuri) { 
 4492: 	  $refuri=&declutter($refuri);
 4493:           my ($match,$cond)=&is_on_map($refuri);
 4494:             if ($match) {
 4495:               my $refstatecond=$cond;
 4496:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4497:                   =~/\Q$priv\E\&([^\:]*)/) {
 4498:                   $thisallowed.=$1;
 4499:                   $uri=$refuri;
 4500:                   $statecond=$refstatecond;
 4501:               }
 4502:           }
 4503:         }
 4504:        }
 4505:    }
 4506: 
 4507: #
 4508: # Gathered now: all privileges that could apply, and condition number
 4509: # 
 4510: #
 4511: # Full or no access?
 4512: #
 4513: 
 4514:     if ($thisallowed=~/F/) {
 4515: 	return 'F';
 4516:     }
 4517: 
 4518:     unless ($thisallowed) {
 4519:         return '';
 4520:     }
 4521: 
 4522: # Restrictions exist, deal with them
 4523: #
 4524: #   C:according to course preferences
 4525: #   R:according to resource settings
 4526: #   L:unless locked
 4527: #   X:according to user session state
 4528: #
 4529: 
 4530: # Possibly locked functionality, check all courses
 4531: # Locks might take effect only after 10 minutes cache expiration for other
 4532: # courses, and 2 minutes for current course
 4533: 
 4534:     my $envkey;
 4535:     if ($thisallowed=~/L/) {
 4536:         foreach $envkey (keys %env) {
 4537:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4538:                my $courseid=$2;
 4539:                my $roleid=$1.'.'.$2;
 4540:                $courseid=~s/^\///;
 4541:                my $expiretime=600;
 4542:                if ($env{'request.role'} eq $roleid) {
 4543: 		  $expiretime=120;
 4544:                }
 4545: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4546:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4547:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4548: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4549:                }
 4550:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4551:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4552: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4553:                        &log($env{'user.domain'},$env{'user.name'},
 4554:                             $env{'user.home'},
 4555:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4556:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4557:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4558: 		       return '';
 4559:                    }
 4560:                }
 4561:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4562:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4563: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4564:                        &log($env{'user.domain'},$env{'user.name'},
 4565:                             $env{'user.home'},
 4566:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4567:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4568:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4569: 		       return '';
 4570:                    }
 4571:                }
 4572: 	   }
 4573:        }
 4574:     }
 4575:    
 4576: #
 4577: # Rest of the restrictions depend on selected course
 4578: #
 4579: 
 4580:     unless ($env{'request.course.id'}) {
 4581: 	if ($thisallowed eq 'A') {
 4582: 	    return 'A';
 4583:         } elsif ($thisallowed eq 'B') {
 4584:             return 'B';
 4585: 	} else {
 4586: 	    return '1';
 4587: 	}
 4588:     }
 4589: 
 4590: #
 4591: # Now user is definitely in a course
 4592: #
 4593: 
 4594: 
 4595: # Course preferences
 4596: 
 4597:    if ($thisallowed=~/C/) {
 4598:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4599:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4600:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4601: 	   =~/\Q$rolecode\E/) {
 4602: 	   if ($priv ne 'pch') { 
 4603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4605: 			$env{'request.course.id'});
 4606: 	   }
 4607:            return '';
 4608:        }
 4609: 
 4610:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4611: 	   =~/\Q$unamedom\E/) {
 4612: 	   if ($priv ne 'pch') { 
 4613: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4614: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4615: 			$env{'request.course.id'});
 4616: 	   }
 4617:            return '';
 4618:        }
 4619:    }
 4620: 
 4621: # Resource preferences
 4622: 
 4623:    if ($thisallowed=~/R/) {
 4624:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4625:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4626: 	   if ($priv ne 'pch') { 
 4627: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4628: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4629: 	   }
 4630: 	   return '';
 4631:        }
 4632:    }
 4633: 
 4634: # Restricted by state or randomout?
 4635: 
 4636:    if ($thisallowed=~/X/) {
 4637:       if ($env{'acc.randomout'}) {
 4638: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4639:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4640:             return ''; 
 4641:          }
 4642:       }
 4643:       if (&condval($statecond)) {
 4644: 	 return '2';
 4645:       } else {
 4646:          return '';
 4647:       }
 4648:    }
 4649: 
 4650:     if ($thisallowed eq 'A') {
 4651: 	return 'A';
 4652:     } elsif ($thisallowed eq 'B') {
 4653:         return 'B';
 4654:     }
 4655:    return 'F';
 4656: }
 4657: 
 4658: sub split_uri_for_cond {
 4659:     my $uri=&deversion(&declutter(shift));
 4660:     my @uriparts=split(/\//,$uri);
 4661:     my $filename=pop(@uriparts);
 4662:     my $pathname=join('/',@uriparts);
 4663:     return ($pathname,$filename);
 4664: }
 4665: # --------------------------------------------------- Is a resource on the map?
 4666: 
 4667: sub is_on_map {
 4668:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4669:     #Trying to find the conditional for the file
 4670:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4671: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4672:     if ($match) {
 4673: 	return (1,$1);
 4674:     } else {
 4675: 	return (0,0);
 4676:     }
 4677: }
 4678: 
 4679: # --------------------------------------------------------- Get symb from alias
 4680: 
 4681: sub get_symb_from_alias {
 4682:     my $symb=shift;
 4683:     my ($map,$resid,$url)=&decode_symb($symb);
 4684: # Already is a symb
 4685:     if ($url) { return $symb; }
 4686: # Must be an alias
 4687:     my $aliassymb='';
 4688:     my %bighash;
 4689:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4690:                             &GDBM_READER(),0640)) {
 4691:         my $rid=$bighash{'mapalias_'.$symb};
 4692: 	if ($rid) {
 4693: 	    my ($mapid,$resid)=split(/\./,$rid);
 4694: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4695: 				    $resid,$bighash{'src_'.$rid});
 4696: 	}
 4697:         untie %bighash;
 4698:     }
 4699:     return $aliassymb;
 4700: }
 4701: 
 4702: # ----------------------------------------------------------------- Define Role
 4703: 
 4704: sub definerole {
 4705:   if (allowed('mcr','/')) {
 4706:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4707:     foreach my $role (split(':',$sysrole)) {
 4708: 	my ($crole,$cqual)=split(/\&/,$role);
 4709:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4710:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4711: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4712:                return "refused:s:$crole&$cqual"; 
 4713:             }
 4714:         }
 4715:     }
 4716:     foreach my $role (split(':',$domrole)) {
 4717: 	my ($crole,$cqual)=split(/\&/,$role);
 4718:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4719:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4720: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4721:                return "refused:d:$crole&$cqual"; 
 4722:             }
 4723:         }
 4724:     }
 4725:     foreach my $role (split(':',$courole)) {
 4726: 	my ($crole,$cqual)=split(/\&/,$role);
 4727:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4728:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4729: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4730:                return "refused:c:$crole&$cqual"; 
 4731:             }
 4732:         }
 4733:     }
 4734:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4735:                 "$env{'user.domain'}:$env{'user.name'}:".
 4736: 	        "rolesdef_$rolename=".
 4737:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4738:     return reply($command,$env{'user.home'});
 4739:   } else {
 4740:     return 'refused';
 4741:   }
 4742: }
 4743: 
 4744: # ---------------- Make a metadata query against the network of library servers
 4745: 
 4746: sub metadata_query {
 4747:     my ($query,$custom,$customshow,$server_array)=@_;
 4748:     my %rhash;
 4749:     my %libserv = &all_library();
 4750:     my @server_list = (defined($server_array) ? @$server_array
 4751:                                               : keys(%libserv) );
 4752:     for my $server (@server_list) {
 4753: 	unless ($custom or $customshow) {
 4754: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4755: 	    $rhash{$server}=$reply;
 4756: 	}
 4757: 	else {
 4758: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4759: 			     &escape($custom).':'.&escape($customshow),
 4760: 			     $server);
 4761: 	    $rhash{$server}=$reply;
 4762: 	}
 4763:     }
 4764:     return \%rhash;
 4765: }
 4766: 
 4767: # ----------------------------------------- Send log queries and wait for reply
 4768: 
 4769: sub log_query {
 4770:     my ($uname,$udom,$query,%filters)=@_;
 4771:     my $uhome=&homeserver($uname,$udom);
 4772:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4773:     my $uhost=&hostname($uhome);
 4774:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4775:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4776:                        $uhome);
 4777:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4778:     return get_query_reply($queryid);
 4779: }
 4780: 
 4781: # -------------------------- Update MySQL table for portfolio file
 4782: 
 4783: sub update_portfolio_table {
 4784:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4785:     my $homeserver = &homeserver($uname,$udom);
 4786:     my $queryid=
 4787:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4788:                ':'.&escape($file_name).':'.$action,$homeserver);
 4789:     my $reply = &get_query_reply($queryid);
 4790:     return $reply;
 4791: }
 4792: 
 4793: # -------------------------- Update MySQL allusers table
 4794: 
 4795: sub update_allusers_table {
 4796:     my ($uname,$udom,$names) = @_;
 4797:     my $homeserver = &homeserver($uname,$udom);
 4798:     my $queryid=
 4799:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4800:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4801:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4802:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4803:                'generation='.&escape($names->{'generation'}).'%%'.
 4804:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4805:                'id='.&escape($names->{'id'}),$homeserver);
 4806:     my $reply = &get_query_reply($queryid);
 4807:     return $reply;
 4808: }
 4809: 
 4810: # ------- Request retrieval of institutional classlists for course(s)
 4811: 
 4812: sub fetch_enrollment_query {
 4813:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4814:     my $homeserver;
 4815:     my $maxtries = 1;
 4816:     if ($context eq 'automated') {
 4817:         $homeserver = $perlvar{'lonHostID'};
 4818:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4819:     } else {
 4820:         $homeserver = &homeserver($cnum,$dom);
 4821:     }
 4822:     my $host=&hostname($homeserver);
 4823:     my $cmd = '';
 4824:     foreach my $affiliate (keys %{$affiliatesref}) {
 4825:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4826:     }
 4827:     $cmd =~ s/%%$//;
 4828:     $cmd = &escape($cmd);
 4829:     my $query = 'fetchenrollment';
 4830:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4831:     unless ($queryid=~/^\Q$host\E\_/) { 
 4832:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4833:         return 'error: '.$queryid;
 4834:     }
 4835:     my $reply = &get_query_reply($queryid);
 4836:     my $tries = 1;
 4837:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4838:         $reply = &get_query_reply($queryid);
 4839:         $tries ++;
 4840:     }
 4841:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4842:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4843:     } else {
 4844:         my @responses = split(/:/,$reply);
 4845:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4846:             foreach my $line (@responses) {
 4847:                 my ($key,$value) = split(/=/,$line,2);
 4848:                 $$replyref{$key} = $value;
 4849:             }
 4850:         } else {
 4851:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4852:             foreach my $line (@responses) {
 4853:                 my ($key,$value) = split(/=/,$line);
 4854:                 $$replyref{$key} = $value;
 4855:                 if ($value > 0) {
 4856:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4857:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4858:                         my $destname = $pathname.'/'.$filename;
 4859:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4860:                         if ($xml_classlist =~ /^error/) {
 4861:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4862:                         } else {
 4863:                             if ( open(FILE,">$destname") ) {
 4864:                                 print FILE &unescape($xml_classlist);
 4865:                                 close(FILE);
 4866:                             } else {
 4867:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4868:                             }
 4869:                         }
 4870:                     }
 4871:                 }
 4872:             }
 4873:         }
 4874:         return 'ok';
 4875:     }
 4876:     return 'error';
 4877: }
 4878: 
 4879: sub get_query_reply {
 4880:     my $queryid=shift;
 4881:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4882:     my $reply='';
 4883:     for (1..100) {
 4884: 	sleep 2;
 4885:         if (-e $replyfile.'.end') {
 4886: 	    if (open(my $fh,$replyfile)) {
 4887: 		$reply = join('',<$fh>);
 4888: 		close($fh);
 4889: 	   } else { return 'error: reply_file_error'; }
 4890:            return &unescape($reply);
 4891: 	}
 4892:     }
 4893:     return 'timeout:'.$queryid;
 4894: }
 4895: 
 4896: sub courselog_query {
 4897: #
 4898: # possible filters:
 4899: # url: url or symb
 4900: # username
 4901: # domain
 4902: # action: view, submit, grade
 4903: # start: timestamp
 4904: # end: timestamp
 4905: #
 4906:     my (%filters)=@_;
 4907:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4908:     if ($filters{'url'}) {
 4909: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4910:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4911:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4912:     }
 4913:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4914:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4915:     return &log_query($cname,$cdom,'courselog',%filters);
 4916: }
 4917: 
 4918: sub userlog_query {
 4919: #
 4920: # possible filters:
 4921: # action: log check role
 4922: # start: timestamp
 4923: # end: timestamp
 4924: #
 4925:     my ($uname,$udom,%filters)=@_;
 4926:     return &log_query($uname,$udom,'userlog',%filters);
 4927: }
 4928: 
 4929: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4930: 
 4931: sub auto_run {
 4932:     my ($cnum,$cdom) = @_;
 4933:     my $response = 0;
 4934:     my $settings;
 4935:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4936:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4937:         $settings = $domconfig{'autoenroll'};
 4938:         if ($settings->{'run'} eq '1') {
 4939:             $response = 1;
 4940:         }
 4941:     } else {
 4942:         my $homeserver;
 4943:         if (&is_course($cdom,$cnum)) {
 4944:             $homeserver = &homeserver($cnum,$cdom);
 4945:         } else {
 4946:             $homeserver = &domain($cdom,'primary');
 4947:         }
 4948:         if ($homeserver ne 'no_host') {
 4949:             $response = &reply('autorun:'.$cdom,$homeserver);
 4950:         }
 4951:     }
 4952:     return $response;
 4953: }
 4954: 
 4955: sub auto_get_sections {
 4956:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4957:     my $homeserver = &homeserver($cnum,$cdom);
 4958:     my @secs = ();
 4959:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4960:     unless ($response eq 'refused') {
 4961:         @secs = split(/:/,$response);
 4962:     }
 4963:     return @secs;
 4964: }
 4965: 
 4966: sub auto_new_course {
 4967:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4968:     my $homeserver = &homeserver($cnum,$cdom);
 4969:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4970:     return $response;
 4971: }
 4972: 
 4973: sub auto_validate_courseID {
 4974:     my ($cnum,$cdom,$inst_course_id) = @_;
 4975:     my $homeserver = &homeserver($cnum,$cdom);
 4976:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4977:     return $response;
 4978: }
 4979: 
 4980: sub auto_create_password {
 4981:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4982:     my ($homeserver,$response);
 4983:     my $create_passwd = 0;
 4984:     my $authchk = '';
 4985:     if ($udom =~ /^$match_domain$/) {
 4986:         $homeserver = &domain($udom,'primary');
 4987:     }
 4988:     if ($homeserver eq '') {
 4989:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4990:             $homeserver = &homeserver($cnum,$cdom);
 4991:         }
 4992:     }
 4993:     if ($homeserver eq '') {
 4994:         $authchk = 'nodomain';
 4995:     } else {
 4996:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4997:         if ($response eq 'refused') {
 4998:             $authchk = 'refused';
 4999:         } else {
 5000:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5001:         }
 5002:     }
 5003:     return ($authparam,$create_passwd,$authchk);
 5004: }
 5005: 
 5006: sub auto_photo_permission {
 5007:     my ($cnum,$cdom,$students) = @_;
 5008:     my $homeserver = &homeserver($cnum,$cdom);
 5009:     my ($outcome,$perm_reqd,$conditions) = 
 5010: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5011:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5012: 	return (undef,undef);
 5013:     }
 5014:     return ($outcome,$perm_reqd,$conditions);
 5015: }
 5016: 
 5017: sub auto_checkphotos {
 5018:     my ($uname,$udom,$pid) = @_;
 5019:     my $homeserver = &homeserver($uname,$udom);
 5020:     my ($result,$resulttype);
 5021:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5022: 				   &escape($uname).':'.&escape($pid),
 5023: 				   $homeserver));
 5024:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5025: 	return (undef,undef);
 5026:     }
 5027:     if ($outcome) {
 5028:         ($result,$resulttype) = split(/:/,$outcome);
 5029:     } 
 5030:     return ($result,$resulttype);
 5031: }
 5032: 
 5033: sub auto_photochoice {
 5034:     my ($cnum,$cdom) = @_;
 5035:     my $homeserver = &homeserver($cnum,$cdom);
 5036:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5037: 						       &escape($cdom),
 5038: 						       $homeserver)));
 5039:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5040: 	return (undef,undef);
 5041:     }
 5042:     return ($update,$comment);
 5043: }
 5044: 
 5045: sub auto_photoupdate {
 5046:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5047:     my $homeserver = &homeserver($cnum,$dom);
 5048:     my $host=&hostname($homeserver);
 5049:     my $cmd = '';
 5050:     my $maxtries = 1;
 5051:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5052:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5053:     }
 5054:     $cmd =~ s/%%$//;
 5055:     $cmd = &escape($cmd);
 5056:     my $query = 'institutionalphotos';
 5057:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5058:     unless ($queryid=~/^\Q$host\E\_/) {
 5059:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5060:         return 'error: '.$queryid;
 5061:     }
 5062:     my $reply = &get_query_reply($queryid);
 5063:     my $tries = 1;
 5064:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5065:         $reply = &get_query_reply($queryid);
 5066:         $tries ++;
 5067:     }
 5068:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5069:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5070:     } else {
 5071:         my @responses = split(/:/,$reply);
 5072:         my $outcome = shift(@responses); 
 5073:         foreach my $item (@responses) {
 5074:             my ($key,$value) = split(/=/,$item);
 5075:             $$photo{$key} = $value;
 5076:         }
 5077:         return $outcome;
 5078:     }
 5079:     return 'error';
 5080: }
 5081: 
 5082: sub auto_instcode_format {
 5083:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5084: 	$cat_order) = @_;
 5085:     my $courses = '';
 5086:     my @homeservers;
 5087:     if ($caller eq 'global') {
 5088: 	my %servers = &get_servers($codedom,'library');
 5089: 	foreach my $tryserver (keys(%servers)) {
 5090: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5091: 		push(@homeservers,$tryserver);
 5092: 	    }
 5093:         }
 5094:     } else {
 5095:         push(@homeservers,&homeserver($caller,$codedom));
 5096:     }
 5097:     foreach my $code (keys(%{$instcodes})) {
 5098:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5099:     }
 5100:     chop($courses);
 5101:     my $ok_response = 0;
 5102:     my $response;
 5103:     while (@homeservers > 0 && $ok_response == 0) {
 5104:         my $server = shift(@homeservers); 
 5105:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5106:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5107:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5108: 		split(/:/,$response);
 5109:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5110:             push(@{$codetitles},&str2array($codetitles_str));
 5111:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5112:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5113:             $ok_response = 1;
 5114:         }
 5115:     }
 5116:     if ($ok_response) {
 5117:         return 'ok';
 5118:     } else {
 5119:         return $response;
 5120:     }
 5121: }
 5122: 
 5123: sub auto_instcode_defaults {
 5124:     my ($domain,$returnhash,$code_order) = @_;
 5125:     my @homeservers;
 5126: 
 5127:     my %servers = &get_servers($domain,'library');
 5128:     foreach my $tryserver (keys(%servers)) {
 5129: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5130: 	    push(@homeservers,$tryserver);
 5131: 	}
 5132:     }
 5133: 
 5134:     my $response;
 5135:     foreach my $server (@homeservers) {
 5136:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5137:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5138: 	
 5139: 	foreach my $pair (split(/\&/,$response)) {
 5140: 	    my ($name,$value)=split(/\=/,$pair);
 5141: 	    if ($name eq 'code_order') {
 5142: 		@{$code_order} = split(/\&/,&unescape($value));
 5143: 	    } else {
 5144: 		$returnhash->{&unescape($name)}=&unescape($value);
 5145: 	    }
 5146: 	}
 5147: 	return 'ok';
 5148:     }
 5149: 
 5150:     return $response;
 5151: } 
 5152: 
 5153: sub auto_validate_class_sec {
 5154:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5155:     my $homeserver = &homeserver($cnum,$cdom);
 5156:     my $ownerlist;
 5157:     if (ref($owners) eq 'ARRAY') {
 5158:         $ownerlist = join(',',@{$owners});
 5159:     } else {
 5160:         $ownerlist = $owners;
 5161:     }
 5162:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5163:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5164:     return $response;
 5165: }
 5166: 
 5167: # ------------------------------------------------------- Course Group routines
 5168: 
 5169: sub get_coursegroups {
 5170:     my ($cdom,$cnum,$group,$namespace) = @_;
 5171:     return(&dump($namespace,$cdom,$cnum,$group));
 5172: }
 5173: 
 5174: sub modify_coursegroup {
 5175:     my ($cdom,$cnum,$groupsettings) = @_;
 5176:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5177: }
 5178: 
 5179: sub toggle_coursegroup_status {
 5180:     my ($cdom,$cnum,$group,$action) = @_;
 5181:     my ($from_namespace,$to_namespace);
 5182:     if ($action eq 'delete') {
 5183:         $from_namespace = 'coursegroups';
 5184:         $to_namespace = 'deleted_groups';
 5185:     } else {
 5186:         $from_namespace = 'deleted_groups';
 5187:         $to_namespace = 'coursegroups';
 5188:     }
 5189:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5190:     if (my $tmp = &error(%curr_group)) {
 5191:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5192:         return ('read error',$tmp);
 5193:     } else {
 5194:         my %savedsettings = %curr_group; 
 5195:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5196:         my $deloutcome;
 5197:         if ($result eq 'ok') {
 5198:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5199:         } else {
 5200:             return ('write error',$result);
 5201:         }
 5202:         if ($deloutcome eq 'ok') {
 5203:             return 'ok';
 5204:         } else {
 5205:             return ('delete error',$deloutcome);
 5206:         }
 5207:     }
 5208: }
 5209: 
 5210: sub modify_group_roles {
 5211:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5212:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5213:     my $role = 'gr/'.&escape($userprivs);
 5214:     my ($uname,$udom) = split(/:/,$user);
 5215:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5216:     if ($result eq 'ok') {
 5217:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5218:     }
 5219:     return $result;
 5220: }
 5221: 
 5222: sub modify_coursegroup_membership {
 5223:     my ($cdom,$cnum,$membership) = @_;
 5224:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5225:     return $result;
 5226: }
 5227: 
 5228: sub get_active_groups {
 5229:     my ($udom,$uname,$cdom,$cnum) = @_;
 5230:     my $now = time;
 5231:     my %groups = ();
 5232:     foreach my $key (keys(%env)) {
 5233:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5234:             my ($start,$end) = split(/\./,$env{$key});
 5235:             if (($end!=0) && ($end<$now)) { next; }
 5236:             if (($start!=0) && ($start>$now)) { next; }
 5237:             if ($1 eq $cdom && $2 eq $cnum) {
 5238:                 $groups{$3} = $env{$key} ;
 5239:             }
 5240:         }
 5241:     }
 5242:     return %groups;
 5243: }
 5244: 
 5245: sub get_group_membership {
 5246:     my ($cdom,$cnum,$group) = @_;
 5247:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5248: }
 5249: 
 5250: sub get_users_groups {
 5251:     my ($udom,$uname,$courseid) = @_;
 5252:     my @usersgroups;
 5253:     my $cachetime=1800;
 5254: 
 5255:     my $hashid="$udom:$uname:$courseid";
 5256:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5257:     if (defined($cached)) {
 5258:         @usersgroups = split(/:/,$grouplist);
 5259:     } else {  
 5260:         $grouplist = '';
 5261:         my $courseurl = &courseid_to_courseurl($courseid);
 5262:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5263:         my $access_end = $env{'course.'.$courseid.
 5264:                               '.default_enrollment_end_date'};
 5265:         my $now = time;
 5266:         foreach my $key (keys(%roleshash)) {
 5267:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5268:                 my $group = $1;
 5269:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5270:                     my $start = $2;
 5271:                     my $end = $1;
 5272:                     if ($start == -1) { next; } # deleted from group
 5273:                     if (($start!=0) && ($start>$now)) { next; }
 5274:                     if (($end!=0) && ($end<$now)) {
 5275:                         if ($access_end && $access_end < $now) {
 5276:                             if ($access_end - $end < 86400) {
 5277:                                 push(@usersgroups,$group);
 5278:                             }
 5279:                         }
 5280:                         next;
 5281:                     }
 5282:                     push(@usersgroups,$group);
 5283:                 }
 5284:             }
 5285:         }
 5286:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5287:         $grouplist = join(':',@usersgroups);
 5288:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5289:     }
 5290:     return @usersgroups;
 5291: }
 5292: 
 5293: sub devalidate_getgroups_cache {
 5294:     my ($udom,$uname,$cdom,$cnum)=@_;
 5295:     my $courseid = $cdom.'_'.$cnum;
 5296: 
 5297:     my $hashid="$udom:$uname:$courseid";
 5298:     &devalidate_cache_new('getgroups',$hashid);
 5299: }
 5300: 
 5301: # ------------------------------------------------------------------ Plain Text
 5302: 
 5303: sub plaintext {
 5304:     my ($short,$type,$cid) = @_;
 5305:     if ($short =~ /^cr/) {
 5306: 	return (split('/',$short))[-1];
 5307:     }
 5308:     if (!defined($cid)) {
 5309:         $cid = $env{'request.course.id'};
 5310:     }
 5311:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5312:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5313:                                           '.plaintext'});
 5314:     }
 5315:     my %rolenames = (
 5316:                       Course => 'std',
 5317:                       Group => 'alt1',
 5318:                     );
 5319:     if (defined($type) && 
 5320:          defined($rolenames{$type}) && 
 5321:          defined($prp{$short}{$rolenames{$type}})) {
 5322:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5323:     } else {
 5324:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5325:     }
 5326: }
 5327: 
 5328: # ----------------------------------------------------------------- Assign Role
 5329: 
 5330: sub assignrole {
 5331:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
 5332:     my $mrole;
 5333:     if ($role =~ /^cr\//) {
 5334:         my $cwosec=$url;
 5335:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5336: 	unless (&allowed('ccr',$cwosec)) {
 5337:            &logthis('Refused custom assignrole: '.
 5338:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5339: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5340:            return 'refused'; 
 5341:         }
 5342:         $mrole='cr';
 5343:     } elsif ($role =~ /^gr\//) {
 5344:         my $cwogrp=$url;
 5345:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5346:         unless (&allowed('mdg',$cwogrp)) {
 5347:             &logthis('Refused group assignrole: '.
 5348:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5349:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5350:             return 'refused';
 5351:         }
 5352:         $mrole='gr';
 5353:     } else {
 5354:         my $cwosec=$url;
 5355:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5356:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5357:             my $refused;
 5358:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5359:                 if (!(&allowed('c'.$role,$url))) {
 5360:                     $refused = 1;
 5361:                 }
 5362:             } else {
 5363:                 $refused = 1;
 5364:             }
 5365:             if ($refused) {
 5366:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5367:                     $refused = '';
 5368:                 } else {
 5369:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5370:                              ' '.$role.' '.$end.' '.$start.' by '.
 5371: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5372:                     return 'refused';
 5373:                 }
 5374:             }
 5375:         }
 5376:         $mrole=$role;
 5377:     }
 5378:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5379:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5380:     if ($end) { $command.='_'.$end; }
 5381:     if ($start) {
 5382: 	if ($end) { 
 5383:            $command.='_'.$start; 
 5384:         } else {
 5385:            $command.='_0_'.$start;
 5386:         }
 5387:     }
 5388:     my $origstart = $start;
 5389:     my $origend = $end;
 5390: # actually delete
 5391:     if ($deleteflag) {
 5392: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5393: # modify command to delete the role
 5394:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5395:                 "$udom:$uname:$url".'_'."$mrole";
 5396: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5397: # set start and finish to negative values for userrolelog
 5398:            $start=-1;
 5399:            $end=-1;
 5400:         }
 5401:     }
 5402: # send command
 5403:     my $answer=&reply($command,&homeserver($uname,$udom));
 5404: # log new user role if status is ok
 5405:     if ($answer eq 'ok') {
 5406: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5407: # for course roles, perform group memberships changes triggered by role change.
 5408:         unless ($role =~ /^gr/) {
 5409:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5410:                                              $origstart);
 5411:         }
 5412:     }
 5413:     return $answer;
 5414: }
 5415: 
 5416: # -------------------------------------------------- Modify user authentication
 5417: # Overrides without validation
 5418: 
 5419: sub modifyuserauth {
 5420:     my ($udom,$uname,$umode,$upass)=@_;
 5421:     my $uhome=&homeserver($uname,$udom);
 5422:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5423:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5424:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5425:              ' in domain '.$env{'request.role.domain'});  
 5426:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5427: 		     &escape($upass),$uhome);
 5428:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5429:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5430:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5431:     &log($udom,,$uname,$uhome,
 5432:         'Authentication changed by '.$env{'user.domain'}.', '.
 5433:                                      $env{'user.name'}.', '.$umode.
 5434:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5435:     unless ($reply eq 'ok') {
 5436:         &logthis('Authentication mode error: '.$reply);
 5437: 	return 'error: '.$reply;
 5438:     }   
 5439:     return 'ok';
 5440: }
 5441: 
 5442: # --------------------------------------------------------------- Modify a user
 5443: 
 5444: sub modifyuser {
 5445:     my ($udom,    $uname, $uid,
 5446:         $umode,   $upass, $first,
 5447:         $middle,  $last,  $gene,
 5448:         $forceid, $desiredhome, $email)=@_;
 5449:     $udom= &LONCAPA::clean_domain($udom);
 5450:     $uname=&LONCAPA::clean_username($uname);
 5451:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5452:              $umode.', '.$first.', '.$middle.', '.
 5453: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5454:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5455:                                      ' desiredhome not specified'). 
 5456:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5457:              ' in domain '.$env{'request.role.domain'});
 5458:     my $uhome=&homeserver($uname,$udom,'true');
 5459: # ----------------------------------------------------------------- Create User
 5460:     if (($uhome eq 'no_host') && 
 5461: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5462:         my $unhome='';
 5463:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5464:             $unhome = $desiredhome;
 5465: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5466: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5467:         } else { # load balancing routine for determining $unhome
 5468:             my $loadm=10000000;
 5469: 	    my %servers = &get_servers($udom,'library');
 5470: 	    foreach my $tryserver (keys(%servers)) {
 5471: 		my $answer=reply('load',$tryserver);
 5472: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5473: 		    $loadm=$answer;
 5474: 		    $unhome=$tryserver;
 5475: 		}
 5476: 	    }
 5477:         }
 5478:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5479: 	    return 'error: unable to find a home server for '.$uname.
 5480:                    ' in domain '.$udom;
 5481:         }
 5482:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5483:                          &escape($upass),$unhome);
 5484: 	unless ($reply eq 'ok') {
 5485:             return 'error: '.$reply;
 5486:         }   
 5487:         $uhome=&homeserver($uname,$udom,'true');
 5488:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5489: 	    return 'error: unable verify users home machine.';
 5490:         }
 5491:     }   # End of creation of new user
 5492: # ---------------------------------------------------------------------- Add ID
 5493:     if ($uid) {
 5494:        $uid=~tr/A-Z/a-z/;
 5495:        my %uidhash=&idrget($udom,$uname);
 5496:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5497:          && (!$forceid)) {
 5498: 	  unless ($uid eq $uidhash{$uname}) {
 5499: 	      return 'error: user id "'.$uid.'" does not match '.
 5500:                   'current user id "'.$uidhash{$uname}.'".';
 5501:           }
 5502:        } else {
 5503: 	  &idput($udom,($uname => $uid));
 5504:        }
 5505:     }
 5506: # -------------------------------------------------------------- Add names, etc
 5507:     my @tmp=&get('environment',
 5508: 		   ['firstname','middlename','lastname','generation','id',
 5509:                     'permanentemail'],
 5510: 		   $udom,$uname);
 5511:     my %names;
 5512:     if ($tmp[0] =~ m/^error:.*/) { 
 5513:         %names=(); 
 5514:     } else {
 5515:         %names = @tmp;
 5516:     }
 5517: #
 5518: # Make sure to not trash student environment if instructor does not bother
 5519: # to supply name and email information
 5520: #
 5521:     if ($first)  { $names{'firstname'}  = $first; }
 5522:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5523:     if ($last)   { $names{'lastname'}   = $last; }
 5524:     if (defined($gene))   { $names{'generation'} = $gene; }
 5525:     if ($email) {
 5526:        $email=~s/[^\w\@\.\-\,]//gs;
 5527:        if ($email=~/\@/) { $names{'notification'} = $email;
 5528: 			   $names{'critnotification'} = $email;
 5529: 			   $names{'permanentemail'} = $email; }
 5530:     }
 5531:     if ($uid) { $names{'id'}  = $uid; }
 5532:     my $reply = &put('environment', \%names, $udom,$uname);
 5533:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5534:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5535:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5536:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5537:              $umode.', '.$first.', '.$middle.', '.
 5538: 	     $last.', '.$gene.' by '.
 5539:              $env{'user.name'}.' at '.$env{'user.domain'});
 5540:     return 'ok';
 5541: }
 5542: 
 5543: # -------------------------------------------------------------- Modify student
 5544: 
 5545: sub modifystudent {
 5546:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5547:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5548:     if (!$cid) {
 5549: 	unless ($cid=$env{'request.course.id'}) {
 5550: 	    return 'not_in_class';
 5551: 	}
 5552:     }
 5553: # --------------------------------------------------------------- Make the user
 5554:     my $reply=&modifyuser
 5555: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5556:          $desiredhome,$email);
 5557:     unless ($reply eq 'ok') { return $reply; }
 5558:     # This will cause &modify_student_enrollment to get the uid from the
 5559:     # students environment
 5560:     $uid = undef if (!$forceid);
 5561:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5562: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5563:     return $reply;
 5564: }
 5565: 
 5566: sub modify_student_enrollment {
 5567:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
 5568:     my ($cdom,$cnum,$chome);
 5569:     if (!$cid) {
 5570: 	unless ($cid=$env{'request.course.id'}) {
 5571: 	    return 'not_in_class';
 5572: 	}
 5573: 	$cdom=$env{'course.'.$cid.'.domain'};
 5574: 	$cnum=$env{'course.'.$cid.'.num'};
 5575:     } else {
 5576: 	($cdom,$cnum)=split(/_/,$cid);
 5577:     }
 5578:     $chome=$env{'course.'.$cid.'.home'};
 5579:     if (!$chome) {
 5580: 	$chome=&homeserver($cnum,$cdom);
 5581:     }
 5582:     if (!$chome) { return 'unknown_course'; }
 5583:     # Make sure the user exists
 5584:     my $uhome=&homeserver($uname,$udom);
 5585:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5586: 	return 'error: no such user';
 5587:     }
 5588:     # Get student data if we were not given enough information
 5589:     if (!defined($first)  || $first  eq '' || 
 5590:         !defined($last)   || $last   eq '' || 
 5591:         !defined($uid)    || $uid    eq '' || 
 5592:         !defined($middle) || $middle eq '' || 
 5593:         !defined($gene)   || $gene   eq '') {
 5594:         # They did not supply us with enough data to enroll the student, so
 5595:         # we need to pick up more information.
 5596:         my %tmp = &get('environment',
 5597:                        ['firstname','middlename','lastname', 'generation','id']
 5598:                        ,$udom,$uname);
 5599: 
 5600:         #foreach my $key (keys(%tmp)) {
 5601:         #    &logthis("key $key = ".$tmp{$key});
 5602:         #}
 5603:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5604:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5605:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5606:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5607:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5608:     }
 5609:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5610:     my $reply=cput('classlist',
 5611: 		   {"$uname:$udom" => 
 5612: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5613: 		   $cdom,$cnum);
 5614:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5615: 	return 'error: '.$reply;
 5616:     } else {
 5617: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5618:     }
 5619:     # Add student role to user
 5620:     my $uurl='/'.$cid;
 5621:     $uurl=~s/\_/\//g;
 5622:     if ($usec) {
 5623: 	$uurl.='/'.$usec;
 5624:     }
 5625:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
 5626: }
 5627: 
 5628: sub format_name {
 5629:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5630:     my $name;
 5631:     if ($first ne 'lastname') {
 5632: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5633:     } else {
 5634: 	if ($lastname=~/\S/) {
 5635: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5636: 	    $name=~s/\s+,/,/;
 5637: 	} else {
 5638: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5639: 	}
 5640:     }
 5641:     $name=~s/^\s+//;
 5642:     $name=~s/\s+$//;
 5643:     $name=~s/\s+/ /g;
 5644:     return $name;
 5645: }
 5646: 
 5647: # ------------------------------------------------- Write to course preferences
 5648: 
 5649: sub writecoursepref {
 5650:     my ($courseid,%prefs)=@_;
 5651:     $courseid=~s/^\///;
 5652:     $courseid=~s/\_/\//g;
 5653:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5654:     my $chome=homeserver($cnum,$cdomain);
 5655:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5656: 	return 'error: no such course';
 5657:     }
 5658:     my $cstring='';
 5659:     foreach my $pref (keys(%prefs)) {
 5660: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5661:     }
 5662:     $cstring=~s/\&$//;
 5663:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5664: }
 5665: 
 5666: # ---------------------------------------------------------- Make/modify course
 5667: 
 5668: sub createcourse {
 5669:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5670:         $course_owner,$crstype)=@_;
 5671:     $url=&declutter($url);
 5672:     my $cid='';
 5673:     unless (&allowed('ccc',$udom)) {
 5674:         return 'refused';
 5675:     }
 5676: # ------------------------------------------------------------------- Create ID
 5677:    my $uname=int(1+rand(9)).
 5678:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5679:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5680:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5681: # ----------------------------------------------- Make sure that does not exist
 5682:    my $uhome=&homeserver($uname,$udom,'true');
 5683:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5684:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5685:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5686:        $uhome=&homeserver($uname,$udom,'true');       
 5687:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5688:            return 'error: unable to generate unique course-ID';
 5689:        } 
 5690:    }
 5691: # ------------------------------------------------ Check supplied server name
 5692:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5693:     if (! &is_library($course_server)) {
 5694:         return 'error:bad server name '.$course_server;
 5695:     }
 5696: # ------------------------------------------------------------- Make the course
 5697:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5698:                       $course_server);
 5699:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5700:     $uhome=&homeserver($uname,$udom,'true');
 5701:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5702: 	return 'error: no such course';
 5703:     }
 5704: # ----------------------------------------------------------------- Course made
 5705: # log existence
 5706:     my $newcourse = {
 5707:                     $udom.'_'.$uname => {
 5708:                                      description => $description,
 5709:                                      inst_code   => $inst_code,
 5710:                                      owner       => $course_owner,
 5711:                                      type        => $crstype,
 5712:                                                 },
 5713:                     };
 5714:     &courseidput($udom,$newcourse,$uhome,'notime');
 5715: # set toplevel url
 5716:     my $topurl=$url;
 5717:     unless ($nonstandard) {
 5718: # ------------------------------------------ For standard courses, make top url
 5719:         my $mapurl=&clutter($url);
 5720:         if ($mapurl eq '/res/') { $mapurl=''; }
 5721:         $env{'form.initmap'}=(<<ENDINITMAP);
 5722: <map>
 5723: <resource id="1" type="start"></resource>
 5724: <resource id="2" src="$mapurl"></resource>
 5725: <resource id="3" type="finish"></resource>
 5726: <link index="1" from="1" to="2"></link>
 5727: <link index="2" from="2" to="3"></link>
 5728: </map>
 5729: ENDINITMAP
 5730:         $topurl=&declutter(
 5731:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5732:                           );
 5733:     }
 5734: # ----------------------------------------------------------- Write preferences
 5735:     &writecoursepref($udom.'_'.$uname,
 5736:                      ('description' => $description,
 5737:                       'url'         => $topurl));
 5738:     return '/'.$udom.'/'.$uname;
 5739: }
 5740: 
 5741: sub is_course {
 5742:     my ($cdom,$cnum) = @_;
 5743:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5744: 				undef,'.');
 5745:     if (exists($courses{$cdom.'_'.$cnum})) {
 5746:         return 1;
 5747:     }
 5748:     return 0;
 5749: }
 5750: 
 5751: # ---------------------------------------------------------- Assign Custom Role
 5752: 
 5753: sub assigncustomrole {
 5754:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5755:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5756:                        $end,$start,$deleteflag);
 5757: }
 5758: 
 5759: # ----------------------------------------------------------------- Revoke Role
 5760: 
 5761: sub revokerole {
 5762:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5763:     my $now=time;
 5764:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5765: }
 5766: 
 5767: # ---------------------------------------------------------- Revoke Custom Role
 5768: 
 5769: sub revokecustomrole {
 5770:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5771:     my $now=time;
 5772:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5773:            $deleteflag);
 5774: }
 5775: 
 5776: # ------------------------------------------------------------ Disk usage
 5777: sub diskusage {
 5778:     my ($udom,$uname,$directoryRoot)=@_;
 5779:     $directoryRoot =~ s/\/$//;
 5780:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5781:     return $listing;
 5782: }
 5783: 
 5784: sub is_locked {
 5785:     my ($file_name, $domain, $user) = @_;
 5786:     my @check;
 5787:     my $is_locked;
 5788:     push @check, $file_name;
 5789:     my %locked = &get('file_permissions',\@check,
 5790: 		      $env{'user.domain'},$env{'user.name'});
 5791:     my ($tmp)=keys(%locked);
 5792:     if ($tmp=~/^error:/) { undef(%locked); }
 5793:     
 5794:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5795:         $is_locked = 'false';
 5796:         foreach my $entry (@{$locked{$file_name}}) {
 5797:            if (ref($entry) eq 'ARRAY') { 
 5798:                $is_locked = 'true';
 5799:                last;
 5800:            }
 5801:        }
 5802:     } else {
 5803:         $is_locked = 'false';
 5804:     }
 5805: }
 5806: 
 5807: sub declutter_portfile {
 5808:     my ($file) = @_;
 5809:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5810:     return $file;
 5811: }
 5812: 
 5813: # ------------------------------------------------------------- Mark as Read Only
 5814: 
 5815: sub mark_as_readonly {
 5816:     my ($domain,$user,$files,$what) = @_;
 5817:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5818:     my ($tmp)=keys(%current_permissions);
 5819:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5820:     foreach my $file (@{$files}) {
 5821: 	$file = &declutter_portfile($file);
 5822:         push(@{$current_permissions{$file}},$what);
 5823:     }
 5824:     &put('file_permissions',\%current_permissions,$domain,$user);
 5825:     return;
 5826: }
 5827: 
 5828: # ------------------------------------------------------------Save Selected Files
 5829: 
 5830: sub save_selected_files {
 5831:     my ($user, $path, @files) = @_;
 5832:     my $filename = $user."savedfiles";
 5833:     my @other_files = &files_not_in_path($user, $path);
 5834:     open (OUT, '>'.$tmpdir.$filename);
 5835:     foreach my $file (@files) {
 5836:         print (OUT $env{'form.currentpath'}.$file."\n");
 5837:     }
 5838:     foreach my $file (@other_files) {
 5839:         print (OUT $file."\n");
 5840:     }
 5841:     close (OUT);
 5842:     return 'ok';
 5843: }
 5844: 
 5845: sub clear_selected_files {
 5846:     my ($user) = @_;
 5847:     my $filename = $user."savedfiles";
 5848:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5849:     print (OUT undef);
 5850:     close (OUT);
 5851:     return ("ok");    
 5852: }
 5853: 
 5854: sub files_in_path {
 5855:     my ($user, $path) = @_;
 5856:     my $filename = $user."savedfiles";
 5857:     my %return_files;
 5858:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5859:     while (my $line_in = <IN>) {
 5860:         chomp ($line_in);
 5861:         my @paths_and_file = split (m!/!, $line_in);
 5862:         my $file_part = pop (@paths_and_file);
 5863:         my $path_part = join ('/', @paths_and_file);
 5864:         $path_part.='/';
 5865:         my $path_and_file = $path_part.$file_part;
 5866:         if ($path_part eq $path) {
 5867:             $return_files{$file_part}= 'selected';
 5868:         }
 5869:     }
 5870:     close (IN);
 5871:     return (\%return_files);
 5872: }
 5873: 
 5874: # called in portfolio select mode, to show files selected NOT in current directory
 5875: sub files_not_in_path {
 5876:     my ($user, $path) = @_;
 5877:     my $filename = $user."savedfiles";
 5878:     my @return_files;
 5879:     my $path_part;
 5880:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5881:     while (my $line = <IN>) {
 5882:         #ok, I know it's clunky, but I want it to work
 5883:         my @paths_and_file = split(m|/|, $line);
 5884:         my $file_part = pop(@paths_and_file);
 5885:         chomp($file_part);
 5886:         my $path_part = join('/', @paths_and_file);
 5887:         $path_part .= '/';
 5888:         my $path_and_file = $path_part.$file_part;
 5889:         if ($path_part ne $path) {
 5890:             push(@return_files, ($path_and_file));
 5891:         }
 5892:     }
 5893:     close(OUT);
 5894:     return (@return_files);
 5895: }
 5896: 
 5897: #----------------------------------------------Get portfolio file permissions
 5898: 
 5899: sub get_portfile_permissions {
 5900:     my ($domain,$user) = @_;
 5901:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5902:     my ($tmp)=keys(%current_permissions);
 5903:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5904:     return \%current_permissions;
 5905: }
 5906: 
 5907: #---------------------------------------------Get portfolio file access controls
 5908: 
 5909: sub get_access_controls {
 5910:     my ($current_permissions,$group,$file) = @_;
 5911:     my %access;
 5912:     my $real_file = $file;
 5913:     $file =~ s/\.meta$//;
 5914:     if (defined($file)) {
 5915:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5916:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5917:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5918:             }
 5919:         }
 5920:     } else {
 5921:         foreach my $key (keys(%{$current_permissions})) {
 5922:             if ($key =~ /\0accesscontrol$/) {
 5923:                 if (defined($group)) {
 5924:                     if ($key !~ m-^\Q$group\E/-) {
 5925:                         next;
 5926:                     }
 5927:                 }
 5928:                 my ($fullpath) = split(/\0/,$key);
 5929:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5930:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5931:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5932:                     }
 5933:                 }
 5934:             }
 5935:         }
 5936:     }
 5937:     return %access;
 5938: }
 5939: 
 5940: sub modify_access_controls {
 5941:     my ($file_name,$changes,$domain,$user)=@_;
 5942:     my ($outcome,$deloutcome);
 5943:     my %store_permissions;
 5944:     my %new_values;
 5945:     my %new_control;
 5946:     my %translation;
 5947:     my @deletions = ();
 5948:     my $now = time;
 5949:     if (exists($$changes{'activate'})) {
 5950:         if (ref($$changes{'activate'}) eq 'HASH') {
 5951:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5952:             my $numnew = scalar(@newitems);
 5953:             for (my $i=0; $i<$numnew; $i++) {
 5954:                 my $newkey = $newitems[$i];
 5955:                 my $newid = &Apache::loncommon::get_cgi_id();
 5956:                 if ($newkey =~ /^\d+:/) { 
 5957:                     $newkey =~ s/^(\d+)/$newid/;
 5958:                     $translation{$1} = $newid;
 5959:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5960:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5961:                     $translation{$1} = $newid;
 5962:                 }
 5963:                 $new_values{$file_name."\0".$newkey} = 
 5964:                                           $$changes{'activate'}{$newitems[$i]};
 5965:                 $new_control{$newkey} = $now;
 5966:             }
 5967:         }
 5968:     }
 5969:     my %todelete;
 5970:     my %changed_items;
 5971:     foreach my $action ('delete','update') {
 5972:         if (exists($$changes{$action})) {
 5973:             if (ref($$changes{$action}) eq 'HASH') {
 5974:                 foreach my $key (keys(%{$$changes{$action}})) {
 5975:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5976:                     if ($action eq 'delete') { 
 5977:                         $todelete{$itemnum} = 1;
 5978:                     } else {
 5979:                         $changed_items{$itemnum} = $key;
 5980:                     }
 5981:                 }
 5982:             }
 5983:         }
 5984:     }
 5985:     # get lock on access controls for file.
 5986:     my $lockhash = {
 5987:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5988:                                                        ':'.$env{'user.domain'},
 5989:                    }; 
 5990:     my $tries = 0;
 5991:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5992:    
 5993:     while (($gotlock ne 'ok') && $tries <3) {
 5994:         $tries ++;
 5995:         sleep 1;
 5996:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5997:     }
 5998:     if ($gotlock eq 'ok') {
 5999:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6000:         my ($tmp)=keys(%curr_permissions);
 6001:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6002:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6003:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6004:             if (ref($curr_controls) eq 'HASH') {
 6005:                 foreach my $control_item (keys(%{$curr_controls})) {
 6006:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6007:                     if (defined($todelete{$itemnum})) {
 6008:                         push(@deletions,$file_name."\0".$control_item);
 6009:                     } else {
 6010:                         if (defined($changed_items{$itemnum})) {
 6011:                             $new_control{$changed_items{$itemnum}} = $now;
 6012:                             push(@deletions,$file_name."\0".$control_item);
 6013:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6014:                         } else {
 6015:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6016:                         }
 6017:                     }
 6018:                 }
 6019:             }
 6020:         }
 6021:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6022:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6023:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6024:         #  remove lock
 6025:         my @del_lock = ($file_name."\0".'locked_access_records');
 6026:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6027:         my ($file,$group);
 6028:         if (&is_course($domain,$user)) {
 6029:             ($group,$file) = split(/\//,$file_name,2);
 6030:         } else {
 6031:             $file = $file_name;
 6032:         }
 6033:         my $sqlresult =
 6034:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 6035:                                     $group);
 6036:     } else {
 6037:         $outcome = "error: could not obtain lockfile\n";  
 6038:     }
 6039:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6040: }
 6041: 
 6042: sub make_public_indefinitely {
 6043:     my ($requrl) = @_;
 6044:     my $now = time;
 6045:     my $action = 'activate';
 6046:     my $aclnum = 0;
 6047:     if (&is_portfolio_url($requrl)) {
 6048:         my (undef,$udom,$unum,$file_name,$group) =
 6049:             &parse_portfolio_url($requrl);
 6050:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6051:         my %access_controls = &get_access_controls($current_perms,
 6052:                                                    $group,$file_name);
 6053:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6054:             my ($num,$scope,$end,$start) = 
 6055:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6056:             if ($scope eq 'public') {
 6057:                 if ($start <= $now && $end == 0) {
 6058:                     $action = 'none';
 6059:                 } else {
 6060:                     $action = 'update';
 6061:                     $aclnum = $num;
 6062:                 }
 6063:                 last;
 6064:             }
 6065:         }
 6066:         if ($action eq 'none') {
 6067:              return 'ok';
 6068:         } else {
 6069:             my %changes;
 6070:             my $newend = 0;
 6071:             my $newstart = $now;
 6072:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6073:             $changes{$action}{$newkey} = {
 6074:                 type => 'public',
 6075:                 time => {
 6076:                     start => $newstart,
 6077:                     end   => $newend,
 6078:                 },
 6079:             };
 6080:             my ($outcome,$deloutcome,$new_values,$translation) =
 6081:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6082:             return $outcome;
 6083:         }
 6084:     } else {
 6085:         return 'invalid';
 6086:     }
 6087: }
 6088: 
 6089: #------------------------------------------------------Get Marked as Read Only
 6090: 
 6091: sub get_marked_as_readonly {
 6092:     my ($domain,$user,$what,$group) = @_;
 6093:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6094:     my @readonly_files;
 6095:     my $cmp1=$what;
 6096:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6097:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6098:         if (defined($group)) {
 6099:             if ($file_name !~ m-^\Q$group\E/-) {
 6100:                 next;
 6101:             }
 6102:         }
 6103:         if (ref($value) eq "ARRAY"){
 6104:             foreach my $stored_what (@{$value}) {
 6105:                 my $cmp2=$stored_what;
 6106:                 if (ref($stored_what) eq 'ARRAY') {
 6107:                     $cmp2=join('',@{$stored_what});
 6108:                 }
 6109:                 if ($cmp1 eq $cmp2) {
 6110:                     push(@readonly_files, $file_name);
 6111:                     last;
 6112:                 } elsif (!defined($what)) {
 6113:                     push(@readonly_files, $file_name);
 6114:                     last;
 6115:                 }
 6116:             }
 6117:         }
 6118:     }
 6119:     return @readonly_files;
 6120: }
 6121: #-----------------------------------------------------------Get Marked as Read Only Hash
 6122: 
 6123: sub get_marked_as_readonly_hash {
 6124:     my ($current_permissions,$group,$what) = @_;
 6125:     my %readonly_files;
 6126:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6127:         if (defined($group)) {
 6128:             if ($file_name !~ m-^\Q$group\E/-) {
 6129:                 next;
 6130:             }
 6131:         }
 6132:         if (ref($value) eq "ARRAY"){
 6133:             foreach my $stored_what (@{$value}) {
 6134:                 if (ref($stored_what) eq 'ARRAY') {
 6135:                     foreach my $lock_descriptor(@{$stored_what}) {
 6136:                         if ($lock_descriptor eq 'graded') {
 6137:                             $readonly_files{$file_name} = 'graded';
 6138:                         } elsif ($lock_descriptor eq 'handback') {
 6139:                             $readonly_files{$file_name} = 'handback';
 6140:                         } else {
 6141:                             if (!exists($readonly_files{$file_name})) {
 6142:                                 $readonly_files{$file_name} = 'locked';
 6143:                             }
 6144:                         }
 6145:                     }
 6146:                 } 
 6147:             }
 6148:         } 
 6149:     }
 6150:     return %readonly_files;
 6151: }
 6152: # ------------------------------------------------------------ Unmark as Read Only
 6153: 
 6154: sub unmark_as_readonly {
 6155:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6156:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6157:     my ($domain,$user,$what,$file_name,$group) = @_;
 6158:     $file_name = &declutter_portfile($file_name);
 6159:     my $symb_crs = $what;
 6160:     if (ref($what)) { $symb_crs=join('',@$what); }
 6161:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6162:     my ($tmp)=keys(%current_permissions);
 6163:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6164:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6165:     foreach my $file (@readonly_files) {
 6166: 	my $clean_file = &declutter_portfile($file);
 6167: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6168: 	my $current_locks = $current_permissions{$file};
 6169:         my @new_locks;
 6170:         my @del_keys;
 6171:         if (ref($current_locks) eq "ARRAY"){
 6172:             foreach my $locker (@{$current_locks}) {
 6173:                 my $compare=$locker;
 6174:                 if (ref($locker) eq 'ARRAY') {
 6175:                     $compare=join('',@{$locker});
 6176:                     if ($compare ne $symb_crs) {
 6177:                         push(@new_locks, $locker);
 6178:                     }
 6179:                 }
 6180:             }
 6181:             if (scalar(@new_locks) > 0) {
 6182:                 $current_permissions{$file} = \@new_locks;
 6183:             } else {
 6184:                 push(@del_keys, $file);
 6185:                 &del('file_permissions',\@del_keys, $domain, $user);
 6186:                 delete($current_permissions{$file});
 6187:             }
 6188:         }
 6189:     }
 6190:     &put('file_permissions',\%current_permissions,$domain,$user);
 6191:     return;
 6192: }
 6193: 
 6194: # ------------------------------------------------------------ Directory lister
 6195: 
 6196: sub dirlist {
 6197:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6198: 
 6199:     $uri=~s/^\///;
 6200:     $uri=~s/\/$//;
 6201:     my ($udom, $uname);
 6202:     (undef,$udom,$uname)=split(/\//,$uri);
 6203:     if(defined($userdomain)) {
 6204:         $udom = $userdomain;
 6205:     }
 6206:     if(defined($username)) {
 6207:         $uname = $username;
 6208:     }
 6209: 
 6210:     my $dirRoot = $perlvar{'lonDocRoot'};
 6211:     if(defined($alternateDirectoryRoot)) {
 6212:         $dirRoot = $alternateDirectoryRoot;
 6213:         $dirRoot =~ s/\/$//;
 6214:     }
 6215: 
 6216:     if($udom) {
 6217:         if($uname) {
 6218:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6219: 				 &homeserver($uname,$udom));
 6220:             my @listing_results;
 6221:             if ($listing eq 'unknown_cmd') {
 6222:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6223: 				  &homeserver($uname,$udom));
 6224:                 @listing_results = split(/:/,$listing);
 6225:             } else {
 6226:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6227:             }
 6228:             return @listing_results;
 6229:         } elsif(!defined($alternateDirectoryRoot)) {
 6230:             my %allusers;
 6231: 	    my %servers = &get_servers($udom,'library');
 6232: 	    foreach my $tryserver (keys(%servers)) {
 6233: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6234: 				     $udom, $tryserver);
 6235: 		my @listing_results;
 6236: 		if ($listing eq 'unknown_cmd') {
 6237: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6238: 				      $udom, $tryserver);
 6239: 		    @listing_results = split(/:/,$listing);
 6240: 		} else {
 6241: 		    @listing_results =
 6242: 			map { &unescape($_); } split(/:/,$listing);
 6243: 		}
 6244: 		if ($listing_results[0] ne 'no_such_dir' && 
 6245: 		    $listing_results[0] ne 'empty'       &&
 6246: 		    $listing_results[0] ne 'con_lost') {
 6247: 		    foreach my $line (@listing_results) {
 6248: 			my ($entry) = split(/&/,$line,2);
 6249: 			$allusers{$entry} = 1;
 6250: 		    }
 6251: 		}
 6252:             }
 6253:             my $alluserstr='';
 6254:             foreach my $user (sort(keys(%allusers))) {
 6255:                 $alluserstr.=$user.'&user:';
 6256:             }
 6257:             $alluserstr=~s/:$//;
 6258:             return split(/:/,$alluserstr);
 6259:         } else {
 6260:             return ('missing user name');
 6261:         }
 6262:     } elsif(!defined($alternateDirectoryRoot)) {
 6263:         my @all_domains = sort(&all_domains());
 6264:          foreach my $domain (@all_domains) {
 6265:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6266:          }
 6267:          return @all_domains;
 6268:      } else {
 6269:         return ('missing domain');
 6270:     }
 6271: }
 6272: 
 6273: # --------------------------------------------- GetFileTimestamp
 6274: # This function utilizes dirlist and returns the date stamp for
 6275: # when it was last modified.  It will also return an error of -1
 6276: # if an error occurs
 6277: 
 6278: ##
 6279: ## FIXME: This subroutine assumes its caller knows something about the
 6280: ## directory structure of the home server for the student ($root).
 6281: ## Not a good assumption to make.  Since this is for looking up files
 6282: ## in user directories, the full path should be constructed by lond, not
 6283: ## whatever machine we request data from.
 6284: ##
 6285: sub GetFileTimestamp {
 6286:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6287:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6288:     $studentName   = &LONCAPA::clean_username($studentName);
 6289:     my $subdir=$studentName.'__';
 6290:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6291:     my $proname="$studentDomain/$subdir/$studentName";
 6292:     $proname .= '/'.$filename;
 6293:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6294:                                               $studentName, $root);
 6295:     my @stats = split('&', $fileStat);
 6296:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6297:         # @stats contains first the filename, then the stat output
 6298:         return $stats[10]; # so this is 10 instead of 9.
 6299:     } else {
 6300:         return -1;
 6301:     }
 6302: }
 6303: 
 6304: sub stat_file {
 6305:     my ($uri) = @_;
 6306:     $uri = &clutter_with_no_wrapper($uri);
 6307: 
 6308:     my ($udom,$uname,$file,$dir);
 6309:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6310: 	($udom,$uname,$file) =
 6311: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6312: 	$file = 'userfiles/'.$file;
 6313: 	$dir = &propath($udom,$uname);
 6314:     }
 6315:     if ($uri =~ m-^/res/-) {
 6316: 	($udom,$uname) = 
 6317: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6318: 	$file = $uri;
 6319:     }
 6320: 
 6321:     if (!$udom || !$uname || !$file) {
 6322: 	# unable to handle the uri
 6323: 	return ();
 6324:     }
 6325: 
 6326:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6327:     my @stats = split('&', $result);
 6328:     
 6329:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6330: 	shift(@stats); #filename is first
 6331: 	return @stats;
 6332:     }
 6333:     return ();
 6334: }
 6335: 
 6336: # -------------------------------------------------------- Value of a Condition
 6337: 
 6338: # gets the value of a specific preevaluated condition
 6339: #    stored in the string  $env{user.state.<cid>}
 6340: # or looks up a condition reference in the bighash and if if hasn't
 6341: # already been evaluated recurses into docondval to get the value of
 6342: # the condition, then memoizing it to 
 6343: #   $env{user.state.<cid>.<condition>}
 6344: sub directcondval {
 6345:     my $number=shift;
 6346:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6347: 	&Apache::lonuserstate::evalstate();
 6348:     }
 6349:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6350: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6351:     } elsif ($number =~ /^_/) {
 6352: 	my $sub_condition;
 6353: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6354: 		&GDBM_READER(),0640)) {
 6355: 	    $sub_condition=$bighash{'conditions'.$number};
 6356: 	    untie(%bighash);
 6357: 	}
 6358: 	my $value = &docondval($sub_condition);
 6359: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6360: 	return $value;
 6361:     }
 6362:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6363:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6364:     } else {
 6365:        return 2;
 6366:     }
 6367: }
 6368: 
 6369: # get the collection of conditions for this resource
 6370: sub condval {
 6371:     my $condidx=shift;
 6372:     my $allpathcond='';
 6373:     foreach my $cond (split(/\|/,$condidx)) {
 6374: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6375: 	    $allpathcond.=
 6376: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6377: 	}
 6378:     }
 6379:     $allpathcond=~s/\|$//;
 6380:     return &docondval($allpathcond);
 6381: }
 6382: 
 6383: #evaluates an expression of conditions
 6384: sub docondval {
 6385:     my ($allpathcond) = @_;
 6386:     my $result=0;
 6387:     if ($env{'request.course.id'}
 6388: 	&& defined($allpathcond)) {
 6389: 	my $operand='|';
 6390: 	my @stack;
 6391: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6392: 	    if ($chunk eq '(') {
 6393: 		push @stack,($operand,$result);
 6394: 	    } elsif ($chunk eq ')') {
 6395: 		my $before=pop @stack;
 6396: 		if (pop @stack eq '&') {
 6397: 		    $result=$result>$before?$before:$result;
 6398: 		} else {
 6399: 		    $result=$result>$before?$result:$before;
 6400: 		}
 6401: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6402: 		$operand=$chunk;
 6403: 	    } else {
 6404: 		my $new=directcondval($chunk);
 6405: 		if ($operand eq '&') {
 6406: 		    $result=$result>$new?$new:$result;
 6407: 		} else {
 6408: 		    $result=$result>$new?$result:$new;
 6409: 		}
 6410: 	    }
 6411: 	}
 6412:     }
 6413:     return $result;
 6414: }
 6415: 
 6416: # ---------------------------------------------------- Devalidate courseresdata
 6417: 
 6418: sub devalidatecourseresdata {
 6419:     my ($coursenum,$coursedomain)=@_;
 6420:     my $hashid=$coursenum.':'.$coursedomain;
 6421:     &devalidate_cache_new('courseres',$hashid);
 6422: }
 6423: 
 6424: 
 6425: # --------------------------------------------------- Course Resourcedata Query
 6426: #
 6427: #  Parameters:
 6428: #      $coursenum    - Number of the course.
 6429: #      $coursedomain - Domain at which the course was created.
 6430: #  Returns:
 6431: #     A hash of the course parameters along (I think) with timestamps
 6432: #     and version info.
 6433: 
 6434: sub get_courseresdata {
 6435:     my ($coursenum,$coursedomain)=@_;
 6436:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6437:     my $hashid=$coursenum.':'.$coursedomain;
 6438:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6439:     my %dumpreply;
 6440:     unless (defined($cached)) {
 6441: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6442: 	$result=\%dumpreply;
 6443: 	my ($tmp) = keys(%dumpreply);
 6444: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6445: 	    &do_cache_new('courseres',$hashid,$result,600);
 6446: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6447: 	    return $tmp;
 6448: 	} elsif ($tmp =~ /^(error)/) {
 6449: 	    $result=undef;
 6450: 	    &do_cache_new('courseres',$hashid,$result,600);
 6451: 	}
 6452:     }
 6453:     return $result;
 6454: }
 6455: 
 6456: sub devalidateuserresdata {
 6457:     my ($uname,$udom)=@_;
 6458:     my $hashid="$udom:$uname";
 6459:     &devalidate_cache_new('userres',$hashid);
 6460: }
 6461: 
 6462: sub get_userresdata {
 6463:     my ($uname,$udom)=@_;
 6464:     #most student don\'t have any data set, check if there is some data
 6465:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6466: 
 6467:     my $hashid="$udom:$uname";
 6468:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6469:     if (!defined($cached)) {
 6470: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6471: 	$result=\%resourcedata;
 6472: 	&do_cache_new('userres',$hashid,$result,600);
 6473:     }
 6474:     my ($tmp)=keys(%$result);
 6475:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6476: 	return $result;
 6477:     }
 6478:     #error 2 occurs when the .db doesn't exist
 6479:     if ($tmp!~/error: 2 /) {
 6480: 	&logthis("<font color=\"blue\">WARNING:".
 6481: 		 " Trying to get resource data for ".
 6482: 		 $uname." at ".$udom.": ".
 6483: 		 $tmp."</font>");
 6484:     } elsif ($tmp=~/error: 2 /) {
 6485: 	#&EXT_cache_set($udom,$uname);
 6486: 	&do_cache_new('userres',$hashid,undef,600);
 6487: 	undef($tmp); # not really an error so don't send it back
 6488:     }
 6489:     return $tmp;
 6490: }
 6491: #----------------------------------------------- resdata - return resource data
 6492: #  Purpose:
 6493: #    Return resource data for either users or for a course.
 6494: #  Parameters:
 6495: #     $name      - Course/user name.
 6496: #     $domain    - Name of the domain the user/course is registered on.
 6497: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6498: #     @which     - Array of names of resources desired.
 6499: #  Returns:
 6500: #     The value of the first reasource in @which that is found in the
 6501: #     resource hash.
 6502: #  Exceptional Conditions:
 6503: #     If the $type passed in is not valid (not the string 'course' or 
 6504: #     'user', an undefined  reference is returned.
 6505: #     If none of the resources are found, an undef is returned
 6506: sub resdata {
 6507:     my ($name,$domain,$type,@which)=@_;
 6508:     my $result;
 6509:     if ($type eq 'course') {
 6510: 	$result=&get_courseresdata($name,$domain);
 6511:     } elsif ($type eq 'user') {
 6512: 	$result=&get_userresdata($name,$domain);
 6513:     }
 6514:     if (!ref($result)) { return $result; }    
 6515:     foreach my $item (@which) {
 6516: 	if (defined($result->{$item->[0]})) {
 6517: 	    return [$result->{$item->[0]},$item->[1]];
 6518: 	}
 6519:     }
 6520:     return undef;
 6521: }
 6522: 
 6523: #
 6524: # EXT resource caching routines
 6525: #
 6526: 
 6527: sub clear_EXT_cache_status {
 6528:     &delenv('cache.EXT.');
 6529: }
 6530: 
 6531: sub EXT_cache_status {
 6532:     my ($target_domain,$target_user) = @_;
 6533:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6534:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6535:         # We know already the user has no data
 6536:         return 1;
 6537:     } else {
 6538:         return 0;
 6539:     }
 6540: }
 6541: 
 6542: sub EXT_cache_set {
 6543:     my ($target_domain,$target_user) = @_;
 6544:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6545:     #&appenv({$cachename => time});
 6546: }
 6547: 
 6548: # --------------------------------------------------------- Value of a Variable
 6549: sub EXT {
 6550: 
 6551:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6552:     unless ($varname) { return ''; }
 6553:     #get real user name/domain, courseid and symb
 6554:     my $courseid;
 6555:     my $publicuser;
 6556:     if ($symbparm) {
 6557: 	$symbparm=&get_symb_from_alias($symbparm);
 6558:     }
 6559:     if (!($uname && $udom)) {
 6560:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6561:       if (!$symbparm) {	$symbparm=$cursymb; }
 6562:     } else {
 6563: 	$courseid=$env{'request.course.id'};
 6564:     }
 6565:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6566:     my $rest;
 6567:     if (defined($therest[0])) {
 6568:        $rest=join('.',@therest);
 6569:     } else {
 6570:        $rest='';
 6571:     }
 6572: 
 6573:     my $qualifierrest=$qualifier;
 6574:     if ($rest) { $qualifierrest.='.'.$rest; }
 6575:     my $spacequalifierrest=$space;
 6576:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6577:     if ($realm eq 'user') {
 6578: # --------------------------------------------------------------- user.resource
 6579: 	if ($space eq 'resource') {
 6580: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6581: 		  || defined($Apache::lonhomework::parsing_a_task))
 6582: 		 &&
 6583: 		 ($symbparm eq &symbread()) ) {	
 6584: 		# if we are in the middle of processing the resource the
 6585: 		# get the value we are planning on committing
 6586:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6587:                     return $Apache::lonhomework::results{$qualifierrest};
 6588:                 } else {
 6589:                     return $Apache::lonhomework::history{$qualifierrest};
 6590:                 }
 6591: 	    } else {
 6592: 		my %restored;
 6593: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6594: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6595: 		} else {
 6596: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6597: 		}
 6598: 		return $restored{$qualifierrest};
 6599: 	    }
 6600: # ----------------------------------------------------------------- user.access
 6601:         } elsif ($space eq 'access') {
 6602: 	    # FIXME - not supporting calls for a specific user
 6603:             return &allowed($qualifier,$rest);
 6604: # ------------------------------------------ user.preferences, user.environment
 6605:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6606: 	    if (($uname eq $env{'user.name'}) &&
 6607: 		($udom eq $env{'user.domain'})) {
 6608: 		return $env{join('.',('environment',$qualifierrest))};
 6609: 	    } else {
 6610: 		my %returnhash;
 6611: 		if (!$publicuser) {
 6612: 		    %returnhash=&userenvironment($udom,$uname,
 6613: 						 $qualifierrest);
 6614: 		}
 6615: 		return $returnhash{$qualifierrest};
 6616: 	    }
 6617: # ----------------------------------------------------------------- user.course
 6618:         } elsif ($space eq 'course') {
 6619: 	    # FIXME - not supporting calls for a specific user
 6620:             return $env{join('.',('request.course',$qualifier))};
 6621: # ------------------------------------------------------------------- user.role
 6622:         } elsif ($space eq 'role') {
 6623: 	    # FIXME - not supporting calls for a specific user
 6624:             my ($role,$where)=split(/\./,$env{'request.role'});
 6625:             if ($qualifier eq 'value') {
 6626: 		return $role;
 6627:             } elsif ($qualifier eq 'extent') {
 6628:                 return $where;
 6629:             }
 6630: # ----------------------------------------------------------------- user.domain
 6631:         } elsif ($space eq 'domain') {
 6632:             return $udom;
 6633: # ------------------------------------------------------------------- user.name
 6634:         } elsif ($space eq 'name') {
 6635:             return $uname;
 6636: # ---------------------------------------------------- Any other user namespace
 6637:         } else {
 6638: 	    my %reply;
 6639: 	    if (!$publicuser) {
 6640: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6641: 	    }
 6642: 	    return $reply{$qualifierrest};
 6643:         }
 6644:     } elsif ($realm eq 'query') {
 6645: # ---------------------------------------------- pull stuff out of query string
 6646:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6647: 						[$spacequalifierrest]);
 6648: 	return $env{'form.'.$spacequalifierrest}; 
 6649:    } elsif ($realm eq 'request') {
 6650: # ------------------------------------------------------------- request.browser
 6651:         if ($space eq 'browser') {
 6652: 	    if ($qualifier eq 'textremote') {
 6653: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6654: 		    return 1;
 6655: 		} else {
 6656: 		    return 0;
 6657: 		}
 6658: 	    } else {
 6659: 		return $env{'browser.'.$qualifier};
 6660: 	    }
 6661: # ------------------------------------------------------------ request.filename
 6662:         } else {
 6663:             return $env{'request.'.$spacequalifierrest};
 6664:         }
 6665:     } elsif ($realm eq 'course') {
 6666: # ---------------------------------------------------------- course.description
 6667:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6668:     } elsif ($realm eq 'resource') {
 6669: 
 6670: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6671: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6672: 	}
 6673: 
 6674: 	if ($space eq 'title') {
 6675: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6676: 	    return &gettitle($symbparm);
 6677: 	}
 6678: 	
 6679: 	if ($space eq 'map') {
 6680: 	    my ($map) = &decode_symb($symbparm);
 6681: 	    return &symbread($map);
 6682: 	}
 6683: 	if ($space eq 'filename') {
 6684: 	    if ($symbparm) {
 6685: 		return &clutter((&decode_symb($symbparm))[2]);
 6686: 	    }
 6687: 	    return &hreflocation('',$env{'request.filename'});
 6688: 	}
 6689: 
 6690: 	my ($section, $group, @groups);
 6691: 	my ($courselevelm,$courselevel);
 6692: 	if ($symbparm && defined($courseid) && 
 6693: 	    $courseid eq $env{'request.course.id'}) {
 6694: 
 6695: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6696: 
 6697: # ----------------------------------------------------- Cascading lookup scheme
 6698: 	    my $symbp=$symbparm;
 6699: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6700: 
 6701: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6702: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6703: 
 6704: 	    if (($env{'user.name'} eq $uname) &&
 6705: 		($env{'user.domain'} eq $udom)) {
 6706: 		$section=$env{'request.course.sec'};
 6707:                 @groups = split(/:/,$env{'request.course.groups'});  
 6708:                 @groups=&sort_course_groups($courseid,@groups); 
 6709: 	    } else {
 6710: 		if (! defined($usection)) {
 6711: 		    $section=&getsection($udom,$uname,$courseid);
 6712: 		} else {
 6713: 		    $section = $usection;
 6714: 		}
 6715:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6716: 	    }
 6717: 
 6718: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6719: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6720: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6721: 
 6722: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6723: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6724: 	    $courselevelm=$courseid.'.'.$mapparm;
 6725: 
 6726: # ----------------------------------------------------------- first, check user
 6727: 
 6728: 	    my $userreply=&resdata($uname,$udom,'user',
 6729: 				       ([$courselevelr,'resource'],
 6730: 					[$courselevelm,'map'     ],
 6731: 					[$courselevel, 'course'  ]));
 6732: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6733: 
 6734: # ------------------------------------------------ second, check some of course
 6735:             my $coursereply;
 6736:             if (@groups > 0) {
 6737:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6738:                                        $mapparm,$spacequalifierrest);
 6739:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6740:             }
 6741: 
 6742: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6743: 				  $env{'course.'.$courseid.'.domain'},
 6744: 				  'course',
 6745: 				  ([$seclevelr,   'resource'],
 6746: 				   [$seclevelm,   'map'     ],
 6747: 				   [$seclevel,    'course'  ],
 6748: 				   [$courselevelr,'resource']));
 6749: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6750: 
 6751: # ------------------------------------------------------ third, check map parms
 6752: 	    my %parmhash=();
 6753: 	    my $thisparm='';
 6754: 	    if (tie(%parmhash,'GDBM_File',
 6755: 		    $env{'request.course.fn'}.'_parms.db',
 6756: 		    &GDBM_READER(),0640)) {
 6757: 		$thisparm=$parmhash{$symbparm};
 6758: 		untie(%parmhash);
 6759: 	    }
 6760: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6761: 	}
 6762: # ------------------------------------------ fourth, look in resource metadata
 6763: 
 6764: 	$spacequalifierrest=~s/\./\_/;
 6765: 	my $filename;
 6766: 	if (!$symbparm) { $symbparm=&symbread(); }
 6767: 	if ($symbparm) {
 6768: 	    $filename=(&decode_symb($symbparm))[2];
 6769: 	} else {
 6770: 	    $filename=$env{'request.filename'};
 6771: 	}
 6772: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6773: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6774: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6775: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6776: 
 6777: # ---------------------------------------------- fourth, look in rest of course
 6778: 	if ($symbparm && defined($courseid) && 
 6779: 	    $courseid eq $env{'request.course.id'}) {
 6780: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6781: 				     $env{'course.'.$courseid.'.domain'},
 6782: 				     'course',
 6783: 				     ([$courselevelm,'map'   ],
 6784: 				      [$courselevel, 'course']));
 6785: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6786: 	}
 6787: # ------------------------------------------------------------------ Cascade up
 6788: 	unless ($space eq '0') {
 6789: 	    my @parts=split(/_/,$space);
 6790: 	    my $id=pop(@parts);
 6791: 	    my $part=join('_',@parts);
 6792: 	    if ($part eq '') { $part='0'; }
 6793: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6794: 				 $symbparm,$udom,$uname,$section,1);
 6795: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6796: 	}
 6797: 	if ($recurse) { return undef; }
 6798: 	my $pack_def=&packages_tab_default($filename,$varname);
 6799: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6800: # ---------------------------------------------------- Any other user namespace
 6801:     } elsif ($realm eq 'environment') {
 6802: # ----------------------------------------------------------------- environment
 6803: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6804: 	    return $env{'environment.'.$spacequalifierrest};
 6805: 	} else {
 6806: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6807: 		return '';
 6808: 	    }
 6809: 	    my %returnhash=&userenvironment($udom,$uname,
 6810: 					    $spacequalifierrest);
 6811: 	    return $returnhash{$spacequalifierrest};
 6812: 	}
 6813:     } elsif ($realm eq 'system') {
 6814: # ----------------------------------------------------------------- system.time
 6815: 	if ($space eq 'time') {
 6816: 	    return time;
 6817:         }
 6818:     } elsif ($realm eq 'server') {
 6819: # ----------------------------------------------------------------- system.time
 6820: 	if ($space eq 'name') {
 6821: 	    return $ENV{'SERVER_NAME'};
 6822:         }
 6823:     }
 6824:     return '';
 6825: }
 6826: 
 6827: sub get_reply {
 6828:     my ($reply_value) = @_;
 6829:     if (ref($reply_value) eq 'ARRAY') {
 6830:         if (wantarray) {
 6831: 	    return @$reply_value;
 6832:         }
 6833:         return $reply_value->[0];
 6834:     } else {
 6835:         return $reply_value;
 6836:     }
 6837: }
 6838: 
 6839: sub check_group_parms {
 6840:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6841:     my @groupitems = ();
 6842:     my $resultitem;
 6843:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6844:     foreach my $group (@{$groups}) {
 6845:         foreach my $level (@levels) {
 6846:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6847:              push(@groupitems,[$item,$level->[1]]);
 6848:         }
 6849:     }
 6850:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6851:                             $env{'course.'.$courseid.'.domain'},
 6852:                                      'course',@groupitems);
 6853:     return $coursereply;
 6854: }
 6855: 
 6856: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6857:     my ($courseid,@groups) = @_;
 6858:     @groups = sort(@groups);
 6859:     return @groups;
 6860: }
 6861: 
 6862: sub packages_tab_default {
 6863:     my ($uri,$varname)=@_;
 6864:     my (undef,$part,$name)=split(/\./,$varname);
 6865: 
 6866:     my (@extension,@specifics,$do_default);
 6867:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6868: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6869: 	if ($pack_type eq 'default') {
 6870: 	    $do_default=1;
 6871: 	} elsif ($pack_type eq 'extension') {
 6872: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6873: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6874: 	    # only look at packages defaults for packages that this id is
 6875: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6876: 	}
 6877:     }
 6878:     # first look for a package that matches the requested part id
 6879:     foreach my $package (@specifics) {
 6880: 	my (undef,$pack_type,$pack_part)=@{$package};
 6881: 	next if ($pack_part ne $part);
 6882: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6883: 	    return $packagetab{"$pack_type&$name&default"};
 6884: 	}
 6885:     }
 6886:     # look for any possible matching non extension_ package
 6887:     foreach my $package (@specifics) {
 6888: 	my (undef,$pack_type,$pack_part)=@{$package};
 6889: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6890: 	    return $packagetab{"$pack_type&$name&default"};
 6891: 	}
 6892: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6893: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6894: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6895: 	}
 6896:     }
 6897:     # look for any posible extension_ match
 6898:     foreach my $package (@extension) {
 6899: 	my ($package,$pack_type)=@{$package};
 6900: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6901: 	    return $packagetab{"$pack_type&$name&default"};
 6902: 	}
 6903: 	if (defined($packagetab{$package."&$name&default"})) {
 6904: 	    return $packagetab{$package."&$name&default"};
 6905: 	}
 6906:     }
 6907:     # look for a global default setting
 6908:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6909: 	return $packagetab{"default&$name&default"};
 6910:     }
 6911:     return undef;
 6912: }
 6913: 
 6914: sub add_prefix_and_part {
 6915:     my ($prefix,$part)=@_;
 6916:     my $keyroot;
 6917:     if (defined($prefix) && $prefix !~ /^__/) {
 6918: 	# prefix that has a part already
 6919: 	$keyroot=$prefix;
 6920:     } elsif (defined($prefix)) {
 6921: 	# prefix that is missing a part
 6922: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6923:     } else {
 6924: 	# no prefix at all
 6925: 	if (defined($part)) { $keyroot='_'.$part; }
 6926:     }
 6927:     return $keyroot;
 6928: }
 6929: 
 6930: # ---------------------------------------------------------------- Get metadata
 6931: 
 6932: my %metaentry;
 6933: sub metadata {
 6934:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6935:     $uri=&declutter($uri);
 6936:     # if it is a non metadata possible uri return quickly
 6937:     if (($uri eq '') || 
 6938: 	(($uri =~ m|^/*adm/|) && 
 6939: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6940:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6941: 	return undef;
 6942:     }
 6943:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6944: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6945: 	return undef;
 6946:     }
 6947:     my $filename=$uri;
 6948:     $uri=~s/\.meta$//;
 6949: #
 6950: # Is the metadata already cached?
 6951: # Look at timestamp of caching
 6952: # Everything is cached by the main uri, libraries are never directly cached
 6953: #
 6954:     if (!defined($liburi)) {
 6955: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6956: 	if (defined($cached)) { return $result->{':'.$what}; }
 6957:     }
 6958:     {
 6959: #
 6960: # Is this a recursive call for a library?
 6961: #
 6962: #	if (! exists($metacache{$uri})) {
 6963: #	    $metacache{$uri}={};
 6964: #	}
 6965: 	my $cachetime = 60*60;
 6966:         if ($liburi) {
 6967: 	    $liburi=&declutter($liburi);
 6968:             $filename=$liburi;
 6969:         } else {
 6970: 	    &devalidate_cache_new('meta',$uri);
 6971: 	    undef(%metaentry);
 6972: 	}
 6973:         my %metathesekeys=();
 6974:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6975: 	my $metastring;
 6976: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6977: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6978: 	    $metastring = 
 6979: 		&Apache::lonnet::ssi_body($which,
 6980: 					  ('grade_target' => 'meta'));
 6981: 	    $cachetime = 1; # only want this cached in the child not long term
 6982: 	} elsif ($uri !~ m -^(editupload)/-) {
 6983: 	    my $file=&filelocation('',&clutter($filename));
 6984: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6985: 	    $metastring=&getfile($file);
 6986: 	}
 6987:         my $parser=HTML::LCParser->new(\$metastring);
 6988:         my $token;
 6989:         undef %metathesekeys;
 6990:         while ($token=$parser->get_token) {
 6991: 	    if ($token->[0] eq 'S') {
 6992: 		if (defined($token->[2]->{'package'})) {
 6993: #
 6994: # This is a package - get package info
 6995: #
 6996: 		    my $package=$token->[2]->{'package'};
 6997: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6998: 		    if (defined($token->[2]->{'id'})) { 
 6999: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7000: 		    }
 7001: 		    if ($metaentry{':packages'}) {
 7002: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7003: 		    } else {
 7004: 			$metaentry{':packages'}=$package.$keyroot;
 7005: 		    }
 7006: 		    foreach my $pack_entry (keys(%packagetab)) {
 7007: 			my $part=$keyroot;
 7008: 			$part=~s/^\_//;
 7009: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7010: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7011: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7012: 			    # ignore package.tab specified default values
 7013:                             # here &package_tab_default() will fetch those
 7014: 			    if ($subp eq 'default') { next; }
 7015: 			    my $value=$packagetab{$pack_entry};
 7016: 			    my $unikey;
 7017: 			    if ($pack =~ /_0$/) {
 7018: 				$unikey='parameter_0_'.$name;
 7019: 				$part=0;
 7020: 			    } else {
 7021: 				$unikey='parameter'.$keyroot.'_'.$name;
 7022: 			    }
 7023: 			    if ($subp eq 'display') {
 7024: 				$value.=' [Part: '.$part.']';
 7025: 			    }
 7026: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7027: 			    $metathesekeys{$unikey}=1;
 7028: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7029: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7030: 			    }
 7031: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7032: 				$metaentry{':'.$unikey}=
 7033: 				    $metaentry{':'.$unikey.'.default'};
 7034: 			    }
 7035: 			}
 7036: 		    }
 7037: 		} else {
 7038: #
 7039: # This is not a package - some other kind of start tag
 7040: #
 7041: 		    my $entry=$token->[1];
 7042: 		    my $unikey;
 7043: 		    if ($entry eq 'import') {
 7044: 			$unikey='';
 7045: 		    } else {
 7046: 			$unikey=$entry;
 7047: 		    }
 7048: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7049: 
 7050: 		    if (defined($token->[2]->{'id'})) { 
 7051: 			$unikey.='_'.$token->[2]->{'id'}; 
 7052: 		    }
 7053: 
 7054: 		    if ($entry eq 'import') {
 7055: #
 7056: # Importing a library here
 7057: #
 7058: 			if ($depthcount<20) {
 7059: 			    my $location=$parser->get_text('/import');
 7060: 			    my $dir=$filename;
 7061: 			    $dir=~s|[^/]*$||;
 7062: 			    $location=&filelocation($dir,$location);
 7063: 			    my $metadata = 
 7064: 				&metadata($uri,'keys', $location,$unikey,
 7065: 					  $depthcount+1);
 7066: 			    foreach my $meta (split(',',$metadata)) {
 7067: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7068: 				$metathesekeys{$meta}=1;
 7069: 			    }
 7070: 			}
 7071: 		    } else { 
 7072: 			
 7073: 			if (defined($token->[2]->{'name'})) { 
 7074: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7075: 			}
 7076: 			$metathesekeys{$unikey}=1;
 7077: 			foreach my $param (@{$token->[3]}) {
 7078: 			    $metaentry{':'.$unikey.'.'.$param} =
 7079: 				$token->[2]->{$param};
 7080: 			}
 7081: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7082: 			my $default=$metaentry{':'.$unikey.'.default'};
 7083: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7084: 		 # only ws inside the tag, and not in default, so use default
 7085: 		 # as value
 7086: 			    $metaentry{':'.$unikey}=$default;
 7087: 			} elsif ( $internaltext =~ /\S/ ) {
 7088: 		  # something interesting inside the tag
 7089: 			    $metaentry{':'.$unikey}=$internaltext;
 7090: 			} else {
 7091: 		  # no interesting values, don't set a default
 7092: 			}
 7093: # end of not-a-package not-a-library import
 7094: 		    }
 7095: # end of not-a-package start tag
 7096: 		}
 7097: # the next is the end of "start tag"
 7098: 	    }
 7099: 	}
 7100: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7101: 	$extension = lc($extension);
 7102: 	if ($extension eq 'htm') { $extension='html'; }
 7103: 
 7104: 	foreach my $key (keys(%packagetab)) {
 7105: 	    #no specific packages #how's our extension
 7106: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7107: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7108: 					 \%metathesekeys);
 7109: 	}
 7110: 
 7111: 	if (!exists($metaentry{':packages'})
 7112: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7113: 	    foreach my $key (keys(%packagetab)) {
 7114: 		#no specific packages well let's get default then
 7115: 		if ($key!~/^default&/) { next; }
 7116: 		&metadata_create_package_def($uri,$key,'default',
 7117: 					     \%metathesekeys);
 7118: 	    }
 7119: 	}
 7120: # are there custom rights to evaluate
 7121: 	if ($metaentry{':copyright'} eq 'custom') {
 7122: 
 7123:     #
 7124:     # Importing a rights file here
 7125:     #
 7126: 	    unless ($depthcount) {
 7127: 		my $location=$metaentry{':customdistributionfile'};
 7128: 		my $dir=$filename;
 7129: 		$dir=~s|[^/]*$||;
 7130: 		$location=&filelocation($dir,$location);
 7131: 		my $rights_metadata =
 7132: 		    &metadata($uri,'keys',$location,'_rights',
 7133: 			      $depthcount+1);
 7134: 		foreach my $rights (split(',',$rights_metadata)) {
 7135: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7136: 		    $metathesekeys{$rights}=1;
 7137: 		}
 7138: 	    }
 7139: 	}
 7140: 	# uniqifiy package listing
 7141: 	my %seen;
 7142: 	my @uniq_packages =
 7143: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7144: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7145: 
 7146: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7147: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7148: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7149: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7150: # this is the end of "was not already recently cached
 7151:     }
 7152:     return $metaentry{':'.$what};
 7153: }
 7154: 
 7155: sub metadata_create_package_def {
 7156:     my ($uri,$key,$package,$metathesekeys)=@_;
 7157:     my ($pack,$name,$subp)=split(/\&/,$key);
 7158:     if ($subp eq 'default') { next; }
 7159:     
 7160:     if (defined($metaentry{':packages'})) {
 7161: 	$metaentry{':packages'}.=','.$package;
 7162:     } else {
 7163: 	$metaentry{':packages'}=$package;
 7164:     }
 7165:     my $value=$packagetab{$key};
 7166:     my $unikey;
 7167:     $unikey='parameter_0_'.$name;
 7168:     $metaentry{':'.$unikey.'.part'}=0;
 7169:     $$metathesekeys{$unikey}=1;
 7170:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7171: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7172:     }
 7173:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7174: 	$metaentry{':'.$unikey}=
 7175: 	    $metaentry{':'.$unikey.'.default'};
 7176:     }
 7177: }
 7178: 
 7179: sub metadata_generate_part0 {
 7180:     my ($metadata,$metacache,$uri) = @_;
 7181:     my %allnames;
 7182:     foreach my $metakey (keys(%$metadata)) {
 7183: 	if ($metakey=~/^parameter\_(.*)/) {
 7184: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7185: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7186: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7187: 	    $allnames{$name}=$part;
 7188: 	  }
 7189: 	}
 7190:     }
 7191:     foreach my $name (keys(%allnames)) {
 7192:       $$metadata{"parameter_0_$name"}=1;
 7193:       my $key=":parameter_0_$name";
 7194:       $$metacache{"$key.part"}='0';
 7195:       $$metacache{"$key.name"}=$name;
 7196:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7197: 					   $allnames{$name}.'_'.$name.
 7198: 					   '.type'};
 7199:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7200: 			     '.display'};
 7201:       my $expr='[Part: '.$allnames{$name}.']';
 7202:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7203:       $$metacache{"$key.display"}=$olddis;
 7204:     }
 7205: }
 7206: 
 7207: # ------------------------------------------------------ Devalidate title cache
 7208: 
 7209: sub devalidate_title_cache {
 7210:     my ($url)=@_;
 7211:     if (!$env{'request.course.id'}) { return; }
 7212:     my $symb=&symbread($url);
 7213:     if (!$symb) { return; }
 7214:     my $key=$env{'request.course.id'}."\0".$symb;
 7215:     &devalidate_cache_new('title',$key);
 7216: }
 7217: 
 7218: # ------------------------------------------------- Get the title of a resource
 7219: 
 7220: sub gettitle {
 7221:     my $urlsymb=shift;
 7222:     my $symb=&symbread($urlsymb);
 7223:     if ($symb) {
 7224: 	my $key=$env{'request.course.id'}."\0".$symb;
 7225: 	my ($result,$cached)=&is_cached_new('title',$key);
 7226: 	if (defined($cached)) { 
 7227: 	    return $result;
 7228: 	}
 7229: 	my ($map,$resid,$url)=&decode_symb($symb);
 7230: 	my $title='';
 7231: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7232: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7233: 	} else {
 7234: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7235: 		    &GDBM_READER(),0640)) {
 7236: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7237: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7238: 		untie(%bighash);
 7239: 	    }
 7240: 	}
 7241: 	$title=~s/\&colon\;/\:/gs;
 7242: 	if ($title) {
 7243: 	    return &do_cache_new('title',$key,$title,600);
 7244: 	}
 7245: 	$urlsymb=$url;
 7246:     }
 7247:     my $title=&metadata($urlsymb,'title');
 7248:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7249:     return $title;
 7250: }
 7251: 
 7252: sub get_slot {
 7253:     my ($which,$cnum,$cdom)=@_;
 7254:     if (!$cnum || !$cdom) {
 7255: 	(undef,my $courseid)=&whichuser();
 7256: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7257: 	$cnum=$env{'course.'.$courseid.'.num'};
 7258:     }
 7259:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7260:     my %slotinfo;
 7261:     if (exists($remembered{$key})) {
 7262: 	$slotinfo{$which} = $remembered{$key};
 7263:     } else {
 7264: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7265: 	&Apache::lonhomework::showhash(%slotinfo);
 7266: 	my ($tmp)=keys(%slotinfo);
 7267: 	if ($tmp=~/^error:/) { return (); }
 7268: 	$remembered{$key} = $slotinfo{$which};
 7269:     }
 7270:     if (ref($slotinfo{$which}) eq 'HASH') {
 7271: 	return %{$slotinfo{$which}};
 7272:     }
 7273:     return $slotinfo{$which};
 7274: }
 7275: # ------------------------------------------------- Update symbolic store links
 7276: 
 7277: sub symblist {
 7278:     my ($mapname,%newhash)=@_;
 7279:     $mapname=&deversion(&declutter($mapname));
 7280:     my %hash;
 7281:     if (($env{'request.course.fn'}) && (%newhash)) {
 7282:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7283:                       &GDBM_WRCREAT(),0640)) {
 7284: 	    foreach my $url (keys %newhash) {
 7285: 		next if ($url eq 'last_known'
 7286: 			 && $env{'form.no_update_last_known'});
 7287: 		$hash{declutter($url)}=&encode_symb($mapname,
 7288: 						    $newhash{$url}->[1],
 7289: 						    $newhash{$url}->[0]);
 7290:             }
 7291:             if (untie(%hash)) {
 7292: 		return 'ok';
 7293:             }
 7294:         }
 7295:     }
 7296:     return 'error';
 7297: }
 7298: 
 7299: # --------------------------------------------------------------- Verify a symb
 7300: 
 7301: sub symbverify {
 7302:     my ($symb,$thisurl)=@_;
 7303:     my $thisfn=$thisurl;
 7304:     $thisfn=&declutter($thisfn);
 7305: # direct jump to resource in page or to a sequence - will construct own symbs
 7306:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7307: # check URL part
 7308:     my ($map,$resid,$url)=&decode_symb($symb);
 7309: 
 7310:     unless ($url eq $thisfn) { return 0; }
 7311: 
 7312:     $symb=&symbclean($symb);
 7313:     $thisurl=&deversion($thisurl);
 7314:     $thisfn=&deversion($thisfn);
 7315: 
 7316:     my %bighash;
 7317:     my $okay=0;
 7318: 
 7319:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7320:                             &GDBM_READER(),0640)) {
 7321:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7322:         unless ($ids) { 
 7323:            $ids=$bighash{'ids_/'.$thisurl};
 7324:         }
 7325:         if ($ids) {
 7326: # ------------------------------------------------------------------- Has ID(s)
 7327: 	    foreach my $id (split(/\,/,$ids)) {
 7328: 	       my ($mapid,$resid)=split(/\./,$id);
 7329:                if (
 7330:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7331:    eq $symb) { 
 7332: 		   if (($env{'request.role.adv'}) ||
 7333: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7334: 		       $okay=1; 
 7335: 		   }
 7336: 	       }
 7337: 	   }
 7338:         }
 7339: 	untie(%bighash);
 7340:     }
 7341:     return $okay;
 7342: }
 7343: 
 7344: # --------------------------------------------------------------- Clean-up symb
 7345: 
 7346: sub symbclean {
 7347:     my $symb=shift;
 7348:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7349: # remove version from map
 7350:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7351: 
 7352: # remove version from URL
 7353:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7354: 
 7355: # remove wrapper
 7356: 
 7357:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7358:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7359:     return $symb;
 7360: }
 7361: 
 7362: # ---------------------------------------------- Split symb to find map and url
 7363: 
 7364: sub encode_symb {
 7365:     my ($map,$resid,$url)=@_;
 7366:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7367: }
 7368: 
 7369: sub decode_symb {
 7370:     my $symb=shift;
 7371:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7372:     my ($map,$resid,$url)=split(/___/,$symb);
 7373:     return (&fixversion($map),$resid,&fixversion($url));
 7374: }
 7375: 
 7376: sub fixversion {
 7377:     my $fn=shift;
 7378:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7379:     my %bighash;
 7380:     my $uri=&clutter($fn);
 7381:     my $key=$env{'request.course.id'}.'_'.$uri;
 7382: # is this cached?
 7383:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7384:     if (defined($cached)) { return $result; }
 7385: # unfortunately not cached, or expired
 7386:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7387: 	    &GDBM_READER(),0640)) {
 7388:  	if ($bighash{'version_'.$uri}) {
 7389:  	    my $version=$bighash{'version_'.$uri};
 7390:  	    unless (($version eq 'mostrecent') || 
 7391: 		    ($version==&getversion($uri))) {
 7392:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7393:  	    }
 7394:  	}
 7395:  	untie %bighash;
 7396:     }
 7397:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7398: }
 7399: 
 7400: sub deversion {
 7401:     my $url=shift;
 7402:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7403:     return $url;
 7404: }
 7405: 
 7406: # ------------------------------------------------------ Return symb list entry
 7407: 
 7408: sub symbread {
 7409:     my ($thisfn,$donotrecurse)=@_;
 7410:     my $cache_str='request.symbread.cached.'.$thisfn;
 7411:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7412: # no filename provided? try from environment
 7413:     unless ($thisfn) {
 7414:         if ($env{'request.symb'}) {
 7415: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7416: 	}
 7417: 	$thisfn=$env{'request.filename'};
 7418:     }
 7419:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7420: # is that filename actually a symb? Verify, clean, and return
 7421:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7422: 	if (&symbverify($thisfn,$1)) {
 7423: 	    return $env{$cache_str}=&symbclean($thisfn);
 7424: 	}
 7425:     }
 7426:     $thisfn=declutter($thisfn);
 7427:     my %hash;
 7428:     my %bighash;
 7429:     my $syval='';
 7430:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7431:         my $targetfn = $thisfn;
 7432:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7433:             $targetfn = 'adm/wrapper/'.$thisfn;
 7434:         }
 7435: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7436: 	    $targetfn=$1;
 7437: 	}
 7438:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7439:                       &GDBM_READER(),0640)) {
 7440: 	    $syval=$hash{$targetfn};
 7441:             untie(%hash);
 7442:         }
 7443: # ---------------------------------------------------------- There was an entry
 7444:         if ($syval) {
 7445: 	    #unless ($syval=~/\_\d+$/) {
 7446: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7447: 		    #&appenv({'request.ambiguous' => $thisfn});
 7448: 		    #return $env{$cache_str}='';
 7449: 		#}    
 7450: 		#$syval.=$1;
 7451: 	    #}
 7452:         } else {
 7453: # ------------------------------------------------------- Was not in symb table
 7454:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7455:                             &GDBM_READER(),0640)) {
 7456: # ---------------------------------------------- Get ID(s) for current resource
 7457:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7458:               unless ($ids) { 
 7459:                  $ids=$bighash{'ids_/'.$thisfn};
 7460:               }
 7461:               unless ($ids) {
 7462: # alias?
 7463: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7464:               }
 7465:               if ($ids) {
 7466: # ------------------------------------------------------------------- Has ID(s)
 7467:                  my @possibilities=split(/\,/,$ids);
 7468:                  if ($#possibilities==0) {
 7469: # ----------------------------------------------- There is only one possibility
 7470: 		     my ($mapid,$resid)=split(/\./,$ids);
 7471: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7472: 						    $resid,$thisfn);
 7473:                  } elsif (!$donotrecurse) {
 7474: # ------------------------------------------ There is more than one possibility
 7475:                      my $realpossible=0;
 7476:                      foreach my $id (@possibilities) {
 7477: 			 my $file=$bighash{'src_'.$id};
 7478:                          if (&allowed('bre',$file)) {
 7479:          		    my ($mapid,$resid)=split(/\./,$id);
 7480:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7481: 				$realpossible++;
 7482:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7483: 						    $resid,$thisfn);
 7484:                             }
 7485: 			 }
 7486:                      }
 7487: 		     if ($realpossible!=1) { $syval=''; }
 7488:                  } else {
 7489:                      $syval='';
 7490:                  }
 7491: 	      }
 7492:               untie(%bighash)
 7493:            }
 7494:         }
 7495:         if ($syval) {
 7496: 	    return $env{$cache_str}=$syval;
 7497:         }
 7498:     }
 7499:     &appenv({'request.ambiguous' => $thisfn});
 7500:     return $env{$cache_str}='';
 7501: }
 7502: 
 7503: # ---------------------------------------------------------- Return random seed
 7504: 
 7505: sub numval {
 7506:     my $txt=shift;
 7507:     $txt=~tr/A-J/0-9/;
 7508:     $txt=~tr/a-j/0-9/;
 7509:     $txt=~tr/K-T/0-9/;
 7510:     $txt=~tr/k-t/0-9/;
 7511:     $txt=~tr/U-Z/0-5/;
 7512:     $txt=~tr/u-z/0-5/;
 7513:     $txt=~s/\D//g;
 7514:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7515:     return int($txt);
 7516: }
 7517: 
 7518: sub numval2 {
 7519:     my $txt=shift;
 7520:     $txt=~tr/A-J/0-9/;
 7521:     $txt=~tr/a-j/0-9/;
 7522:     $txt=~tr/K-T/0-9/;
 7523:     $txt=~tr/k-t/0-9/;
 7524:     $txt=~tr/U-Z/0-5/;
 7525:     $txt=~tr/u-z/0-5/;
 7526:     $txt=~s/\D//g;
 7527:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7528:     my $total;
 7529:     foreach my $val (@txts) { $total+=$val; }
 7530:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7531:     return int($total);
 7532: }
 7533: 
 7534: sub numval3 {
 7535:     use integer;
 7536:     my $txt=shift;
 7537:     $txt=~tr/A-J/0-9/;
 7538:     $txt=~tr/a-j/0-9/;
 7539:     $txt=~tr/K-T/0-9/;
 7540:     $txt=~tr/k-t/0-9/;
 7541:     $txt=~tr/U-Z/0-5/;
 7542:     $txt=~tr/u-z/0-5/;
 7543:     $txt=~s/\D//g;
 7544:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7545:     my $total;
 7546:     foreach my $val (@txts) { $total+=$val; }
 7547:     if ($_64bit) { $total=(($total<<32)>>32); }
 7548:     return $total;
 7549: }
 7550: 
 7551: sub digest {
 7552:     my ($data)=@_;
 7553:     my $digest=&Digest::MD5::md5($data);
 7554:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7555:     my ($e,$f);
 7556:     {
 7557:         use integer;
 7558:         $e=($a+$b);
 7559:         $f=($c+$d);
 7560:         if ($_64bit) {
 7561:             $e=(($e<<32)>>32);
 7562:             $f=(($f<<32)>>32);
 7563:         }
 7564:     }
 7565:     if (wantarray) {
 7566: 	return ($e,$f);
 7567:     } else {
 7568: 	my $g;
 7569: 	{
 7570: 	    use integer;
 7571: 	    $g=($e+$f);
 7572: 	    if ($_64bit) {
 7573: 		$g=(($g<<32)>>32);
 7574: 	    }
 7575: 	}
 7576: 	return $g;
 7577:     }
 7578: }
 7579: 
 7580: sub latest_rnd_algorithm_id {
 7581:     return '64bit5';
 7582: }
 7583: 
 7584: sub get_rand_alg {
 7585:     my ($courseid)=@_;
 7586:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7587:     if ($courseid) {
 7588: 	return $env{"course.$courseid.rndseed"};
 7589:     }
 7590:     return &latest_rnd_algorithm_id();
 7591: }
 7592: 
 7593: sub validCODE {
 7594:     my ($CODE)=@_;
 7595:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7596:     return 0;
 7597: }
 7598: 
 7599: sub getCODE {
 7600:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7601:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7602: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7603: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7604: 	return $Apache::lonhomework::history{'resource.CODE'};
 7605:     }
 7606:     return undef;
 7607: }
 7608: 
 7609: sub rndseed {
 7610:     my ($symb,$courseid,$domain,$username)=@_;
 7611:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7612:     if (!defined($symb)) {
 7613: 	unless ($symb=$wsymb) { return time; }
 7614:     }
 7615:     if (!$courseid) { $courseid=$wcourseid; }
 7616:     if (!$domain) { $domain=$wdomain; }
 7617:     if (!$username) { $username=$wusername }
 7618:     my $which=&get_rand_alg();
 7619: 
 7620:     if (defined(&getCODE())) {
 7621: 	if ($which eq '64bit5') {
 7622: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7623: 	} elsif ($which eq '64bit4') {
 7624: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7625: 	} else {
 7626: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7627: 	}
 7628:     } elsif ($which eq '64bit5') {
 7629: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7630:     } elsif ($which eq '64bit4') {
 7631: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7632:     } elsif ($which eq '64bit3') {
 7633: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7634:     } elsif ($which eq '64bit2') {
 7635: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7636:     } elsif ($which eq '64bit') {
 7637: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7638:     }
 7639:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7640: }
 7641: 
 7642: sub rndseed_32bit {
 7643:     my ($symb,$courseid,$domain,$username)=@_;
 7644:     {
 7645: 	use integer;
 7646: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7647: 	my $symbseed=numval($symb) << 22;
 7648: 	my $namechck=unpack("%32C*",$username) << 17;
 7649: 	my $nameseed=numval($username) << 12;
 7650: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7651: 	my $courseseed=unpack("%32C*",$courseid);
 7652: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7653: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7654: 	#&logthis("rndseed :$num:$symb");
 7655: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7656: 	return $num;
 7657:     }
 7658: }
 7659: 
 7660: sub rndseed_64bit {
 7661:     my ($symb,$courseid,$domain,$username)=@_;
 7662:     {
 7663: 	use integer;
 7664: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7665: 	my $symbseed=numval($symb) << 10;
 7666: 	my $namechck=unpack("%32S*",$username);
 7667: 	
 7668: 	my $nameseed=numval($username) << 21;
 7669: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7670: 	my $courseseed=unpack("%32S*",$courseid);
 7671: 	
 7672: 	my $num1=$symbchck+$symbseed+$namechck;
 7673: 	my $num2=$nameseed+$domainseed+$courseseed;
 7674: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7675: 	#&logthis("rndseed :$num:$symb");
 7676: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7677: 	return "$num1,$num2";
 7678:     }
 7679: }
 7680: 
 7681: sub rndseed_64bit2 {
 7682:     my ($symb,$courseid,$domain,$username)=@_;
 7683:     {
 7684: 	use integer;
 7685: 	# strings need to be an even # of cahracters long, it it is odd the
 7686:         # last characters gets thrown away
 7687: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7688: 	my $symbseed=numval($symb) << 10;
 7689: 	my $namechck=unpack("%32S*",$username.' ');
 7690: 	
 7691: 	my $nameseed=numval($username) << 21;
 7692: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7693: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7694: 	
 7695: 	my $num1=$symbchck+$symbseed+$namechck;
 7696: 	my $num2=$nameseed+$domainseed+$courseseed;
 7697: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7698: 	#&logthis("rndseed :$num:$symb");
 7699: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7700: 	return "$num1,$num2";
 7701:     }
 7702: }
 7703: 
 7704: sub rndseed_64bit3 {
 7705:     my ($symb,$courseid,$domain,$username)=@_;
 7706:     {
 7707: 	use integer;
 7708: 	# strings need to be an even # of cahracters long, it it is odd the
 7709:         # last characters gets thrown away
 7710: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7711: 	my $symbseed=numval2($symb) << 10;
 7712: 	my $namechck=unpack("%32S*",$username.' ');
 7713: 	
 7714: 	my $nameseed=numval2($username) << 21;
 7715: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7716: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7717: 	
 7718: 	my $num1=$symbchck+$symbseed+$namechck;
 7719: 	my $num2=$nameseed+$domainseed+$courseseed;
 7720: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7721: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7722: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7723: 	
 7724: 	return "$num1:$num2";
 7725:     }
 7726: }
 7727: 
 7728: sub rndseed_64bit4 {
 7729:     my ($symb,$courseid,$domain,$username)=@_;
 7730:     {
 7731: 	use integer;
 7732: 	# strings need to be an even # of cahracters long, it it is odd the
 7733:         # last characters gets thrown away
 7734: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7735: 	my $symbseed=numval3($symb) << 10;
 7736: 	my $namechck=unpack("%32S*",$username.' ');
 7737: 	
 7738: 	my $nameseed=numval3($username) << 21;
 7739: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7740: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7741: 	
 7742: 	my $num1=$symbchck+$symbseed+$namechck;
 7743: 	my $num2=$nameseed+$domainseed+$courseseed;
 7744: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7745: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7746: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7747: 	
 7748: 	return "$num1:$num2";
 7749:     }
 7750: }
 7751: 
 7752: sub rndseed_64bit5 {
 7753:     my ($symb,$courseid,$domain,$username)=@_;
 7754:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7755:     return "$num1:$num2";
 7756: }
 7757: 
 7758: sub rndseed_CODE_64bit {
 7759:     my ($symb,$courseid,$domain,$username)=@_;
 7760:     {
 7761: 	use integer;
 7762: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7763: 	my $symbseed=numval2($symb);
 7764: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7765: 	my $CODEseed=numval(&getCODE());
 7766: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7767: 	my $num1=$symbseed+$CODEchck;
 7768: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7769: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7770: 	#&logthis("rndseed :$num1:$num2:$symb");
 7771: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7772: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7773: 	return "$num1:$num2";
 7774:     }
 7775: }
 7776: 
 7777: sub rndseed_CODE_64bit4 {
 7778:     my ($symb,$courseid,$domain,$username)=@_;
 7779:     {
 7780: 	use integer;
 7781: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7782: 	my $symbseed=numval3($symb);
 7783: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7784: 	my $CODEseed=numval3(&getCODE());
 7785: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7786: 	my $num1=$symbseed+$CODEchck;
 7787: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7788: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7789: 	#&logthis("rndseed :$num1:$num2:$symb");
 7790: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7791: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7792: 	return "$num1:$num2";
 7793:     }
 7794: }
 7795: 
 7796: sub rndseed_CODE_64bit5 {
 7797:     my ($symb,$courseid,$domain,$username)=@_;
 7798:     my $code = &getCODE();
 7799:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7800:     return "$num1:$num2";
 7801: }
 7802: 
 7803: sub setup_random_from_rndseed {
 7804:     my ($rndseed)=@_;
 7805:     if ($rndseed =~/([,:])/) {
 7806: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7807: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7808:     } else {
 7809: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7810:     }
 7811: }
 7812: 
 7813: sub latest_receipt_algorithm_id {
 7814:     return 'receipt3';
 7815: }
 7816: 
 7817: sub recunique {
 7818:     my $fucourseid=shift;
 7819:     my $unique;
 7820:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7821: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7822: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7823:     } else {
 7824: 	$unique=$perlvar{'lonReceipt'};
 7825:     }
 7826:     return unpack("%32C*",$unique);
 7827: }
 7828: 
 7829: sub recprefix {
 7830:     my $fucourseid=shift;
 7831:     my $prefix;
 7832:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7833: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7834: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7835:     } else {
 7836: 	$prefix=$perlvar{'lonHostID'};
 7837:     }
 7838:     return unpack("%32C*",$prefix);
 7839: }
 7840: 
 7841: sub ireceipt {
 7842:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7843: 
 7844:     my $return =&recprefix($fucourseid).'-';
 7845: 
 7846:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7847: 	$env{'request.state'} eq 'construct') {
 7848: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7849: 	return $return;
 7850:     }
 7851: 
 7852:     my $cuname=unpack("%32C*",$funame);
 7853:     my $cudom=unpack("%32C*",$fudom);
 7854:     my $cucourseid=unpack("%32C*",$fucourseid);
 7855:     my $cusymb=unpack("%32C*",$fusymb);
 7856:     my $cunique=&recunique($fucourseid);
 7857:     my $cpart=unpack("%32S*",$part);
 7858:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7859: 
 7860: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7861: 			       
 7862: 	$return.= ($cunique%$cuname+
 7863: 		   $cunique%$cudom+
 7864: 		   $cusymb%$cuname+
 7865: 		   $cusymb%$cudom+
 7866: 		   $cucourseid%$cuname+
 7867: 		   $cucourseid%$cudom+
 7868: 		   $cpart%$cuname+
 7869: 		   $cpart%$cudom);
 7870:     } else {
 7871: 	$return.= ($cunique%$cuname+
 7872: 		   $cunique%$cudom+
 7873: 		   $cusymb%$cuname+
 7874: 		   $cusymb%$cudom+
 7875: 		   $cucourseid%$cuname+
 7876: 		   $cucourseid%$cudom);
 7877:     }
 7878:     return $return;
 7879: }
 7880: 
 7881: sub receipt {
 7882:     my ($part)=@_;
 7883:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7884:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7885: }
 7886: 
 7887: sub whichuser {
 7888:     my ($passedsymb)=@_;
 7889:     my ($symb,$courseid,$domain,$name,$publicuser);
 7890:     if (defined($env{'form.grade_symb'})) {
 7891: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7892: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7893: 	if (!$allowed &&
 7894: 	    exists($env{'request.course.sec'}) &&
 7895: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7896: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7897: 			      '/'.$env{'request.course.sec'});
 7898: 	}
 7899: 	if ($allowed) {
 7900: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7901: 	    $courseid=$tmp_courseid;
 7902: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7903: 	    ($name)=&get_env_multiple('form.grade_username');
 7904: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7905: 	}
 7906:     }
 7907:     if (!$passedsymb) {
 7908: 	$symb=&symbread();
 7909:     } else {
 7910: 	$symb=$passedsymb;
 7911:     }
 7912:     $courseid=$env{'request.course.id'};
 7913:     $domain=$env{'user.domain'};
 7914:     $name=$env{'user.name'};
 7915:     if ($name eq 'public' && $domain eq 'public') {
 7916: 	if (!defined($env{'form.username'})) {
 7917: 	    $env{'form.username'}.=time.rand(10000000);
 7918: 	}
 7919: 	$name.=$env{'form.username'};
 7920:     }
 7921:     return ($symb,$courseid,$domain,$name,$publicuser);
 7922: 
 7923: }
 7924: 
 7925: # ------------------------------------------------------------ Serves up a file
 7926: # returns either the contents of the file or 
 7927: # -1 if the file doesn't exist
 7928: #
 7929: # if the target is a file that was uploaded via DOCS, 
 7930: # a check will be made to see if a current copy exists on the local server,
 7931: # if it does this will be served, otherwise a copy will be retrieved from
 7932: # the home server for the course and stored in /home/httpd/html/userfiles on
 7933: # the local server.   
 7934: 
 7935: sub getfile {
 7936:     my ($file) = @_;
 7937:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7938:     &repcopy($file);
 7939:     return &readfile($file);
 7940: }
 7941: 
 7942: sub repcopy_userfile {
 7943:     my ($file)=@_;
 7944:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7945:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7946:     my ($cdom,$cnum,$filename) = 
 7947: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7948:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7949:     if (-e "$file") {
 7950: # we already have a local copy, check it out
 7951: 	my @fileinfo = stat($file);
 7952: 	my $rtncode;
 7953: 	my $info;
 7954: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7955: 	if ($lwpresp ne 'ok') {
 7956: # there is no such file anymore, even though we had a local copy
 7957: 	    if ($rtncode eq '404') {
 7958: 		unlink($file);
 7959: 	    }
 7960: 	    return -1;
 7961: 	}
 7962: 	if ($info < $fileinfo[9]) {
 7963: # nice, the file we have is up-to-date, just say okay
 7964: 	    return 'ok';
 7965: 	} else {
 7966: # the file is outdated, get rid of it
 7967: 	    unlink($file);
 7968: 	}
 7969:     }
 7970: # one way or the other, at this point, we don't have the file
 7971: # construct the correct path for the file
 7972:     my @parts = ($cdom,$cnum); 
 7973:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7974: 	push @parts, split(/\//,$1);
 7975:     }
 7976:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7977:     foreach my $part (@parts) {
 7978: 	$path .= '/'.$part;
 7979: 	if (!-e $path) {
 7980: 	    mkdir($path,0770);
 7981: 	}
 7982:     }
 7983: # now the path exists for sure
 7984: # get a user agent
 7985:     my $ua=new LWP::UserAgent;
 7986:     my $transferfile=$file.'.in.transfer';
 7987: # FIXME: this should flock
 7988:     if (-e $transferfile) { return 'ok'; }
 7989:     my $request;
 7990:     $uri=~s/^\///;
 7991:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7992:     my $response=$ua->request($request,$transferfile);
 7993: # did it work?
 7994:     if ($response->is_error()) {
 7995: 	unlink($transferfile);
 7996: 	&logthis("Userfile repcopy failed for $uri");
 7997: 	return -1;
 7998:     }
 7999: # worked, rename the transfer file
 8000:     rename($transferfile,$file);
 8001:     return 'ok';
 8002: }
 8003: 
 8004: sub tokenwrapper {
 8005:     my $uri=shift;
 8006:     $uri=~s|^http\://([^/]+)||;
 8007:     $uri=~s|^/||;
 8008:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8009:     my $token=$1;
 8010:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8011:     if ($udom && $uname && $file) {
 8012: 	$file=~s|(\?\.*)*$||;
 8013:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8014:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 8015:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8016:                                '&tokenissued='.$perlvar{'lonHostID'};
 8017:     } else {
 8018:         return '/adm/notfound.html';
 8019:     }
 8020: }
 8021: 
 8022: # call with reqtype HEAD: get last modification time
 8023: # call with reqtype GET: get the file contents
 8024: # Do not call this with reqtype GET for large files! It loads everything into memory
 8025: #
 8026: sub getuploaded {
 8027:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8028:     $uri=~s/^\///;
 8029:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8030:     my $ua=new LWP::UserAgent;
 8031:     my $request=new HTTP::Request($reqtype,$uri);
 8032:     my $response=$ua->request($request);
 8033:     $$rtncode = $response->code;
 8034:     if (! $response->is_success()) {
 8035: 	return 'failed';
 8036:     }      
 8037:     if ($reqtype eq 'HEAD') {
 8038: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8039:     } elsif ($reqtype eq 'GET') {
 8040: 	$$info = $response->content;
 8041:     }
 8042:     return 'ok';
 8043: }
 8044: 
 8045: sub readfile {
 8046:     my $file = shift;
 8047:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8048:     my $fh;
 8049:     open($fh,"<$file");
 8050:     my $a='';
 8051:     while (my $line = <$fh>) { $a .= $line; }
 8052:     return $a;
 8053: }
 8054: 
 8055: sub filelocation {
 8056:     my ($dir,$file) = @_;
 8057:     my $location;
 8058:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8059: 
 8060:     if ($file =~ m-^/adm/-) {
 8061: 	$file=~s-^/adm/wrapper/-/-;
 8062: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8063:     }
 8064: 
 8065:     if ($file=~m:^/~:) { # is a contruction space reference
 8066:         $location = $file;
 8067:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8068:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8069: 	# is a correct contruction space reference
 8070:         $location = $file;
 8071:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8072:         my ($udom,$uname,$filename)=
 8073:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8074:         my $home=&homeserver($uname,$udom);
 8075:         my $is_me=0;
 8076:         my @ids=&current_machine_ids();
 8077:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8078:         if ($is_me) {
 8079:   	    $location=&propath($udom,$uname).
 8080:   	      '/userfiles/'.$filename;
 8081:         } else {
 8082:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8083:   	      $udom.'/'.$uname.'/'.$filename;
 8084:         }
 8085:     } elsif ($file =~ m-^/adm/-) {
 8086: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8087:     } else {
 8088:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8089:         $file=~s:^/res/:/:;
 8090:         if ( !( $file =~ m:^/:) ) {
 8091:             $location = $dir. '/'.$file;
 8092:         } else {
 8093:             $location = '/home/httpd/html/res'.$file;
 8094:         }
 8095:     }
 8096:     $location=~s://+:/:g; # remove duplicate /
 8097:     while ($location=~m{/\.\./}) {
 8098: 	if ($location =~ m{/[^/]+/\.\./}) {
 8099: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8100: 	} else {
 8101: 	    $location=~ s{/\.\./}{/}g;
 8102: 	}
 8103:     } #remove dir/..
 8104:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8105:     return $location;
 8106: }
 8107: 
 8108: sub hreflocation {
 8109:     my ($dir,$file)=@_;
 8110:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8111: 	$file=filelocation($dir,$file);
 8112:     } elsif ($file=~m-^/adm/-) {
 8113: 	$file=~s-^/adm/wrapper/-/-;
 8114: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8115:     }
 8116:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8117: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8118:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8119: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8120:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8121: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8122: 	    -/uploaded/$1/$2/-x;
 8123:     }
 8124:     if ($file=~ m{^/userfiles/}) {
 8125: 	$file =~ s{^/userfiles/}{/uploaded/};
 8126:     }
 8127:     return $file;
 8128: }
 8129: 
 8130: sub current_machine_domains {
 8131:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8132: }
 8133: 
 8134: sub machine_domains {
 8135:     my ($hostname) = @_;
 8136:     my @domains;
 8137:     my %hostname = &all_hostnames();
 8138:     while( my($id, $name) = each(%hostname)) {
 8139: #	&logthis("-$id-$name-$hostname-");
 8140: 	if ($hostname eq $name) {
 8141: 	    push(@domains,&host_domain($id));
 8142: 	}
 8143:     }
 8144:     return @domains;
 8145: }
 8146: 
 8147: sub current_machine_ids {
 8148:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8149: }
 8150: 
 8151: sub machine_ids {
 8152:     my ($hostname) = @_;
 8153:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8154:     my @ids;
 8155:     my %name_to_host = &all_names();
 8156:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8157: 	return @{ $name_to_host{$hostname} };
 8158:     }
 8159:     return;
 8160: }
 8161: 
 8162: sub additional_machine_domains {
 8163:     my @domains;
 8164:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8165:     while( my $line = <$fh>) {
 8166:         $line =~ s/\s//g;
 8167:         push(@domains,$line);
 8168:     }
 8169:     return @domains;
 8170: }
 8171: 
 8172: sub default_login_domain {
 8173:     my $domain = $perlvar{'lonDefDomain'};
 8174:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8175:     foreach my $posdom (&current_machine_domains(),
 8176:                         &additional_machine_domains()) {
 8177:         if (lc($posdom) eq lc($testdomain)) {
 8178:             $domain=$posdom;
 8179:             last;
 8180:         }
 8181:     }
 8182:     return $domain;
 8183: }
 8184: 
 8185: # ------------------------------------------------------------- Declutters URLs
 8186: 
 8187: sub declutter {
 8188:     my $thisfn=shift;
 8189:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8190:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8191:     $thisfn=~s/^\///;
 8192:     $thisfn=~s|^adm/wrapper/||;
 8193:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8194:     $thisfn=~s/^res\///;
 8195:     $thisfn=~s/\?.+$//;
 8196:     return $thisfn;
 8197: }
 8198: 
 8199: # ------------------------------------------------------------- Clutter up URLs
 8200: 
 8201: sub clutter {
 8202:     my $thisfn='/'.&declutter(shift);
 8203:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8204: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8205:        $thisfn='/res'.$thisfn; 
 8206:     }
 8207:     if ($thisfn !~m|/adm|) {
 8208: 	if ($thisfn =~ m|/ext/|) {
 8209: 	    $thisfn='/adm/wrapper'.$thisfn;
 8210: 	} else {
 8211: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8212: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8213: 	    if ($embstyle eq 'ssi'
 8214: 		|| ($embstyle eq 'hdn')
 8215: 		|| ($embstyle eq 'rat')
 8216: 		|| ($embstyle eq 'prv')
 8217: 		|| ($embstyle eq 'ign')) {
 8218: 		#do nothing with these
 8219: 	    } elsif (($embstyle eq 'img') 
 8220: 		|| ($embstyle eq 'emb')
 8221: 		|| ($embstyle eq 'wrp')) {
 8222: 		$thisfn='/adm/wrapper'.$thisfn;
 8223: 	    } elsif ($embstyle eq 'unk'
 8224: 		     && $thisfn!~/\.(sequence|page)$/) {
 8225: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8226: 	    } else {
 8227: #		&logthis("Got a blank emb style");
 8228: 	    }
 8229: 	}
 8230:     }
 8231:     return $thisfn;
 8232: }
 8233: 
 8234: sub clutter_with_no_wrapper {
 8235:     my $uri = &clutter(shift);
 8236:     if ($uri =~ m-^/adm/-) {
 8237: 	$uri =~ s-^/adm/wrapper/-/-;
 8238: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8239:     }
 8240:     return $uri;
 8241: }
 8242: 
 8243: sub freeze_escape {
 8244:     my ($value)=@_;
 8245:     if (ref($value)) {
 8246: 	$value=&nfreeze($value);
 8247: 	return '__FROZEN__'.&escape($value);
 8248:     }
 8249:     return &escape($value);
 8250: }
 8251: 
 8252: 
 8253: sub thaw_unescape {
 8254:     my ($value)=@_;
 8255:     if ($value =~ /^__FROZEN__/) {
 8256: 	substr($value,0,10,undef);
 8257: 	$value=&unescape($value);
 8258: 	return &thaw($value);
 8259:     }
 8260:     return &unescape($value);
 8261: }
 8262: 
 8263: sub correct_line_ends {
 8264:     my ($result)=@_;
 8265:     $$result =~s/\r\n/\n/mg;
 8266:     $$result =~s/\r/\n/mg;
 8267: }
 8268: # ================================================================ Main Program
 8269: 
 8270: sub goodbye {
 8271:    &logthis("Starting Shut down");
 8272: #not converted to using infrastruture and probably shouldn't be
 8273:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8274: #converted
 8275: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8276:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8277: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8278: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8279: #1.1 only
 8280: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8281: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8282: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8283: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8284:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8285:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8286:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8287:    &flushcourselogs();
 8288:    &logthis("Shutting down");
 8289: }
 8290: 
 8291: sub get_dns {
 8292:     my ($url,$func,$ignore_cache) = @_;
 8293:     if (!$ignore_cache) {
 8294: 	my ($content,$cached)=
 8295: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8296: 	if ($cached) {
 8297: 	    &$func($content);
 8298: 	    return;
 8299: 	}
 8300:     }
 8301: 
 8302:     my %alldns;
 8303:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8304:     foreach my $dns (<$config>) {
 8305: 	next if ($dns !~ /^\^(\S*)/x);
 8306: 	$alldns{$1} = 1;
 8307:     }
 8308:     while (%alldns) {
 8309: 	my ($dns) = keys(%alldns);
 8310: 	delete($alldns{$dns});
 8311: 	my $ua=new LWP::UserAgent;
 8312: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8313: 	my $response=$ua->request($request);
 8314: 	next if ($response->is_error());
 8315: 	my @content = split("\n",$response->content);
 8316: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8317: 	&$func(\@content);
 8318: 	return;
 8319:     }
 8320:     close($config);
 8321:     my $which = (split('/',$url))[3];
 8322:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8323:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8324:     my @content = <$config>;
 8325:     &$func(\@content);
 8326:     return;
 8327: }
 8328: # ------------------------------------------------------------ Read domain file
 8329: {
 8330:     my $loaded;
 8331:     my %domain;
 8332: 
 8333:     sub parse_domain_tab {
 8334: 	my ($lines) = @_;
 8335: 	foreach my $line (@$lines) {
 8336: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8337: 
 8338: 	    chomp($line);
 8339: 	    my ($name,@elements) = split(/:/,$line,9);
 8340: 	    my %this_domain;
 8341: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8342: 			       'lang_def', 'city', 'longi', 'lati',
 8343: 			       'primary') {
 8344: 		$this_domain{$field} = shift(@elements);
 8345: 	    }
 8346: 	    $domain{$name} = \%this_domain;
 8347: 	}
 8348:     }
 8349: 
 8350:     sub reset_domain_info {
 8351: 	undef($loaded);
 8352: 	undef(%domain);
 8353:     }
 8354: 
 8355:     sub load_domain_tab {
 8356: 	my ($ignore_cache) = @_;
 8357: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8358: 	my $fh;
 8359: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8360: 	    my @lines = <$fh>;
 8361: 	    &parse_domain_tab(\@lines);
 8362: 	}
 8363: 	close($fh);
 8364: 	$loaded = 1;
 8365:     }
 8366: 
 8367:     sub domain {
 8368: 	&load_domain_tab() if (!$loaded);
 8369: 
 8370: 	my ($name,$what) = @_;
 8371: 	return if ( !exists($domain{$name}) );
 8372: 
 8373: 	if (!$what) {
 8374: 	    return $domain{$name}{'description'};
 8375: 	}
 8376: 	return $domain{$name}{$what};
 8377:     }
 8378: }
 8379: 
 8380: 
 8381: # ------------------------------------------------------------- Read hosts file
 8382: {
 8383:     my %hostname;
 8384:     my %hostdom;
 8385:     my %libserv;
 8386:     my $loaded;
 8387:     my %name_to_host;
 8388: 
 8389:     sub parse_hosts_tab {
 8390: 	my ($file) = @_;
 8391: 	foreach my $configline (@$file) {
 8392: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8393: 	    next if ($configline =~ /^\^/);
 8394: 	    chomp($configline);
 8395: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8396: 	    $name=~s/\s//g;
 8397: 	    if ($id && $domain && $role && $name) {
 8398: 		$hostname{$id}=$name;
 8399: 		push(@{$name_to_host{$name}}, $id);
 8400: 		$hostdom{$id}=$domain;
 8401: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8402: 	    }
 8403: 	}
 8404:     }
 8405:     
 8406:     sub reset_hosts_info {
 8407: 	&purge_remembered();
 8408: 	&reset_domain_info();
 8409: 	&reset_hosts_ip_info();
 8410: 	undef(%name_to_host);
 8411: 	undef(%hostname);
 8412: 	undef(%hostdom);
 8413: 	undef(%libserv);
 8414: 	undef($loaded);
 8415:     }
 8416: 
 8417:     sub load_hosts_tab {
 8418: 	my ($ignore_cache) = @_;
 8419: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8420: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8421: 	my @config = <$config>;
 8422: 	&parse_hosts_tab(\@config);
 8423: 	close($config);
 8424: 	$loaded=1;
 8425:     }
 8426: 
 8427:     sub hostname {
 8428: 	&load_hosts_tab() if (!$loaded);
 8429: 
 8430: 	my ($lonid) = @_;
 8431: 	return $hostname{$lonid};
 8432:     }
 8433: 
 8434:     sub all_hostnames {
 8435: 	&load_hosts_tab() if (!$loaded);
 8436: 
 8437: 	return %hostname;
 8438:     }
 8439: 
 8440:     sub all_names {
 8441: 	&load_hosts_tab() if (!$loaded);
 8442: 
 8443: 	return %name_to_host;
 8444:     }
 8445: 
 8446:     sub is_library {
 8447: 	&load_hosts_tab() if (!$loaded);
 8448: 
 8449: 	return exists($libserv{$_[0]});
 8450:     }
 8451: 
 8452:     sub all_library {
 8453: 	&load_hosts_tab() if (!$loaded);
 8454: 
 8455: 	return %libserv;
 8456:     }
 8457: 
 8458:     sub get_servers {
 8459: 	&load_hosts_tab() if (!$loaded);
 8460: 
 8461: 	my ($domain,$type) = @_;
 8462: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8463: 	                                          : %hostname;
 8464: 	my %result;
 8465: 	if (ref($domain) eq 'ARRAY') {
 8466: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8467: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8468: 		    $result{$host} = $hostname;
 8469: 		}
 8470: 	    }
 8471: 	} else {
 8472: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8473: 		if ($hostdom{$host} eq $domain) {
 8474: 		    $result{$host} = $hostname;
 8475: 		}
 8476: 	    }
 8477: 	}
 8478: 	return %result;
 8479:     }
 8480: 
 8481:     sub host_domain {
 8482: 	&load_hosts_tab() if (!$loaded);
 8483: 
 8484: 	my ($lonid) = @_;
 8485: 	return $hostdom{$lonid};
 8486:     }
 8487: 
 8488:     sub all_domains {
 8489: 	&load_hosts_tab() if (!$loaded);
 8490: 
 8491: 	my %seen;
 8492: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8493: 	return @uniq;
 8494:     }
 8495: }
 8496: 
 8497: { 
 8498:     my %iphost;
 8499:     my %name_to_ip;
 8500:     my %lonid_to_ip;
 8501: 
 8502:     sub get_hosts_from_ip {
 8503: 	my ($ip) = @_;
 8504: 	my %iphosts = &get_iphost();
 8505: 	if (ref($iphosts{$ip})) {
 8506: 	    return @{$iphosts{$ip}};
 8507: 	}
 8508: 	return;
 8509:     }
 8510:     
 8511:     sub reset_hosts_ip_info {
 8512: 	undef(%iphost);
 8513: 	undef(%name_to_ip);
 8514: 	undef(%lonid_to_ip);
 8515:     }
 8516: 
 8517:     sub get_host_ip {
 8518: 	my ($lonid) = @_;
 8519: 	if (exists($lonid_to_ip{$lonid})) {
 8520: 	    return $lonid_to_ip{$lonid};
 8521: 	}
 8522: 	my $name=&hostname($lonid);
 8523:    	my $ip = gethostbyname($name);
 8524: 	return if (!$ip || length($ip) ne 4);
 8525: 	$ip=inet_ntoa($ip);
 8526: 	$name_to_ip{$name}   = $ip;
 8527: 	$lonid_to_ip{$lonid} = $ip;
 8528: 	return $ip;
 8529:     }
 8530:     
 8531:     sub get_iphost {
 8532: 	my ($ignore_cache) = @_;
 8533: 
 8534: 	if (!$ignore_cache) {
 8535: 	    if (%iphost) {
 8536: 		return %iphost;
 8537: 	    }
 8538: 	    my ($ip_info,$cached)=
 8539: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8540: 	    if ($cached) {
 8541: 		%iphost      = %{$ip_info->[0]};
 8542: 		%name_to_ip  = %{$ip_info->[1]};
 8543: 		%lonid_to_ip = %{$ip_info->[2]};
 8544: 		return %iphost;
 8545: 	    }
 8546: 	}
 8547: 
 8548: 	# get yesterday's info for fallback
 8549: 	my %old_name_to_ip;
 8550: 	my ($ip_info,$cached)=
 8551: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8552: 	if ($cached) {
 8553: 	    %old_name_to_ip = %{$ip_info->[1]};
 8554: 	}
 8555: 
 8556: 	my %name_to_host = &all_names();
 8557: 	foreach my $name (keys(%name_to_host)) {
 8558: 	    my $ip;
 8559: 	    if (!exists($name_to_ip{$name})) {
 8560: 		$ip = gethostbyname($name);
 8561: 		if (!$ip || length($ip) ne 4) {
 8562: 		    if (defined($old_name_to_ip{$name})) {
 8563: 			$ip = $old_name_to_ip{$name};
 8564: 			&logthis("Can't find $name defaulting to old $ip");
 8565: 		    } else {
 8566: 			&logthis("Name $name no IP found");
 8567: 			next;
 8568: 		    }
 8569: 		} else {
 8570: 		    $ip=inet_ntoa($ip);
 8571: 		}
 8572: 		$name_to_ip{$name} = $ip;
 8573: 	    } else {
 8574: 		$ip = $name_to_ip{$name};
 8575: 	    }
 8576: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8577: 		$lonid_to_ip{$id} = $ip;
 8578: 	    }
 8579: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8580: 	}
 8581: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8582: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8583: 				      48*60*60);
 8584: 
 8585: 	return %iphost;
 8586:     }
 8587: }
 8588: 
 8589: BEGIN {
 8590: 
 8591: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8592:     unless ($readit) {
 8593: {
 8594:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8595:     %perlvar = (%perlvar,%{$configvars});
 8596: }
 8597: 
 8598: 
 8599: # ------------------------------------------------------ Read spare server file
 8600: {
 8601:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8602: 
 8603:     while (my $configline=<$config>) {
 8604:        chomp($configline);
 8605:        if ($configline) {
 8606: 	   my ($host,$type) = split(':',$configline,2);
 8607: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8608: 	   push(@{ $spareid{$type} }, $host);
 8609:        }
 8610:     }
 8611:     close($config);
 8612: }
 8613: # ------------------------------------------------------------ Read permissions
 8614: {
 8615:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8616: 
 8617:     while (my $configline=<$config>) {
 8618: 	chomp($configline);
 8619: 	if ($configline) {
 8620: 	    my ($role,$perm)=split(/ /,$configline);
 8621: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8622: 	}
 8623:     }
 8624:     close($config);
 8625: }
 8626: 
 8627: # -------------------------------------------- Read plain texts for permissions
 8628: {
 8629:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8630: 
 8631:     while (my $configline=<$config>) {
 8632: 	chomp($configline);
 8633: 	if ($configline) {
 8634: 	    my ($short,@plain)=split(/:/,$configline);
 8635:             %{$prp{$short}} = ();
 8636: 	    if (@plain > 0) {
 8637:                 $prp{$short}{'std'} = $plain[0];
 8638:                 for (my $i=1; $i<@plain; $i++) {
 8639:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8640:                 }
 8641:             }
 8642: 	}
 8643:     }
 8644:     close($config);
 8645: }
 8646: 
 8647: # ---------------------------------------------------------- Read package table
 8648: {
 8649:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8650: 
 8651:     while (my $configline=<$config>) {
 8652: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8653: 	chomp($configline);
 8654: 	my ($short,$plain)=split(/:/,$configline);
 8655: 	my ($pack,$name)=split(/\&/,$short);
 8656: 	if ($plain ne '') {
 8657: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8658: 	    $packagetab{$short}=$plain; 
 8659: 	}
 8660:     }
 8661:     close($config);
 8662: }
 8663: 
 8664: # ------------- set up temporary directory
 8665: {
 8666:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8667: 
 8668: }
 8669: 
 8670: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8671: 				'compress_threshold'=> 20_000,
 8672:  			        });
 8673: 
 8674: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8675: $dumpcount=0;
 8676: 
 8677: &logtouch();
 8678: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8679: $readit=1;
 8680:     {
 8681: 	use integer;
 8682: 	my $test=(2**32)+1;
 8683: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8684: 	&logthis(" Detected 64bit platform ($_64bit)");
 8685:     }
 8686: }
 8687: }
 8688: 
 8689: 1;
 8690: __END__
 8691: 
 8692: =pod
 8693: 
 8694: =head1 NAME
 8695: 
 8696: Apache::lonnet - Subroutines to ask questions about things in the network.
 8697: 
 8698: =head1 SYNOPSIS
 8699: 
 8700: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8701: 
 8702:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8703: 
 8704: Common parameters:
 8705: 
 8706: =over 4
 8707: 
 8708: =item *
 8709: 
 8710: $uname : an internal username (if $cname expecting a course Id specifically)
 8711: 
 8712: =item *
 8713: 
 8714: $udom : a domain (if $cdom expecting a course's domain specifically)
 8715: 
 8716: =item *
 8717: 
 8718: $symb : a resource instance identifier
 8719: 
 8720: =item *
 8721: 
 8722: $namespace : the name of a .db file that contains the data needed or
 8723: being set.
 8724: 
 8725: =back
 8726: 
 8727: =head1 OVERVIEW
 8728: 
 8729: lonnet provides subroutines which interact with the
 8730: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8731: about classes, users, and resources.
 8732: 
 8733: For many of these objects you can also use this to store data about
 8734: them or modify them in various ways.
 8735: 
 8736: =head2 Symbs
 8737: 
 8738: To identify a specific instance of a resource, LON-CAPA uses symbols
 8739: or "symbs"X<symb>. These identifiers are built from the URL of the
 8740: map, the resource number of the resource in the map, and the URL of
 8741: the resource itself. The latter is somewhat redundant, but might help
 8742: if maps change.
 8743: 
 8744: An example is
 8745: 
 8746:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8747: 
 8748: The respective map entry is
 8749: 
 8750:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8751:   title="Problem 2">
 8752:  </resource>
 8753: 
 8754: Symbs are used by the random number generator, as well as to store and
 8755: restore data specific to a certain instance of for example a problem.
 8756: 
 8757: =head2 Storing And Retrieving Data
 8758: 
 8759: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8760: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8761: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8762: is is the non-critical message twin of cstore. These functions are for
 8763: handlers to store a perl hash to a user's permanent data space in an
 8764: easy manner, and to retrieve it again on another call. It is expected
 8765: that a handler would use this once at the beginning to retrieve data,
 8766: and then again once at the end to send only the new data back.
 8767: 
 8768: The data is stored in the user's data directory on the user's
 8769: homeserver under the ID of the course.
 8770: 
 8771: The hash that is returned by restore will have all of the previous
 8772: value for all of the elements of the hash.
 8773: 
 8774: Example:
 8775: 
 8776:  #creating a hash
 8777:  my %hash;
 8778:  $hash{'foo'}='bar';
 8779: 
 8780:  #storing it
 8781:  &Apache::lonnet::cstore(\%hash);
 8782: 
 8783:  #changing a value
 8784:  $hash{'foo'}='notbar';
 8785: 
 8786:  #adding a new value
 8787:  $hash{'bar'}='foo';
 8788:  &Apache::lonnet::cstore(\%hash);
 8789: 
 8790:  #retrieving the hash
 8791:  my %history=&Apache::lonnet::restore();
 8792: 
 8793:  #print the hash
 8794:  foreach my $key (sort(keys(%history))) {
 8795:    print("\%history{$key} = $history{$key}");
 8796:  }
 8797: 
 8798: Will print out:
 8799: 
 8800:  %history{1:foo} = bar
 8801:  %history{1:keys} = foo:timestamp
 8802:  %history{1:timestamp} = 990455579
 8803:  %history{2:bar} = foo
 8804:  %history{2:foo} = notbar
 8805:  %history{2:keys} = foo:bar:timestamp
 8806:  %history{2:timestamp} = 990455580
 8807:  %history{bar} = foo
 8808:  %history{foo} = notbar
 8809:  %history{timestamp} = 990455580
 8810:  %history{version} = 2
 8811: 
 8812: Note that the special hash entries C<keys>, C<version> and
 8813: C<timestamp> were added to the hash. C<version> will be equal to the
 8814: total number of versions of the data that have been stored. The
 8815: C<timestamp> attribute will be the UNIX time the hash was
 8816: stored. C<keys> is available in every historical section to list which
 8817: keys were added or changed at a specific historical revision of a
 8818: hash.
 8819: 
 8820: B<Warning>: do not store the hash that restore returns directly. This
 8821: will cause a mess since it will restore the historical keys as if the
 8822: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8823: 
 8824: Calling convention:
 8825: 
 8826:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8827:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8828: 
 8829: For more detailed information, see lonnet specific documentation.
 8830: 
 8831: =head1 RETURN MESSAGES
 8832: 
 8833: =over 4
 8834: 
 8835: =item * B<con_lost>: unable to contact remote host
 8836: 
 8837: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8838: when the connection is brought back up
 8839: 
 8840: =item * B<con_failed>: unable to contact remote host and unable to save message
 8841: for later delivery
 8842: 
 8843: =item * B<error:>: an error a occured, a description of the error follows the :
 8844: 
 8845: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8846: that was requested
 8847: 
 8848: =back
 8849: 
 8850: =head1 PUBLIC SUBROUTINES
 8851: 
 8852: =head2 Session Environment Functions
 8853: 
 8854: =over 4
 8855: 
 8856: =item * 
 8857: X<appenv()>
 8858: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 8859: the user envirnoment file, and will be restored for each access this
 8860: user makes during this session, also modifies the %env for the current
 8861: process. Optional rolesarrayref - if defined contains a reference to an array
 8862: of roles which are exempt from the restriction on modifying user.role entries 
 8863: in the user's environment.db and in %env.    
 8864: 
 8865: =item *
 8866: X<delenv()>
 8867: B<delenv($regexp)>: removes all items from the session
 8868: environment file that matches the regular expression in $regexp. The
 8869: values are also delted from the current processes %env.
 8870: 
 8871: =item * get_env_multiple($name) 
 8872: 
 8873: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8874: values may be defined and end up as an array ref.
 8875: 
 8876: returns an array of values
 8877: 
 8878: =back
 8879: 
 8880: =head2 User Information
 8881: 
 8882: =over 4
 8883: 
 8884: =item *
 8885: X<queryauthenticate()>
 8886: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8887: authentication scheme
 8888: 
 8889: =item *
 8890: X<authenticate()>
 8891: B<authenticate($uname,$upass,$udom)>: try to
 8892: authenticate user from domain's lib servers (first use the current
 8893: one). C<$upass> should be the users password.
 8894: 
 8895: =item *
 8896: X<homeserver()>
 8897: B<homeserver($uname,$udom)>: find the server which has
 8898: the user's directory and files (there must be only one), this caches
 8899: the answer, and also caches if there is a borken connection.
 8900: 
 8901: =item *
 8902: X<idget()>
 8903: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8904: (IDs are a unique resource in a domain, there must be only 1 ID per
 8905: username, and only 1 username per ID in a specific domain) (returns
 8906: hash: id=>name,id=>name)
 8907: 
 8908: =item *
 8909: X<idrget()>
 8910: B<idrget($udom,@unames)>: find the IDs behind a list of
 8911: usernames (returns hash: name=>id,name=>id)
 8912: 
 8913: =item *
 8914: X<idput()>
 8915: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8916: 
 8917: =item *
 8918: X<rolesinit()>
 8919: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8920: 
 8921: =item *
 8922: X<getsection()>
 8923: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8924: course $cname, return section name/number or '' for "not in course"
 8925: and '-1' for "no section"
 8926: 
 8927: =item *
 8928: X<userenvironment()>
 8929: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8930: passed in @what from the requested user's environment, returns a hash
 8931: 
 8932: =item * 
 8933: X<userlog_query()>
 8934: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8935: activity.log file. %filters defines filters applied when parsing the
 8936: log file. These can be start or end timestamps, or the type of action
 8937: - log to look for Login or Logout events, check for Checkin or
 8938: Checkout, role for role selection. The response is in the form
 8939: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8940: escaped strings of the action recorded in the activity.log file.
 8941: 
 8942: =back
 8943: 
 8944: =head2 User Roles
 8945: 
 8946: =over 4
 8947: 
 8948: =item *
 8949: 
 8950: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8951:  F: full access
 8952:  U,I,K: authentication modes (cxx only)
 8953:  '': forbidden
 8954:  1: user needs to choose course
 8955:  2: browse allowed
 8956:  A: passphrase authentication needed
 8957: 
 8958: =item *
 8959: 
 8960: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8961: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8962: and course level
 8963: 
 8964: =item *
 8965: 
 8966: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8967: explanation of a user role term
 8968: 
 8969: =item *
 8970: 
 8971: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8972: All arguments are optional. Returns a hash of a roles, either for
 8973: co-author/assistant author roles for a user's Construction Space
 8974: (default), or if $context is 'userroles', roles for the user himself,
 8975: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8976: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8977: For each key, value is set to colon-separated start and end times for
 8978: the role.  If no username and domain are specified, will default to
 8979: current user/domain. Types, roles, and roledoms are references to arrays
 8980: of role statuses (active, future or previous), roles 
 8981: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8982: to restrict the list of roles reported. If no array ref is 
 8983: provided for types, will default to return only active roles.
 8984: 
 8985: =back
 8986: 
 8987: =head2 User Modification
 8988: 
 8989: =over 4
 8990: 
 8991: =item *
 8992: 
 8993: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8994: user for the level given by URL.  Optional start and end dates (leave empty
 8995: string or zero for "no date")
 8996: 
 8997: =item *
 8998: 
 8999: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9000: change a users, password, possible return values are: ok,
 9001: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9002: refused
 9003: 
 9004: =item *
 9005: 
 9006: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9007: 
 9008: =item *
 9009: 
 9010: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 9011: modify user
 9012: 
 9013: =item *
 9014: 
 9015: modifystudent
 9016: 
 9017: modify a students enrollment and identification information.
 9018: The course id is resolved based on the current users environment.  
 9019: This means the envoking user must be a course coordinator or otherwise
 9020: associated with a course.
 9021: 
 9022: This call is essentially a wrapper for lonnet::modifyuser and
 9023: lonnet::modify_student_enrollment
 9024: 
 9025: Inputs: 
 9026: 
 9027: =over 4
 9028: 
 9029: =item B<$udom> Students loncapa domain
 9030: 
 9031: =item B<$uname> Students loncapa login name
 9032: 
 9033: =item B<$uid> Students id/student number
 9034: 
 9035: =item B<$umode> Students authentication mode
 9036: 
 9037: =item B<$upass> Students password
 9038: 
 9039: =item B<$first> Students first name
 9040: 
 9041: =item B<$middle> Students middle name
 9042: 
 9043: =item B<$last> Students last name
 9044: 
 9045: =item B<$gene> Students generation
 9046: 
 9047: =item B<$usec> Students section in course
 9048: 
 9049: =item B<$end> Unix time of the roles expiration
 9050: 
 9051: =item B<$start> Unix time of the roles start date
 9052: 
 9053: =item B<$forceid> If defined, allow $uid to be changed
 9054: 
 9055: =item B<$desiredhome> server to use as home server for student
 9056: 
 9057: =back
 9058: 
 9059: =item *
 9060: 
 9061: modify_student_enrollment
 9062: 
 9063: Change a students enrollment status in a class.  The environment variable
 9064: 'role.request.course' must be defined for this function to proceed.
 9065: 
 9066: Inputs:
 9067: 
 9068: =over 4
 9069: 
 9070: =item $udom, students domain
 9071: 
 9072: =item $uname, students name
 9073: 
 9074: =item $uid, students user id
 9075: 
 9076: =item $first, students first name
 9077: 
 9078: =item $middle
 9079: 
 9080: =item $last
 9081: 
 9082: =item $gene
 9083: 
 9084: =item $usec
 9085: 
 9086: =item $end
 9087: 
 9088: =item $start
 9089: 
 9090: =back
 9091: 
 9092: 
 9093: =item *
 9094: 
 9095: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9096: custom role; give a custom role to a user for the level given by URL.  Specify
 9097: name and domain of role author, and role name
 9098: 
 9099: =item *
 9100: 
 9101: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9102: 
 9103: =item *
 9104: 
 9105: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9106: 
 9107: =back
 9108: 
 9109: =head2 Course Infomation
 9110: 
 9111: =over 4
 9112: 
 9113: =item *
 9114: 
 9115: coursedescription($courseid) : returns a hash of information about the
 9116: specified course id, including all environment settings for the
 9117: course, the description of the course will be in the hash under the
 9118: key 'description'
 9119: 
 9120: =item *
 9121: 
 9122: resdata($name,$domain,$type,@which) : request for current parameter
 9123: setting for a specific $type, where $type is either 'course' or 'user',
 9124: @what should be a list of parameters to ask about. This routine caches
 9125: answers for 5 minutes.
 9126: 
 9127: =item *
 9128: 
 9129: get_courseresdata($courseid, $domain) : dump the entire course resource
 9130: data base, returning a hash that is keyed by the resource name and has
 9131: values that are the resource value.  I believe that the timestamps and
 9132: versions are also returned.
 9133: 
 9134: 
 9135: =back
 9136: 
 9137: =head2 Course Modification
 9138: 
 9139: =over 4
 9140: 
 9141: =item *
 9142: 
 9143: writecoursepref($courseid,%prefs) : write preferences (environment
 9144: database) for a course
 9145: 
 9146: =item *
 9147: 
 9148: createcourse($udom,$description,$url) : make/modify course
 9149: 
 9150: =back
 9151: 
 9152: =head2 Resource Subroutines
 9153: 
 9154: =over 4
 9155: 
 9156: =item *
 9157: 
 9158: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9159: 
 9160: =item *
 9161: 
 9162: repcopy($filename) : subscribes to the requested file, and attempts to
 9163: replicate from the owning library server, Might return
 9164: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9165: 'bad_request', also attempts to grab the metadata for the
 9166: resource. Expects the local filesystem pathname
 9167: (/home/httpd/html/res/....)
 9168: 
 9169: =back
 9170: 
 9171: =head2 Resource Information
 9172: 
 9173: =over 4
 9174: 
 9175: =item *
 9176: 
 9177: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9178: a vairety of different possible values, $varname should be a request
 9179: string, and the other parameters can be used to specify who and what
 9180: one is asking about.
 9181: 
 9182: Possible values for $varname are environment.lastname (or other item
 9183: from the envirnment hash), user.name (or someother aspect about the
 9184: user), resource.0.maxtries (or some other part and parameter of a
 9185: resource)
 9186: 
 9187: =item *
 9188: 
 9189: directcondval($number) : get current value of a condition; reads from a state
 9190: string
 9191: 
 9192: =item *
 9193: 
 9194: condval($condidx) : value of condition index based on state
 9195: 
 9196: =item *
 9197: 
 9198: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9199: resource's metadata, $what should be either a specific key, or either
 9200: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9201: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9202: 
 9203: this function automatically caches all requests
 9204: 
 9205: =item *
 9206: 
 9207: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9208: network of library servers; returns file handle of where SQL and regex results
 9209: will be stored for query
 9210: 
 9211: =item *
 9212: 
 9213: symbread($filename) : return symbolic list entry (filename argument optional);
 9214: returns the data handle
 9215: 
 9216: =item *
 9217: 
 9218: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9219: a possible symb for the URL in $thisfn, and if is an encryypted
 9220: resource that the user accessed using /enc/ returns a 1 on success, 0
 9221: on failure, user must be in a course, as it assumes the existance of
 9222: the course initial hash, and uses $env('request.course.id'}
 9223: 
 9224: 
 9225: =item *
 9226: 
 9227: symbclean($symb) : removes versions numbers from a symb, returns the
 9228: cleaned symb
 9229: 
 9230: =item *
 9231: 
 9232: is_on_map($uri) : checks if the $uri is somewhere on the current
 9233: course map, user must be in a course for it to work.
 9234: 
 9235: =item *
 9236: 
 9237: numval($salt) : return random seed value (addend for rndseed)
 9238: 
 9239: =item *
 9240: 
 9241: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9242: a random seed, all arguments are optional, if they aren't sent it uses the
 9243: environment to derive them. Note: if symb isn't sent and it can't get one
 9244: from &symbread it will use the current time as its return value
 9245: 
 9246: =item *
 9247: 
 9248: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9249: unfakeable, receipt
 9250: 
 9251: =item *
 9252: 
 9253: receipt() : API to ireceipt working off of env values; given out to users
 9254: 
 9255: =item *
 9256: 
 9257: countacc($url) : count the number of accesses to a given URL
 9258: 
 9259: =item *
 9260: 
 9261: 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
 9262: 
 9263: =item *
 9264: 
 9265: 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)
 9266: 
 9267: =item *
 9268: 
 9269: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9270: 
 9271: =item *
 9272: 
 9273: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9274: forcing spreadsheet to reevaluate the resource scores next time.
 9275: 
 9276: =back
 9277: 
 9278: =head2 Storing/Retreiving Data
 9279: 
 9280: =over 4
 9281: 
 9282: =item *
 9283: 
 9284: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9285: for this url; hashref needs to be given and should be a \%hashname; the
 9286: remaining args aren't required and if they aren't passed or are '' they will
 9287: be derived from the env
 9288: 
 9289: =item *
 9290: 
 9291: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9292: uses critical subroutine
 9293: 
 9294: =item *
 9295: 
 9296: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9297: all args are optional
 9298: 
 9299: =item *
 9300: 
 9301: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9302: dumps the complete (or key matching regexp) namespace into a hash
 9303: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9304: normally &store()ed into
 9305: 
 9306: $range should be either an integer '100' (give me the first 100
 9307:                                            matching records)
 9308:               or be  two integers sperated by a - with no spaces
 9309:                  '30-50' (give me the 30th through the 50th matching
 9310:                           records)
 9311: 
 9312: 
 9313: =item *
 9314: 
 9315: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9316: replaces a &store() version of data with a replacement set of data
 9317: for a particular resource in a namespace passed in the $storehash hash 
 9318: reference
 9319: 
 9320: =item *
 9321: 
 9322: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9323: works very similar to store/cstore, but all data is stored in a
 9324: temporary location and can be reset using tmpreset, $storehash should
 9325: be a hash reference, returns nothing on success
 9326: 
 9327: =item *
 9328: 
 9329: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9330: similar to restore, but all data is stored in a temporary location and
 9331: can be reset using tmpreset. Returns a hash of values on success,
 9332: error string otherwise.
 9333: 
 9334: =item *
 9335: 
 9336: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9337: deltes all keys for $symb form the temporary storage hash.
 9338: 
 9339: =item *
 9340: 
 9341: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9342: reference filled in from namesp ($udom and $uname are optional)
 9343: 
 9344: =item *
 9345: 
 9346: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9347: namesp ($udom and $uname are optional)
 9348: 
 9349: =item *
 9350: 
 9351: dump($namespace,$udom,$uname,$regexp,$range) : 
 9352: dumps the complete (or key matching regexp) namespace into a hash
 9353: ($udom, $uname, $regexp, $range are optional)
 9354: 
 9355: $range should be either an integer '100' (give me the first 100
 9356:                                            matching records)
 9357:               or be  two integers sperated by a - with no spaces
 9358:                  '30-50' (give me the 30th through the 50th matching
 9359:                           records)
 9360: =item *
 9361: 
 9362: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9363: $store can be a scalar, an array reference, or if the amount to be 
 9364: incremented is > 1, a hash reference.
 9365: 
 9366: ($udom and $uname are optional)
 9367: 
 9368: =item *
 9369: 
 9370: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9371: ($udom and $uname are optional)
 9372: 
 9373: =item *
 9374: 
 9375: cput($namespace,$storehash,$udom,$uname) : critical put
 9376: ($udom and $uname are optional)
 9377: 
 9378: =item *
 9379: 
 9380: newput($namespace,$storehash,$udom,$uname) :
 9381: 
 9382: Attempts to store the items in the $storehash, but only if they don't
 9383: currently exist, if this succeeds you can be certain that you have 
 9384: successfully created a new key value pair in the $namespace db.
 9385: 
 9386: 
 9387: Args:
 9388:  $namespace: name of database to store values to
 9389:  $storehash: hashref to store to the db
 9390:  $udom: (optional) domain of user containing the db
 9391:  $uname: (optional) name of user caontaining the db
 9392: 
 9393: Returns:
 9394:  'ok' -> succeeded in storing all keys of $storehash
 9395:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9396:                         least <key> already existed in the db (other
 9397:                         requested keys may also already exist)
 9398:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9399:  'con_lost' -> unable to contact request server
 9400:  'refused' -> action was not allowed by remote machine
 9401: 
 9402: 
 9403: =item *
 9404: 
 9405: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9406: reference filled in from namesp (encrypts the return communication)
 9407: ($udom and $uname are optional)
 9408: 
 9409: =item *
 9410: 
 9411: log($udom,$name,$home,$message) : write to permanent log for user; use
 9412: critical subroutine
 9413: 
 9414: =item *
 9415: 
 9416: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9417: array reference filled in from namespace found in domain level on either
 9418: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9419: 
 9420: =item *
 9421: 
 9422: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9423: domain level either on specified domain server ($uhome) or primary domain 
 9424: server ($udom and $uhome are optional)
 9425: 
 9426: =item * 
 9427: 
 9428: get_domain_defaults($target_domain) : returns hash with defaults for
 9429: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9430: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9431: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9432: Values are retrieved from cache (if current), or from domain's configuration.db
 9433: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9434: or lonTabs/domain.tab. 
 9435: 
 9436: %domdefaults = &get_auth_defaults($target_domain);
 9437: 
 9438: =back
 9439: 
 9440: =head2 Network Status Functions
 9441: 
 9442: =over 4
 9443: 
 9444: =item *
 9445: 
 9446: dirlist($uri) : return directory list based on URI
 9447: 
 9448: =item *
 9449: 
 9450: spareserver() : find server with least workload from spare.tab
 9451: 
 9452: =back
 9453: 
 9454: =head2 Apache Request
 9455: 
 9456: =over 4
 9457: 
 9458: =item *
 9459: 
 9460: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9461: localhost, posts hash
 9462: 
 9463: =back
 9464: 
 9465: =head2 Data to String to Data
 9466: 
 9467: =over 4
 9468: 
 9469: =item *
 9470: 
 9471: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9472: and '&' separators, supports elements that are arrayrefs and hashrefs
 9473: 
 9474: =item *
 9475: 
 9476: hashref2str($hashref) : convert a hashref into a string complete with
 9477: escaping and '=' and '&' separators, supports elements that are
 9478: arrayrefs and hashrefs
 9479: 
 9480: =item *
 9481: 
 9482: arrayref2str($arrayref) : convert an arrayref into a string complete
 9483: with escaping and '&' separators, supports elements that are arrayrefs
 9484: and hashrefs
 9485: 
 9486: =item *
 9487: 
 9488: str2hash($string) : convert string to hash using unescaping and
 9489: splitting on '=' and '&', supports elements that are arrayrefs and
 9490: hashrefs
 9491: 
 9492: =item *
 9493: 
 9494: str2array($string) : convert string to hash using unescaping and
 9495: splitting on '&', supports elements that are arrayrefs and hashrefs
 9496: 
 9497: =back
 9498: 
 9499: =head2 Logging Routines
 9500: 
 9501: =over 4
 9502: 
 9503: These routines allow one to make log messages in the lonnet.log and
 9504: lonnet.perm logfiles.
 9505: 
 9506: =item *
 9507: 
 9508: logtouch() : make sure the logfile, lonnet.log, exists
 9509: 
 9510: =item *
 9511: 
 9512: logthis() : append message to the normal lonnet.log file, it gets
 9513: preiodically rolled over and deleted.
 9514: 
 9515: =item *
 9516: 
 9517: logperm() : append a permanent message to lonnet.perm.log, this log
 9518: file never gets deleted by any automated portion of the system, only
 9519: messages of critical importance should go in here.
 9520: 
 9521: =back
 9522: 
 9523: =head2 General File Helper Routines
 9524: 
 9525: =over 4
 9526: 
 9527: =item *
 9528: 
 9529: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9530: (a) files in /uploaded
 9531:   (i) If a local copy of the file exists - 
 9532:       compares modification date of local copy with last-modified date for 
 9533:       definitive version stored on home server for course. If local copy is 
 9534:       stale, requests a new version from the home server and stores it. 
 9535:       If the original has been removed from the home server, then local copy 
 9536:       is unlinked.
 9537:   (ii) If local copy does not exist -
 9538:       requests the file from the home server and stores it. 
 9539:   
 9540:   If $caller is 'uploadrep':  
 9541:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9542:     for request for files originally uploaded via DOCS. 
 9543:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9544:   
 9545:   Otherwise:
 9546:      This indicates a call from the content generation phase of the request.
 9547:      -  returns the entire contents of the file or -1.
 9548:      
 9549: (b) files in /res
 9550:    - returns the entire contents of a file or -1; 
 9551:    it properly subscribes to and replicates the file if neccessary.
 9552: 
 9553: 
 9554: =item *
 9555: 
 9556: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9557:                   reference
 9558: 
 9559: returns either a stat() list of data about the file or an empty list
 9560: if the file doesn't exist or couldn't find out about it (connection
 9561: problems or user unknown)
 9562: 
 9563: =item *
 9564: 
 9565: filelocation($dir,$file) : returns file system location of a file
 9566: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9567: directory that relative $file lookups are to looked in ($dir of /a/dir
 9568: and a file of ../bob will become /a/bob)
 9569: 
 9570: =item *
 9571: 
 9572: hreflocation($dir,$file) : returns file system location or a URL; same as
 9573: filelocation except for hrefs
 9574: 
 9575: =item *
 9576: 
 9577: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9578: 
 9579: =back
 9580: 
 9581: =head2 Usererfile file routines (/uploaded*)
 9582: 
 9583: =over 4
 9584: 
 9585: =item *
 9586: 
 9587: userfileupload(): main rotine for putting a file in a user or course's
 9588:                   filespace, arguments are,
 9589: 
 9590:  formname - required - this is the name of the element in $env where the
 9591:            filename, and the contents of the file to create/modifed exist
 9592:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9593:            contents of the file is located in $env{'form.'.$formname}
 9594:  coursedoc - if true, store the file in the course of the active role
 9595:              of the current user
 9596:  subdir - required - subdirectory to put the file in under ../userfiles/
 9597:          if undefined, it will be placed in "unknown"
 9598: 
 9599:  (This routine calls clean_filename() to remove any dangerous
 9600:  characters from the filename, and then calls finuserfileupload() to
 9601:  complete the transaction)
 9602: 
 9603:  returns either the url of the uploaded file (/uploaded/....) if successful
 9604:  and /adm/notfound.html if unsuccessful
 9605: 
 9606: =item *
 9607: 
 9608: clean_filename(): routine for cleaing a filename up for storage in
 9609:                  userfile space, argument is:
 9610: 
 9611:  filename - proposed filename
 9612: 
 9613: returns: the new clean filename
 9614: 
 9615: =item *
 9616: 
 9617: finishuserfileupload(): routine that creaes and sends the file to
 9618: userspace, probably shouldn't be called directly
 9619: 
 9620:   docuname: username or courseid of destination for the file
 9621:   docudom: domain of user/course of destination for the file
 9622:   formname: same as for userfileupload()
 9623:   fname: filename (inculding subdirectories) for the file
 9624: 
 9625:  returns either the url of the uploaded file (/uploaded/....) if successful
 9626:  and /adm/notfound.html if unsuccessful
 9627: 
 9628: =item *
 9629: 
 9630: renameuserfile(): renames an existing userfile to a new name
 9631: 
 9632:   Args:
 9633:    docuname: username or courseid of destination for the file
 9634:    docudom: domain of user/course of destination for the file
 9635:    old: current file name (including any subdirs under userfiles)
 9636:    new: desired file name (including any subdirs under userfiles)
 9637: 
 9638: =item *
 9639: 
 9640: mkdiruserfile(): creates a directory is a userfiles dir
 9641: 
 9642:   Args:
 9643:    docuname: username or courseid of destination for the file
 9644:    docudom: domain of user/course of destination for the file
 9645:    dir: dir to create (including any subdirs under userfiles)
 9646: 
 9647: =item *
 9648: 
 9649: removeuserfile(): removes a file that exists in userfiles
 9650: 
 9651:   Args:
 9652:    docuname: username or courseid of destination for the file
 9653:    docudom: domain of user/course of destination for the file
 9654:    fname: filname to delete (including any subdirs under userfiles)
 9655: 
 9656: =item *
 9657: 
 9658: removeuploadedurl(): convience function for removeuserfile()
 9659: 
 9660:   Args:
 9661:    url:  a full /uploaded/... url to delete
 9662: 
 9663: =item * 
 9664: 
 9665: get_portfile_permissions():
 9666:   Args:
 9667:     domain: domain of user or course contain the portfolio files
 9668:     user: name of user or num of course contain the portfolio files
 9669:   Returns:
 9670:     hashref of a dump of the proper file_permissions.db
 9671:    
 9672: 
 9673: =item * 
 9674: 
 9675: get_access_controls():
 9676: 
 9677: Args:
 9678:   current_permissions: the hash ref returned from get_portfile_permissions()
 9679:   group: (optional) the group you want the files associated with
 9680:   file: (optional) the file you want access info on
 9681: 
 9682: Returns:
 9683:     a hash (keys are file names) of hashes containing
 9684:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9685:         values are XML containing access control settings (see below) 
 9686: 
 9687: Internal notes:
 9688: 
 9689:  access controls are stored in file_permissions.db as key=value pairs.
 9690:     key -> path to file/file_name\0uniqueID:scope_end_start
 9691:         where scope -> public,guest,course,group,domains or users.
 9692:               end -> UNIX time for end of access (0 -> no end date)
 9693:               start -> UNIX time for start of access
 9694: 
 9695:     value -> XML description of access control
 9696:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9697:             <start></start>
 9698:             <end></end>
 9699: 
 9700:             <password></password>  for scope type = guest
 9701: 
 9702:             <domain></domain>     for scope type = course or group
 9703:             <number></number>
 9704:             <roles id="">
 9705:              <role></role>
 9706:              <access></access>
 9707:              <section></section>
 9708:              <group></group>
 9709:             </roles>
 9710: 
 9711:             <dom></dom>         for scope type = domains
 9712: 
 9713:             <users>             for scope type = users
 9714:              <user>
 9715:               <uname></uname>
 9716:               <udom></udom>
 9717:              </user>
 9718:             </users>
 9719:            </scope> 
 9720:               
 9721:  Access data is also aggregated for each file in an additional key=value pair:
 9722:  key -> path to file/file_name\0accesscontrol 
 9723:  value -> reference to hash
 9724:           hash contains key = value pairs
 9725:           where key = uniqueID:scope_end_start
 9726:                 value = UNIX time record was last updated
 9727: 
 9728:           Used to improve speed of look-ups of access controls for each file.  
 9729:  
 9730:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9731: 
 9732: modify_access_controls():
 9733: 
 9734: Modifies access controls for a portfolio file
 9735: Args
 9736: 1. file name
 9737: 2. reference to hash of required changes,
 9738: 3. domain
 9739: 4. username
 9740:   where domain,username are the domain of the portfolio owner 
 9741:   (either a user or a course) 
 9742: 
 9743: Returns:
 9744: 1. result of additions or updates ('ok' or 'error', with error message). 
 9745: 2. result of deletions ('ok' or 'error', with error message).
 9746: 3. reference to hash of any new or updated access controls.
 9747: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9748:    key = integer (inbound ID)
 9749:    value = uniqueID  
 9750: 
 9751: =back
 9752: 
 9753: =head2 HTTP Helper Routines
 9754: 
 9755: =over 4
 9756: 
 9757: =item *
 9758: 
 9759: escape() : unpack non-word characters into CGI-compatible hex codes
 9760: 
 9761: =item *
 9762: 
 9763: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9764: 
 9765: =back
 9766: 
 9767: =head1 PRIVATE SUBROUTINES
 9768: 
 9769: =head2 Underlying communication routines (Shouldn't call)
 9770: 
 9771: =over 4
 9772: 
 9773: =item *
 9774: 
 9775: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9776: 
 9777: =item *
 9778: 
 9779: reply() : uses subreply to send a message to remote machine, logs all failures
 9780: 
 9781: =item *
 9782: 
 9783: critical() : passes a critical message to another server; if cannot
 9784: get through then place message in connection buffer directory and
 9785: returns con_delayed, if incapable of saving message, returns
 9786: con_failed
 9787: 
 9788: =item *
 9789: 
 9790: reconlonc() : tries to reconnect lonc client processes.
 9791: 
 9792: =back
 9793: 
 9794: =head2 Resource Access Logging
 9795: 
 9796: =over 4
 9797: 
 9798: =item *
 9799: 
 9800: flushcourselogs() : flush (save) buffer logs and access logs
 9801: 
 9802: =item *
 9803: 
 9804: courselog($what) : save message for course in hash
 9805: 
 9806: =item *
 9807: 
 9808: courseacclog($what) : save message for course using &courselog().  Perform
 9809: special processing for specific resource types (problems, exams, quizzes, etc).
 9810: 
 9811: =item *
 9812: 
 9813: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9814: as a PerlChildExitHandler
 9815: 
 9816: =back
 9817: 
 9818: =head2 Other
 9819: 
 9820: =over 4
 9821: 
 9822: =item *
 9823: 
 9824: symblist($mapname,%newhash) : update symbolic storage links
 9825: 
 9826: =back
 9827: 
 9828: =cut
 9829: 

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