File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.952: download - view: text, annotated - select for diffs
Mon Mar 24 05:23:19 2008 UTC (16 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Authentication will be attempted for users attempting to log-in with usernames for which there is no user account, if account creation is permitted for the 'login' type.
- If supplied credentials are authenticated, the user will be able to create an account in the domain. (Requires default authentication in the domain to be Kerberos or localauth -- see lond 1.396).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.952 2008/03/24 05:23:19 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,$checkdefauth)=@_;
  709:     $upass=&escape($upass);
  710:     $uname= &LONCAPA::clean_username($uname);
  711:     my $uhome=&homeserver($uname,$udom,1);
  712:     my $newhome;
  713:     if ((!$uhome) || ($uhome eq 'no_host')) {
  714: # Maybe the machine was offline and only re-appeared again recently?
  715:         &reconlonc();
  716: # One more
  717: 	$uhome=&homeserver($uname,$udom,1);
  718:         if (($uhome eq 'no_host') && $checkdefauth) {
  719:             if (defined(&domain($udom,'primary'))) {
  720:                 $newhome=&domain($udom,'primary');
  721:             }
  722:             if ($newhome ne '') {
  723:                 $uhome = $newhome;
  724:             }
  725:         }
  726: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  727: 	    &logthis("User $uname at $udom is unknown in authenticate");
  728: 	    return 'no_host';
  729:         }
  730:     }
  731:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  732:     if ($answer eq 'authorized') {
  733:         if ($newhome) {
  734:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  735:             return 'no_account_on_host'; 
  736:         } else {
  737:             &logthis("User $uname at $udom authorized by $uhome");
  738:             return $uhome;
  739:         }
  740:     }
  741:     if ($answer eq 'non_authorized') {
  742: 	&logthis("User $uname at $udom rejected by $uhome");
  743: 	return 'no_host'; 
  744:     }
  745:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  746:     return 'no_host';
  747: }
  748: 
  749: # ---------------------- Find the homebase for a user from domain's lib servers
  750: 
  751: my %homecache;
  752: sub homeserver {
  753:     my ($uname,$udom,$ignoreBadCache)=@_;
  754:     my $index="$uname:$udom";
  755: 
  756:     if (exists($homecache{$index})) { return $homecache{$index}; }
  757: 
  758:     my %servers = &get_servers($udom,'library');
  759:     foreach my $tryserver (keys(%servers)) {
  760:         next if ($ignoreBadCache ne 'true' && 
  761: 		 exists($badServerCache{$tryserver}));
  762: 
  763: 	my $answer=reply("home:$udom:$uname",$tryserver);
  764: 	if ($answer eq 'found') {
  765: 	    delete($badServerCache{$tryserver}); 
  766: 	    return $homecache{$index}=$tryserver;
  767: 	} elsif ($answer eq 'no_host') {
  768: 	    $badServerCache{$tryserver}=1;
  769: 	}
  770:     }    
  771:     return 'no_host';
  772: }
  773: 
  774: # ------------------------------------- Find the usernames behind a list of IDs
  775: 
  776: sub idget {
  777:     my ($udom,@ids)=@_;
  778:     my %returnhash=();
  779:     
  780:     my %servers = &get_servers($udom,'library');
  781:     foreach my $tryserver (keys(%servers)) {
  782: 	my $idlist=join('&',@ids);
  783: 	$idlist=~tr/A-Z/a-z/; 
  784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  785: 	my @answer=();
  786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  787: 	    @answer=split(/\&/,$reply);
  788: 	}                    ;
  789: 	my $i;
  790: 	for ($i=0;$i<=$#ids;$i++) {
  791: 	    if ($answer[$i]) {
  792: 		$returnhash{$ids[$i]}=$answer[$i];
  793: 	    } 
  794: 	}
  795:     } 
  796:     return %returnhash;
  797: }
  798: 
  799: # ------------------------------------- Find the IDs behind a list of usernames
  800: 
  801: sub idrget {
  802:     my ($udom,@unames)=@_;
  803:     my %returnhash=();
  804:     foreach my $uname (@unames) {
  805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  806:     }
  807:     return %returnhash;
  808: }
  809: 
  810: # ------------------------------- Store away a list of names and associated IDs
  811: 
  812: sub idput {
  813:     my ($udom,%ids)=@_;
  814:     my %servers=();
  815:     foreach my $uname (keys(%ids)) {
  816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  817:         my $uhom=&homeserver($uname,$udom);
  818:         if ($uhom ne 'no_host') {
  819:             my $id=&escape($ids{$uname});
  820:             $id=~tr/A-Z/a-z/;
  821:             my $esc_unam=&escape($uname);
  822: 	    if ($servers{$uhom}) {
  823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  824:             } else {
  825:                 $servers{$uhom}=$id.'='.$esc_unam;
  826:             }
  827:         }
  828:     }
  829:     foreach my $server (keys(%servers)) {
  830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  831:     }
  832: }
  833: 
  834: # ------------------------------------------- get items from domain db files   
  835: 
  836: sub get_dom {
  837:     my ($namespace,$storearr,$udom,$uhome)=@_;
  838:     my $items='';
  839:     foreach my $item (@$storearr) {
  840:         $items.=&escape($item).'&';
  841:     }
  842:     $items=~s/\&$//;
  843:     if (!$udom) {
  844:         $udom=$env{'user.domain'};
  845:         if (defined(&domain($udom,'primary'))) {
  846:             $uhome=&domain($udom,'primary');
  847:         } else {
  848:             undef($uhome);
  849:         }
  850:     } else {
  851:         if (!$uhome) {
  852:             if (defined(&domain($udom,'primary'))) {
  853:                 $uhome=&domain($udom,'primary');
  854:             }
  855:         }
  856:     }
  857:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  858:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  859:         my %returnhash;
  860:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  861:             return %returnhash;
  862:         }
  863:         my @pairs=split(/\&/,$rep);
  864:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  865:             return @pairs;
  866:         }
  867:         my $i=0;
  868:         foreach my $item (@$storearr) {
  869:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  870:             $i++;
  871:         }
  872:         return %returnhash;
  873:     } else {
  874:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  875:     }
  876: }
  877: 
  878: # -------------------------------------------- put items in domain db files 
  879: 
  880: sub put_dom {
  881:     my ($namespace,$storehash,$udom,$uhome)=@_;
  882:     if (!$udom) {
  883:         $udom=$env{'user.domain'};
  884:         if (defined(&domain($udom,'primary'))) {
  885:             $uhome=&domain($udom,'primary');
  886:         } else {
  887:             undef($uhome);
  888:         }
  889:     } else {
  890:         if (!$uhome) {
  891:             if (defined(&domain($udom,'primary'))) {
  892:                 $uhome=&domain($udom,'primary');
  893:             }
  894:         }
  895:     } 
  896:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  897:         my $items='';
  898:         foreach my $item (keys(%$storehash)) {
  899:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  900:         }
  901:         $items=~s/\&$//;
  902:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  903:     } else {
  904:         &logthis("put_dom failed - no homeserver and/or domain");
  905:     }
  906: }
  907: 
  908: sub retrieve_inst_usertypes {
  909:     my ($udom) = @_;
  910:     my (%returnhash,@order);
  911:     if (defined(&domain($udom,'primary'))) {
  912:         my $uhome=&domain($udom,'primary');
  913:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  914:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  915:         my @pairs=split(/\&/,$hashitems);
  916:         foreach my $item (@pairs) {
  917:             my ($key,$value)=split(/=/,$item,2);
  918:             $key = &unescape($key);
  919:             next if ($key =~ /^error: 2 /);
  920:             $returnhash{$key}=&thaw_unescape($value);
  921:         }
  922:         my @esc_order = split(/\&/,$orderitems);
  923:         foreach my $item (@esc_order) {
  924:             push(@order,&unescape($item));
  925:         }
  926:     } else {
  927:         &logthis("get_dom failed - no primary domain server for $udom");
  928:     }
  929:     return (\%returnhash,\@order);
  930: }
  931: 
  932: sub is_domainimage {
  933:     my ($url) = @_;
  934:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  935:         if (&domain($1) ne '') {
  936:             return '1';
  937:         }
  938:     }
  939:     return;
  940: }
  941: 
  942: sub inst_directory_query {
  943:     my ($srch) = @_;
  944:     my $udom = $srch->{'srchdomain'};
  945:     my %results;
  946:     my $homeserver = &domain($udom,'primary');
  947:     my $outcome;
  948:     if ($homeserver ne '') {
  949: 	my $queryid=&reply("querysend:instdirsearch:".
  950: 			   &escape($srch->{'srchby'}).':'.
  951: 			   &escape($srch->{'srchterm'}).':'.
  952: 			   &escape($srch->{'srchtype'}),$homeserver);
  953: 	my $host=&hostname($homeserver);
  954: 	if ($queryid !~/^\Q$host\E\_/) {
  955: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  956: 	    return;
  957: 	}
  958: 	my $response = &get_query_reply($queryid);
  959: 	my $maxtries = 5;
  960: 	my $tries = 1;
  961: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  962: 	    $response = &get_query_reply($queryid);
  963: 	    $tries ++;
  964: 	}
  965: 
  966:         if (!&error($response) && $response ne 'refused') {
  967:             if ($response eq 'unavailable') {
  968:                 $outcome = $response;
  969:             } else {
  970:                 $outcome = 'ok';
  971:                 my @matches = split(/\n/,$response);
  972:                 foreach my $match (@matches) {
  973:                     my ($key,$value) = split(/=/,$match);
  974:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  975:                 }
  976:             }
  977:         }
  978:     }
  979:     return ($outcome,%results);
  980: }
  981: 
  982: sub usersearch {
  983:     my ($srch) = @_;
  984:     my $dom = $srch->{'srchdomain'};
  985:     my %results;
  986:     my %libserv = &all_library();
  987:     my $query = 'usersearch';
  988:     foreach my $tryserver (keys(%libserv)) {
  989:         if (&host_domain($tryserver) eq $dom) {
  990:             my $host=&hostname($tryserver);
  991:             my $queryid=
  992:                 &reply("querysend:".&escape($query).':'.
  993:                        &escape($srch->{'srchby'}).':'.
  994:                        &escape($srch->{'srchtype'}).':'.
  995:                        &escape($srch->{'srchterm'}),$tryserver);
  996:             if ($queryid !~/^\Q$host\E\_/) {
  997:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  998:                 next;
  999:             }
 1000:             my $reply = &get_query_reply($queryid);
 1001:             my $maxtries = 1;
 1002:             my $tries = 1;
 1003:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1004:                 $reply = &get_query_reply($queryid);
 1005:                 $tries ++;
 1006:             }
 1007:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1008:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1009:             } else {
 1010:                 my @matches;
 1011:                 if ($reply =~ /\n/) {
 1012:                     @matches = split(/\n/,$reply);
 1013:                 } else {
 1014:                     @matches = split(/\&/,$reply);
 1015:                 }
 1016:                 foreach my $match (@matches) {
 1017:                     my ($uname,$udom,%userhash);
 1018:                     foreach my $entry (split(/:/,$match)) {
 1019:                         my ($key,$value) =
 1020:                             map {&unescape($_);} split(/=/,$entry);
 1021:                         $userhash{$key} = $value;
 1022:                         if ($key eq 'username') {
 1023:                             $uname = $value;
 1024:                         } elsif ($key eq 'domain') {
 1025:                             $udom = $value;
 1026:                         }
 1027:                     }
 1028:                     $results{$uname.':'.$udom} = \%userhash;
 1029:                 }
 1030:             }
 1031:         }
 1032:     }
 1033:     return %results;
 1034: }
 1035: 
 1036: sub get_instuser {
 1037:     my ($udom,$uname,$id) = @_;
 1038:     my $homeserver = &domain($udom,'primary');
 1039:     my ($outcome,%results);
 1040:     if ($homeserver ne '') {
 1041:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1042:                            &escape($id).':'.&escape($udom),$homeserver);
 1043:         my $host=&hostname($homeserver);
 1044:         if ($queryid !~/^\Q$host\E\_/) {
 1045:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1046:             return;
 1047:         }
 1048:         my $response = &get_query_reply($queryid);
 1049:         my $maxtries = 5;
 1050:         my $tries = 1;
 1051:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1052:             $response = &get_query_reply($queryid);
 1053:             $tries ++;
 1054:         }
 1055:         if (!&error($response) && $response ne 'refused') {
 1056:             if ($response eq 'unavailable') {
 1057:                 $outcome = $response;
 1058:             } else {
 1059:                 $outcome = 'ok';
 1060:                 my @matches = split(/\n/,$response);
 1061:                 foreach my $match (@matches) {
 1062:                     my ($key,$value) = split(/=/,$match);
 1063:                     $results{&unescape($key)} = &thaw_unescape($value);
 1064:                 }
 1065:             }
 1066:         }
 1067:     }
 1068:     my %userinfo;
 1069:     if (ref($results{$uname}) eq 'HASH') {
 1070:         %userinfo = %{$results{$uname}};
 1071:     } 
 1072:     return ($outcome,%userinfo);
 1073: }
 1074: 
 1075: sub inst_rulecheck {
 1076:     my ($udom,$uname,$id,$item,$rules) = @_;
 1077:     my %returnhash;
 1078:     if ($udom ne '') {
 1079:         if (ref($rules) eq 'ARRAY') {
 1080:             @{$rules} = map {&escape($_);} (@{$rules});
 1081:             my $rulestr = join(':',@{$rules});
 1082:             my $homeserver=&domain($udom,'primary');
 1083:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1084:                 my $response;
 1085:                 if ($item eq 'username') {                
 1086:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1087:                                               ':'.&escape($uname).':'.$rulestr,
 1088:                                               $homeserver));
 1089:                 } elsif ($item eq 'id') {
 1090:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1091:                                               ':'.&escape($id).':'.$rulestr,
 1092:                                               $homeserver));
 1093:                 } elsif ($item eq 'selfcreate') {
 1094:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1095:                                                &escape($udom).':'.&escape($uname).
 1096:                                               ':'.$rulestr,$homeserver));
 1097:                 }
 1098:                 if ($response ne 'refused') {
 1099:                     my @pairs=split(/\&/,$response);
 1100:                     foreach my $item (@pairs) {
 1101:                         my ($key,$value)=split(/=/,$item,2);
 1102:                         $key = &unescape($key);
 1103:                         next if ($key =~ /^error: 2 /);
 1104:                         $returnhash{$key}=&thaw_unescape($value);
 1105:                     }
 1106:                 }
 1107:             }
 1108:         }
 1109:     }
 1110:     return %returnhash;
 1111: }
 1112: 
 1113: sub inst_userrules {
 1114:     my ($udom,$check) = @_;
 1115:     my (%ruleshash,@ruleorder);
 1116:     if ($udom ne '') {
 1117:         my $homeserver=&domain($udom,'primary');
 1118:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1119:             my $response;
 1120:             if ($check eq 'id') {
 1121:                 $response=&reply('instidrules:'.&escape($udom),
 1122:                                  $homeserver);
 1123:             } elsif ($check eq 'email') {
 1124:                 $response=&reply('instemailrules:'.&escape($udom),
 1125:                                  $homeserver);
 1126:             } else {
 1127:                 $response=&reply('instuserrules:'.&escape($udom),
 1128:                                  $homeserver);
 1129:             }
 1130:             if (($response ne 'refused') && ($response ne 'error') && 
 1131:                 ($response ne 'unknown_cmd') && 
 1132:                 ($response ne 'no_such_host')) {
 1133:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1134:                 my @pairs=split(/\&/,$hashitems);
 1135:                 foreach my $item (@pairs) {
 1136:                     my ($key,$value)=split(/=/,$item,2);
 1137:                     $key = &unescape($key);
 1138:                     next if ($key =~ /^error: 2 /);
 1139:                     $ruleshash{$key}=&thaw_unescape($value);
 1140:                 }
 1141:                 my @esc_order = split(/\&/,$orderitems);
 1142:                 foreach my $item (@esc_order) {
 1143:                     push(@ruleorder,&unescape($item));
 1144:                 }
 1145:             }
 1146:         }
 1147:     }
 1148:     return (\%ruleshash,\@ruleorder);
 1149: }
 1150: 
 1151: # ------------------------- Get Authentication and Language Defaults for Domain
 1152: 
 1153: sub get_domain_defaults {
 1154:     my ($domain) = @_;
 1155:     my $cachetime = 60*60*24;
 1156:     my ($defauthtype,$defautharg,$deflang);
 1157:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1158:     if (defined($cached)) {
 1159:         if (ref($result) eq 'HASH') {
 1160:             return %{$result};
 1161:         }
 1162:     }
 1163:     my %domdefaults;
 1164:     my %domconfig =
 1165:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
 1166:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1167:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1168:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1169:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1170:     } else {
 1171:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1172:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1173:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1174:     }
 1175:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1176:                                   $cachetime);
 1177:     return %domdefaults;
 1178: }
 1179: 
 1180: # --------------------------------------------------- Assign a key to a student
 1181: 
 1182: sub assign_access_key {
 1183: #
 1184: # a valid key looks like uname:udom#comments
 1185: # comments are being appended
 1186: #
 1187:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1188:     $kdom=
 1189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1190:     $knum=
 1191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1192:     $cdom=
 1193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1194:     $cnum=
 1195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1196:     $udom=$env{'user.name'} unless (defined($udom));
 1197:     $uname=$env{'user.domain'} unless (defined($uname));
 1198:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1199:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1200:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1201:                                                   # assigned to this person
 1202:                                                   # - this should not happen,
 1203:                                                   # unless something went wrong
 1204:                                                   # the first time around
 1205: # ready to assign
 1206:         $logentry=$1.'; '.$logentry;
 1207:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1208:                                                  $kdom,$knum) eq 'ok') {
 1209: # key now belongs to user
 1210: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1211:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1212:                 &appenv({'environment.'.$envkey => $ckey});
 1213:                 return 'ok';
 1214:             } else {
 1215:                 return 
 1216:   'error: Count not permanently assign key, will need to be re-entered later.';
 1217: 	    }
 1218:         } else {
 1219:             return 'error: Could not assign key, try again later.';
 1220:         }
 1221:     } elsif (!$existing{$ckey}) {
 1222: # the key does not exist
 1223: 	return 'error: The key does not exist';
 1224:     } else {
 1225: # the key is somebody else's
 1226: 	return 'error: The key is already in use';
 1227:     }
 1228: }
 1229: 
 1230: # ------------------------------------------ put an additional comment on a key
 1231: 
 1232: sub comment_access_key {
 1233: #
 1234: # a valid key looks like uname:udom#comments
 1235: # comments are being appended
 1236: #
 1237:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1238:     $cdom=
 1239:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1240:     $cnum=
 1241:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1242:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1243:     if ($existing{$ckey}) {
 1244:         $existing{$ckey}.='; '.$logentry;
 1245: # ready to assign
 1246:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1247:                                                  $cdom,$cnum) eq 'ok') {
 1248: 	    return 'ok';
 1249:         } else {
 1250: 	    return 'error: Count not store comment.';
 1251:         }
 1252:     } else {
 1253: # the key does not exist
 1254: 	return 'error: The key does not exist';
 1255:     }
 1256: }
 1257: 
 1258: # ------------------------------------------------------ Generate a set of keys
 1259: 
 1260: sub generate_access_keys {
 1261:     my ($number,$cdom,$cnum,$logentry)=@_;
 1262:     $cdom=
 1263:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1264:     $cnum=
 1265:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1266:     unless (&allowed('mky',$cdom)) { return 0; }
 1267:     unless (($cdom) && ($cnum)) { return 0; }
 1268:     if ($number>10000) { return 0; }
 1269:     sleep(2); # make sure don't get same seed twice
 1270:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1271:     my $total=0;
 1272:     for (my $i=1;$i<=$number;$i++) {
 1273:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1274:                   sprintf("%lx",int(100000*rand)).'-'.
 1275:                   sprintf("%lx",int(100000*rand));
 1276:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1277:        $newkey=~s/0/h/g; # and also 0 and O
 1278:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1279:        if ($existing{$newkey}) {
 1280:            $i--;
 1281:        } else {
 1282: 	  if (&put('accesskeys',
 1283:               { $newkey => '# generated '.localtime().
 1284:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1285:                            '; '.$logentry },
 1286: 		   $cdom,$cnum) eq 'ok') {
 1287:               $total++;
 1288: 	  }
 1289:        }
 1290:     }
 1291:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1292:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1293:     return $total;
 1294: }
 1295: 
 1296: # ------------------------------------------------------- Validate an accesskey
 1297: 
 1298: sub validate_access_key {
 1299:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1300:     $cdom=
 1301:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1302:     $cnum=
 1303:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1304:     $udom=$env{'user.domain'} unless (defined($udom));
 1305:     $uname=$env{'user.name'} unless (defined($uname));
 1306:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1307:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1308: }
 1309: 
 1310: # ------------------------------------- Find the section of student in a course
 1311: sub devalidate_getsection_cache {
 1312:     my ($udom,$unam,$courseid)=@_;
 1313:     my $hashid="$udom:$unam:$courseid";
 1314:     &devalidate_cache_new('getsection',$hashid);
 1315: }
 1316: 
 1317: sub courseid_to_courseurl {
 1318:     my ($courseid) = @_;
 1319:     #already url style courseid
 1320:     return $courseid if ($courseid =~ m{^/});
 1321: 
 1322:     if (exists($env{'course.'.$courseid.'.num'})) {
 1323: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1324: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1325: 	return "/$cdom/$cnum";
 1326:     }
 1327: 
 1328:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1329:     if (exists($courseinfo{'num'})) {
 1330: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1331:     }
 1332: 
 1333:     return undef;
 1334: }
 1335: 
 1336: sub getsection {
 1337:     my ($udom,$unam,$courseid)=@_;
 1338:     my $cachetime=1800;
 1339: 
 1340:     my $hashid="$udom:$unam:$courseid";
 1341:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1342:     if (defined($cached)) { return $result; }
 1343: 
 1344:     my %Pending; 
 1345:     my %Expired;
 1346:     #
 1347:     # Each role can either have not started yet (pending), be active, 
 1348:     #    or have expired.
 1349:     #
 1350:     # If there is an active role, we are done.
 1351:     #
 1352:     # If there is more than one role which has not started yet, 
 1353:     #     choose the one which will start sooner
 1354:     # If there is one role which has not started yet, return it.
 1355:     #
 1356:     # If there is more than one expired role, choose the one which ended last.
 1357:     # If there is a role which has expired, return it.
 1358:     #
 1359:     $courseid = &courseid_to_courseurl($courseid);
 1360:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1361:     foreach my $key (keys(%roleshash)) {
 1362:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1363:         my $section=$1;
 1364:         if ($key eq $courseid.'_st') { $section=''; }
 1365:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1366:         my $now=time;
 1367:         if (defined($end) && $end && ($now > $end)) {
 1368:             $Expired{$end}=$section;
 1369:             next;
 1370:         }
 1371:         if (defined($start) && $start && ($now < $start)) {
 1372:             $Pending{$start}=$section;
 1373:             next;
 1374:         }
 1375:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1376:     }
 1377:     #
 1378:     # Presumedly there will be few matching roles from the above
 1379:     # loop and the sorting time will be negligible.
 1380:     if (scalar(keys(%Pending))) {
 1381:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1382:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1383:     } 
 1384:     if (scalar(keys(%Expired))) {
 1385:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1386:         my $time = pop(@sorted);
 1387:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1388:     }
 1389:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1390: }
 1391: 
 1392: sub save_cache {
 1393:     &purge_remembered();
 1394:     #&Apache::loncommon::validate_page();
 1395:     undef(%env);
 1396:     undef($env_loaded);
 1397: }
 1398: 
 1399: my $to_remember=-1;
 1400: my %remembered;
 1401: my %accessed;
 1402: my $kicks=0;
 1403: my $hits=0;
 1404: sub make_key {
 1405:     my ($name,$id) = @_;
 1406:     if (length($id) > 65 
 1407: 	&& length(&escape($id)) > 200) {
 1408: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1409:     }
 1410:     return &escape($name.':'.$id);
 1411: }
 1412: 
 1413: sub devalidate_cache_new {
 1414:     my ($name,$id,$debug) = @_;
 1415:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1416:     $id=&make_key($name,$id);
 1417:     $memcache->delete($id);
 1418:     delete($remembered{$id});
 1419:     delete($accessed{$id});
 1420: }
 1421: 
 1422: sub is_cached_new {
 1423:     my ($name,$id,$debug) = @_;
 1424:     $id=&make_key($name,$id);
 1425:     if (exists($remembered{$id})) {
 1426: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1427: 	$accessed{$id}=[&gettimeofday()];
 1428: 	$hits++;
 1429: 	return ($remembered{$id},1);
 1430:     }
 1431:     my $value = $memcache->get($id);
 1432:     if (!(defined($value))) {
 1433: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1434: 	return (undef,undef);
 1435:     }
 1436:     if ($value eq '__undef__') {
 1437: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1438: 	$value=undef;
 1439:     }
 1440:     &make_room($id,$value,$debug);
 1441:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1442:     return ($value,1);
 1443: }
 1444: 
 1445: sub do_cache_new {
 1446:     my ($name,$id,$value,$time,$debug) = @_;
 1447:     $id=&make_key($name,$id);
 1448:     my $setvalue=$value;
 1449:     if (!defined($setvalue)) {
 1450: 	$setvalue='__undef__';
 1451:     }
 1452:     if (!defined($time) ) {
 1453: 	$time=600;
 1454:     }
 1455:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1456:     my $result = $memcache->set($id,$setvalue,$time);
 1457:     if (! $result) {
 1458: 	&logthis("caching of id -> $id  failed");
 1459: 	$memcache->disconnect_all();
 1460:     }
 1461:     # need to make a copy of $value
 1462:     &make_room($id,$value,$debug);
 1463:     return $value;
 1464: }
 1465: 
 1466: sub make_room {
 1467:     my ($id,$value,$debug)=@_;
 1468: 
 1469:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1470:                                     : $value;
 1471:     if ($to_remember<0) { return; }
 1472:     $accessed{$id}=[&gettimeofday()];
 1473:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1474:     my $to_kick;
 1475:     my $max_time=0;
 1476:     foreach my $other (keys(%accessed)) {
 1477: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1478: 	    $to_kick=$other;
 1479: 	    $max_time=&tv_interval($accessed{$other});
 1480: 	}
 1481:     }
 1482:     delete($remembered{$to_kick});
 1483:     delete($accessed{$to_kick});
 1484:     $kicks++;
 1485:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1486:     return;
 1487: }
 1488: 
 1489: sub purge_remembered {
 1490:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1491:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1492:     undef(%remembered);
 1493:     undef(%accessed);
 1494: }
 1495: # ------------------------------------- Read an entry from a user's environment
 1496: 
 1497: sub userenvironment {
 1498:     my ($udom,$unam,@what)=@_;
 1499:     my %returnhash=();
 1500:     my @answer=split(/\&/,
 1501:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1502:                       &homeserver($unam,$udom)));
 1503:     my $i;
 1504:     for ($i=0;$i<=$#what;$i++) {
 1505: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1506:     }
 1507:     return %returnhash;
 1508: }
 1509: 
 1510: # ---------------------------------------------------------- Get a studentphoto
 1511: sub studentphoto {
 1512:     my ($udom,$unam,$ext) = @_;
 1513:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1514:     if (defined($env{'request.course.id'})) {
 1515:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1516:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1517:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1518:             } else {
 1519:                 my ($result,$perm_reqd)=
 1520: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1521:                 if ($result eq 'ok') {
 1522:                     if (!($perm_reqd eq 'yes')) {
 1523:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1524:                     }
 1525:                 }
 1526:             }
 1527:         }
 1528:     } else {
 1529:         my ($result,$perm_reqd) = 
 1530: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1531:         if ($result eq 'ok') {
 1532:             if (!($perm_reqd eq 'yes')) {
 1533:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1534:             }
 1535:         }
 1536:     }
 1537:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1538: }
 1539: 
 1540: sub retrievestudentphoto {
 1541:     my ($udom,$unam,$ext,$type) = @_;
 1542:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1543:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1544:     if ($ret eq 'ok') {
 1545:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1546:         if ($type eq 'thumbnail') {
 1547:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1548:         }
 1549:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1550:         return $tokenurl;
 1551:     } else {
 1552:         if ($type eq 'thumbnail') {
 1553:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1554:         } else { 
 1555:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1556:         }
 1557:     }
 1558: }
 1559: 
 1560: # -------------------------------------------------------------------- New chat
 1561: 
 1562: sub chatsend {
 1563:     my ($newentry,$anon,$group)=@_;
 1564:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1565:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1566:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1567:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1568: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1569: 		   &escape($newentry)).':'.$group,$chome);
 1570: }
 1571: 
 1572: # ------------------------------------------ Find current version of a resource
 1573: 
 1574: sub getversion {
 1575:     my $fname=&clutter(shift);
 1576:     unless ($fname=~/^\/res\//) { return -1; }
 1577:     return &currentversion(&filelocation('',$fname));
 1578: }
 1579: 
 1580: sub currentversion {
 1581:     my $fname=shift;
 1582:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1583:     if (defined($cached)) { return $result; }
 1584:     my $author=$fname;
 1585:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1586:     my ($udom,$uname)=split(/\//,$author);
 1587:     my $home=homeserver($uname,$udom);
 1588:     if ($home eq 'no_host') { 
 1589:         return -1; 
 1590:     }
 1591:     my $answer=reply("currentversion:$fname",$home);
 1592:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1593: 	return -1;
 1594:     }
 1595:     return &do_cache_new('resversion',$fname,$answer,600);
 1596: }
 1597: 
 1598: # ----------------------------- Subscribe to a resource, return URL if possible
 1599: 
 1600: sub subscribe {
 1601:     my $fname=shift;
 1602:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1603:     $fname=~s/[\n\r]//g;
 1604:     my $author=$fname;
 1605:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1606:     my ($udom,$uname)=split(/\//,$author);
 1607:     my $home=homeserver($uname,$udom);
 1608:     if ($home eq 'no_host') {
 1609:         return 'not_found';
 1610:     }
 1611:     my $answer=reply("sub:$fname",$home);
 1612:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1613: 	$answer.=' by '.$home;
 1614:     }
 1615:     return $answer;
 1616: }
 1617:     
 1618: # -------------------------------------------------------------- Replicate file
 1619: 
 1620: sub repcopy {
 1621:     my $filename=shift;
 1622:     $filename=~s/\/+/\//g;
 1623:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1624:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1625:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1626: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1627: 	return &repcopy_userfile($filename);
 1628:     }
 1629:     $filename=~s/[\n\r]//g;
 1630:     my $transname="$filename.in.transfer";
 1631: # FIXME: this should flock
 1632:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1633:     my $remoteurl=subscribe($filename);
 1634:     if ($remoteurl =~ /^con_lost by/) {
 1635: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1636:            return 'unavailable';
 1637:     } elsif ($remoteurl eq 'not_found') {
 1638: 	   #&logthis("Subscribe returned not_found: $filename");
 1639: 	   return 'not_found';
 1640:     } elsif ($remoteurl =~ /^rejected by/) {
 1641: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1642:            return 'forbidden';
 1643:     } elsif ($remoteurl eq 'directory') {
 1644:            return 'ok';
 1645:     } else {
 1646:         my $author=$filename;
 1647:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1648:         my ($udom,$uname)=split(/\//,$author);
 1649:         my $home=homeserver($uname,$udom);
 1650:         unless ($home eq $perlvar{'lonHostID'}) {
 1651:            my @parts=split(/\//,$filename);
 1652:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1653:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1654:                &logthis("Malconfiguration for replication: $filename");
 1655: 	       return 'bad_request';
 1656:            }
 1657:            my $count;
 1658:            for ($count=5;$count<$#parts;$count++) {
 1659:                $path.="/$parts[$count]";
 1660:                if ((-e $path)!=1) {
 1661: 		   mkdir($path,0777);
 1662:                }
 1663:            }
 1664:            my $ua=new LWP::UserAgent;
 1665:            my $request=new HTTP::Request('GET',"$remoteurl");
 1666:            my $response=$ua->request($request,$transname);
 1667:            if ($response->is_error()) {
 1668: 	       unlink($transname);
 1669:                my $message=$response->status_line;
 1670:                &logthis("<font color=\"blue\">WARNING:"
 1671:                        ." LWP get: $message: $filename</font>");
 1672:                return 'unavailable';
 1673:            } else {
 1674: 	       if ($remoteurl!~/\.meta$/) {
 1675:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1676:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1677:                   if ($mresponse->is_error()) {
 1678: 		      unlink($filename.'.meta');
 1679:                       &logthis(
 1680:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1681:                   }
 1682: 	       }
 1683:                rename($transname,$filename);
 1684:                return 'ok';
 1685:            }
 1686:        }
 1687:     }
 1688: }
 1689: 
 1690: # ------------------------------------------------ Get server side include body
 1691: sub ssi_body {
 1692:     my ($filelink,%form)=@_;
 1693:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1694:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1695:     }
 1696:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1697:                                      &ssi($filelink,%form));
 1698:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1699:     $output=~s/^.*?\<body[^\>]*\>//si;
 1700:     $output=~s/\<\/body\s*\>.*?$//si;
 1701:     return $output;
 1702: }
 1703: 
 1704: # --------------------------------------------------------- Server Side Include
 1705: 
 1706: sub absolute_url {
 1707:     my ($host_name) = @_;
 1708:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1709:     if ($host_name eq '') {
 1710: 	$host_name = $ENV{'SERVER_NAME'};
 1711:     }
 1712:     return $protocol.$host_name;
 1713: }
 1714: 
 1715: #
 1716: #   Server side include.
 1717: # Parameters:
 1718: #  fn     Possibly encrypted resource name/id.
 1719: #  form   Hash that describes how the rendering should be done
 1720: #         and other things.
 1721: # Returns:
 1722: #   Scalar context: The content of the response.
 1723: #   Array context:  2 element list of the content and the full response object.
 1724: #     
 1725: sub ssi {
 1726: 
 1727:     my ($fn,%form)=@_;
 1728:     my $ua=new LWP::UserAgent;
 1729:     my $request;
 1730: 
 1731:     $form{'no_update_last_known'}=1;
 1732:     &Apache::lonenc::check_encrypt(\$fn);
 1733:     if (%form) {
 1734:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1735:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1736:     } else {
 1737:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1738:     }
 1739: 
 1740:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1741:     my $response=$ua->request($request);
 1742: 
 1743:     if (wantarray) {
 1744: 	return ($response->content, $response);
 1745:     } else {
 1746: 	return $response->content;
 1747:     }
 1748: }
 1749: 
 1750: sub externalssi {
 1751:     my ($url)=@_;
 1752:     my $ua=new LWP::UserAgent;
 1753:     my $request=new HTTP::Request('GET',$url);
 1754:     my $response=$ua->request($request);
 1755:     return $response->content;
 1756: }
 1757: 
 1758: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1759: 
 1760: sub allowuploaded {
 1761:     my ($srcurl,$url)=@_;
 1762:     $url=&clutter(&declutter($url));
 1763:     my $dir=$url;
 1764:     $dir=~s/\/[^\/]+$//;
 1765:     my %httpref=();
 1766:     my $httpurl=&hreflocation('',$url);
 1767:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1768:     &Apache::lonnet::appenv(\%httpref);
 1769: }
 1770: 
 1771: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1772: # input: action, courseID, current domain, intended
 1773: #        path to file, source of file, instruction to parse file for objects,
 1774: #        ref to hash for embedded objects,
 1775: #        ref to hash for codebase of java objects.
 1776: #
 1777: # output: url to file (if action was uploaddoc), 
 1778: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1779: #
 1780: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1781: # course.
 1782: #
 1783: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1784: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1785: #          course's home server.
 1786: #
 1787: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1788: #          be copied from $source (current location) to 
 1789: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1790: #         and will then be copied to
 1791: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1792: #         course's home server.
 1793: #
 1794: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1795: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1796: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1797: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1798: #         in course's home server.
 1799: #
 1800: 
 1801: sub process_coursefile {
 1802:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1803:     my $fetchresult;
 1804:     my $home=&homeserver($docuname,$docudom);
 1805:     if ($action eq 'propagate') {
 1806:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1807: 			     $home);
 1808:     } else {
 1809:         my $fpath = '';
 1810:         my $fname = $file;
 1811:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1812:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1813:         my $filepath = &build_filepath($fpath);
 1814:         if ($action eq 'copy') {
 1815:             if ($source eq '') {
 1816:                 $fetchresult = 'no source file';
 1817:                 return $fetchresult;
 1818:             } else {
 1819:                 my $destination = $filepath.'/'.$fname;
 1820:                 rename($source,$destination);
 1821:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1822:                                  $home);
 1823:             }
 1824:         } elsif ($action eq 'uploaddoc') {
 1825:             open(my $fh,'>'.$filepath.'/'.$fname);
 1826:             print $fh $env{'form.'.$source};
 1827:             close($fh);
 1828:             if ($parser eq 'parse') {
 1829:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1830:                 unless ($parse_result eq 'ok') {
 1831:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1832:                 }
 1833:             }
 1834:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1835:                                  $home);
 1836:             if ($fetchresult eq 'ok') {
 1837:                 return '/uploaded/'.$fpath.'/'.$fname;
 1838:             } else {
 1839:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1840:                         ' to host '.$home.': '.$fetchresult);
 1841:                 return '/adm/notfound.html';
 1842:             }
 1843:         }
 1844:     }
 1845:     unless ( $fetchresult eq 'ok') {
 1846:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1847:              ' to host '.$home.': '.$fetchresult);
 1848:     }
 1849:     return $fetchresult;
 1850: }
 1851: 
 1852: sub build_filepath {
 1853:     my ($fpath) = @_;
 1854:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1855:     unless ($fpath eq '') {
 1856:         my @parts=split('/',$fpath);
 1857:         foreach my $part (@parts) {
 1858:             $filepath.= '/'.$part;
 1859:             if ((-e $filepath)!=1) {
 1860:                 mkdir($filepath,0777);
 1861:             }
 1862:         }
 1863:     }
 1864:     return $filepath;
 1865: }
 1866: 
 1867: sub store_edited_file {
 1868:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1869:     my $file = $primary_url;
 1870:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1871:     my $fpath = '';
 1872:     my $fname = $file;
 1873:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1874:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1875:     my $filepath = &build_filepath($fpath);
 1876:     open(my $fh,'>'.$filepath.'/'.$fname);
 1877:     print $fh $content;
 1878:     close($fh);
 1879:     my $home=&homeserver($docuname,$docudom);
 1880:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1881: 			  $home);
 1882:     if ($$fetchresult eq 'ok') {
 1883:         return '/uploaded/'.$fpath.'/'.$fname;
 1884:     } else {
 1885:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1886: 		 ' to host '.$home.': '.$$fetchresult);
 1887:         return '/adm/notfound.html';
 1888:     }
 1889: }
 1890: 
 1891: sub clean_filename {
 1892:     my ($fname,$args)=@_;
 1893: # Replace Windows backslashes by forward slashes
 1894:     $fname=~s/\\/\//g;
 1895:     if (!$args->{'keep_path'}) {
 1896:         # Get rid of everything but the actual filename
 1897: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1898:     }
 1899: # Replace spaces by underscores
 1900:     $fname=~s/\s+/\_/g;
 1901: # Replace all other weird characters by nothing
 1902:     $fname=~s{[^/\w\.\-]}{}g;
 1903: # Replace all .\d. sequences with _\d. so they no longer look like version
 1904: # numbers
 1905:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1906:     return $fname;
 1907: }
 1908: 
 1909: # --------------- Take an uploaded file and put it into the userfiles directory
 1910: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1911: #                    the desired filenam is in $env{"form.$formname.filename"}
 1912: #        $coursedoc - if true up to the current course
 1913: #                     if false
 1914: #        $subdir - directory in userfile to store the file into
 1915: #        $parser - instruction to parse file for objects ($parser = parse)    
 1916: #        $allfiles - reference to hash for embedded objects
 1917: #        $codebase - reference to hash for codebase of java objects
 1918: #        $desuname - username for permanent storage of uploaded file
 1919: #        $dsetudom - domain for permanaent storage of uploaded file
 1920: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1921: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1922: # 
 1923: # output: url of file in userspace, or error: <message> 
 1924: #             or /adm/notfound.html if failure to upload occurse
 1925: 
 1926: 
 1927: sub userfileupload {
 1928:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1929:         $destudom,$thumbwidth,$thumbheight)=@_;
 1930:     if (!defined($subdir)) { $subdir='unknown'; }
 1931:     my $fname=$env{'form.'.$formname.'.filename'};
 1932:     $fname=&clean_filename($fname);
 1933: # See if there is anything left
 1934:     unless ($fname) { return 'error: no uploaded file'; }
 1935:     chop($env{'form.'.$formname});
 1936:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1937:         my $now = time;
 1938:         my $filepath = 'tmp/helprequests/'.$now;
 1939:         my @parts=split(/\//,$filepath);
 1940:         my $fullpath = $perlvar{'lonDaemons'};
 1941:         for (my $i=0;$i<@parts;$i++) {
 1942:             $fullpath .= '/'.$parts[$i];
 1943:             if ((-e $fullpath)!=1) {
 1944:                 mkdir($fullpath,0777);
 1945:             }
 1946:         }
 1947:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1948:         print $fh $env{'form.'.$formname};
 1949:         close($fh);
 1950:         return $fullpath.'/'.$fname;
 1951:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1952:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1953:                        '_'.$env{'user.domain'}.'/pending';
 1954:         my @parts=split(/\//,$filepath);
 1955:         my $fullpath = $perlvar{'lonDaemons'};
 1956:         for (my $i=0;$i<@parts;$i++) {
 1957:             $fullpath .= '/'.$parts[$i];
 1958:             if ((-e $fullpath)!=1) {
 1959:                 mkdir($fullpath,0777);
 1960:             }
 1961:         }
 1962:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1963:         print $fh $env{'form.'.$formname};
 1964:         close($fh);
 1965:         return $fullpath.'/'.$fname;
 1966:     }
 1967:     
 1968: # Create the directory if not present
 1969:     $fname="$subdir/$fname";
 1970:     if ($coursedoc) {
 1971: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1972: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1973:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1974:             return &finishuserfileupload($docuname,$docudom,
 1975: 					 $formname,$fname,$parser,$allfiles,
 1976: 					 $codebase,$thumbwidth,$thumbheight);
 1977:         } else {
 1978:             $fname=$env{'form.folder'}.'/'.$fname;
 1979:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1980: 				       $fname,$formname,$parser,
 1981: 				       $allfiles,$codebase);
 1982:         }
 1983:     } elsif (defined($destuname)) {
 1984:         my $docuname=$destuname;
 1985:         my $docudom=$destudom;
 1986: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1987: 				     $parser,$allfiles,$codebase,
 1988:                                      $thumbwidth,$thumbheight);
 1989:         
 1990:     } else {
 1991:         my $docuname=$env{'user.name'};
 1992:         my $docudom=$env{'user.domain'};
 1993:         if (exists($env{'form.group'})) {
 1994:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1995:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1996:         }
 1997: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1998: 				     $parser,$allfiles,$codebase,
 1999:                                      $thumbwidth,$thumbheight);
 2000:     }
 2001: }
 2002: 
 2003: sub finishuserfileupload {
 2004:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2005:         $thumbwidth,$thumbheight) = @_;
 2006:     my $path=$docudom.'/'.$docuname.'/';
 2007:     my $filepath=$perlvar{'lonDocRoot'};
 2008:     my ($fnamepath,$file,$fetchthumb);
 2009:     $file=$fname;
 2010:     if ($fname=~m|/|) {
 2011:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2012: 	$path.=$fnamepath.'/';
 2013:     }
 2014:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2015:     my $count;
 2016:     for ($count=4;$count<=$#parts;$count++) {
 2017:         $filepath.="/$parts[$count]";
 2018:         if ((-e $filepath)!=1) {
 2019: 	    mkdir($filepath,0777);
 2020:         }
 2021:     }
 2022: # Save the file
 2023:     {
 2024: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2025: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2026: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2027: 	    return '/adm/notfound.html';
 2028: 	}
 2029: 	if (!print FH ($env{'form.'.$formname})) {
 2030: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2031: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2032: 	    return '/adm/notfound.html';
 2033: 	}
 2034: 	close(FH);
 2035:     }
 2036:     if ($parser eq 'parse') {
 2037:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 2038: 						   $codebase);
 2039:         unless ($parse_result eq 'ok') {
 2040:             &logthis('Failed to parse '.$filepath.$file.
 2041: 		     ' for embedded media: '.$parse_result); 
 2042:         }
 2043:     }
 2044:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2045:         my $input = $filepath.'/'.$file;
 2046:         my $output = $filepath.'/'.'tn-'.$file;
 2047:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2048:         system("convert -sample $thumbsize $input $output");
 2049:         if (-e $filepath.'/'.'tn-'.$file) {
 2050:             $fetchthumb  = 1; 
 2051:         }
 2052:     }
 2053:  
 2054: # Notify homeserver to grep it
 2055: #
 2056:     my $docuhome=&homeserver($docuname,$docudom);
 2057:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2058:     if ($fetchresult eq 'ok') {
 2059:         if ($fetchthumb) {
 2060:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2061:             if ($thumbresult ne 'ok') {
 2062:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2063:                          $docuhome.': '.$thumbresult);
 2064:             }
 2065:         }
 2066: #
 2067: # Return the URL to it
 2068:         return '/uploaded/'.$path.$file;
 2069:     } else {
 2070:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2071: 		 ': '.$fetchresult);
 2072:         return '/adm/notfound.html';
 2073:     }
 2074: }
 2075: 
 2076: sub extract_embedded_items {
 2077:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2078:     my @state = ();
 2079:     my %javafiles = (
 2080:                       codebase => '',
 2081:                       code => '',
 2082:                       archive => ''
 2083:                     );
 2084:     my %mediafiles = (
 2085:                       src => '',
 2086:                       movie => '',
 2087:                      );
 2088:     my $p;
 2089:     if ($content) {
 2090:         $p = HTML::LCParser->new($content);
 2091:     } else {
 2092:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2093:     }
 2094:     while (my $t=$p->get_token()) {
 2095: 	if ($t->[0] eq 'S') {
 2096: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2097: 	    push(@state, $tagname);
 2098:             if (lc($tagname) eq 'allow') {
 2099:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2100:             }
 2101: 	    if (lc($tagname) eq 'img') {
 2102: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2103: 	    }
 2104: 	    if (lc($tagname) eq 'a') {
 2105: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2106: 	    }
 2107:             if (lc($tagname) eq 'script') {
 2108:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2109:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2110:                 } else {
 2111:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2112:                 }
 2113:             }
 2114:             if (lc($tagname) eq 'link') {
 2115:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2116:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2117:                 }
 2118:             }
 2119: 	    if (lc($tagname) eq 'object' ||
 2120: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2121: 		foreach my $item (keys(%javafiles)) {
 2122: 		    $javafiles{$item} = '';
 2123: 		}
 2124: 	    }
 2125: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2126: 		my $name = lc($attr->{'name'});
 2127: 		foreach my $item (keys(%javafiles)) {
 2128: 		    if ($name eq $item) {
 2129: 			$javafiles{$item} = $attr->{'value'};
 2130: 			last;
 2131: 		    }
 2132: 		}
 2133: 		foreach my $item (keys(%mediafiles)) {
 2134: 		    if ($name eq $item) {
 2135: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2136: 			last;
 2137: 		    }
 2138: 		}
 2139: 	    }
 2140: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2141: 		foreach my $item (keys(%javafiles)) {
 2142: 		    if ($attr->{$item}) {
 2143: 			$javafiles{$item} = $attr->{$item};
 2144: 			last;
 2145: 		    }
 2146: 		}
 2147: 		foreach my $item (keys(%mediafiles)) {
 2148: 		    if ($attr->{$item}) {
 2149: 			&add_filetype($allfiles,$attr->{$item},$item);
 2150: 			last;
 2151: 		    }
 2152: 		}
 2153: 	    }
 2154: 	} elsif ($t->[0] eq 'E') {
 2155: 	    my ($tagname) = ($t->[1]);
 2156: 	    if ($javafiles{'codebase'} ne '') {
 2157: 		$javafiles{'codebase'} .= '/';
 2158: 	    }  
 2159: 	    if (lc($tagname) eq 'applet' ||
 2160: 		lc($tagname) eq 'object' ||
 2161: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2162: 		) {
 2163: 		foreach my $item (keys(%javafiles)) {
 2164: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2165: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2166: 			&add_filetype($allfiles,$file,$item);
 2167: 		    }
 2168: 		}
 2169: 	    } 
 2170: 	    pop @state;
 2171: 	}
 2172:     }
 2173:     return 'ok';
 2174: }
 2175: 
 2176: sub add_filetype {
 2177:     my ($allfiles,$file,$type)=@_;
 2178:     if (exists($allfiles->{$file})) {
 2179: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2180: 	    push(@{$allfiles->{$file}}, &escape($type));
 2181: 	}
 2182:     } else {
 2183: 	@{$allfiles->{$file}} = (&escape($type));
 2184:     }
 2185: }
 2186: 
 2187: sub removeuploadedurl {
 2188:     my ($url)=@_;
 2189:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2190:     return &removeuserfile($uname,$udom,$fname);
 2191: }
 2192: 
 2193: sub removeuserfile {
 2194:     my ($docuname,$docudom,$fname)=@_;
 2195:     my $home=&homeserver($docuname,$docudom);
 2196:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2197:     if ($result eq 'ok') {
 2198:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2199:             my $metafile = $fname.'.meta';
 2200:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2201: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2202:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2203:             my $sqlresult = 
 2204:                 &update_portfolio_table($docuname,$docudom,$file,
 2205:                                         'portfolio_metadata',$group,
 2206:                                         'delete');
 2207:         }
 2208:     }
 2209:     return $result;
 2210: }
 2211: 
 2212: sub mkdiruserfile {
 2213:     my ($docuname,$docudom,$dir)=@_;
 2214:     my $home=&homeserver($docuname,$docudom);
 2215:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2216: }
 2217: 
 2218: sub renameuserfile {
 2219:     my ($docuname,$docudom,$old,$new)=@_;
 2220:     my $home=&homeserver($docuname,$docudom);
 2221:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2222:                         &escape("$old").':'.&escape("$new"),$home);
 2223:     if ($result eq 'ok') {
 2224:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2225:             my $oldmeta = $old.'.meta';
 2226:             my $newmeta = $new.'.meta';
 2227:             my $metaresult = 
 2228:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2229: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2230:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2231:             my $sqlresult = 
 2232:                 &update_portfolio_table($docuname,$docudom,$file,
 2233:                                         'portfolio_metadata',$group,
 2234:                                         'delete');
 2235:         }
 2236:     }
 2237:     return $result;
 2238: }
 2239: 
 2240: # ------------------------------------------------------------------------- Log
 2241: 
 2242: sub log {
 2243:     my ($dom,$nam,$hom,$what)=@_;
 2244:     return critical("log:$dom:$nam:$what",$hom);
 2245: }
 2246: 
 2247: # ------------------------------------------------------------------ Course Log
 2248: #
 2249: # This routine flushes several buffers of non-mission-critical nature
 2250: #
 2251: 
 2252: sub flushcourselogs {
 2253:     &logthis('Flushing log buffers');
 2254: #
 2255: # course logs
 2256: # This is a log of all transactions in a course, which can be used
 2257: # for data mining purposes
 2258: #
 2259: # It also collects the courseid database, which lists last transaction
 2260: # times and course titles for all courseids
 2261: #
 2262:     my %courseidbuffer=();
 2263:     foreach my $crsid (keys(%courselogs)) {
 2264:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2265: 		          &escape($courselogs{$crsid}),
 2266: 		          $coursehombuf{$crsid}) eq 'ok') {
 2267: 	    delete $courselogs{$crsid};
 2268:         } else {
 2269:             &logthis('Failed to flush log buffer for '.$crsid);
 2270:             if (length($courselogs{$crsid})>40000) {
 2271:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2272:                         " exceeded maximum size, deleting.</font>");
 2273:                delete $courselogs{$crsid};
 2274:             }
 2275:         }
 2276:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2277:             'description' => $coursedescrbuf{$crsid},
 2278:             'inst_code'    => $courseinstcodebuf{$crsid},
 2279:             'type'        => $coursetypebuf{$crsid},
 2280:             'owner'       => $courseownerbuf{$crsid},
 2281:         };
 2282:     }
 2283: #
 2284: # Write course id database (reverse lookup) to homeserver of courses 
 2285: # Is used in pickcourse
 2286: #
 2287:     foreach my $crs_home (keys(%courseidbuffer)) {
 2288:         my $response = &courseidput(&host_domain($crs_home),
 2289:                                     $courseidbuffer{$crs_home},
 2290:                                     $crs_home,'timeonly');
 2291:     }
 2292: #
 2293: # File accesses
 2294: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2295: #
 2296:     foreach my $entry (keys(%accesshash)) {
 2297:         if ($entry =~ /___count$/) {
 2298:             my ($dom,$name);
 2299:             ($dom,$name,undef)=
 2300: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2301:             if (! defined($dom) || $dom eq '' || 
 2302:                 ! defined($name) || $name eq '') {
 2303:                 my $cid = $env{'request.course.id'};
 2304:                 $dom  = $env{'request.'.$cid.'.domain'};
 2305:                 $name = $env{'request.'.$cid.'.num'};
 2306:             }
 2307:             my $value = $accesshash{$entry};
 2308:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2309:             my %temphash=($url => $value);
 2310:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2311:             if ($result eq 'ok') {
 2312:                 delete $accesshash{$entry};
 2313:             } elsif ($result eq 'unknown_cmd') {
 2314:                 # Target server has old code running on it.
 2315:                 my %temphash=($entry => $value);
 2316:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2317:                     delete $accesshash{$entry};
 2318:                 }
 2319:             }
 2320:         } else {
 2321:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2322:             my %temphash=($entry => $accesshash{$entry});
 2323:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2324:                 delete $accesshash{$entry};
 2325:             }
 2326:         }
 2327:     }
 2328: #
 2329: # Roles
 2330: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2331: #
 2332:     foreach my $entry (keys(%userrolehash)) {
 2333:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2334: 	    split(/\:/,$entry);
 2335:         if (&Apache::lonnet::put('nohist_userroles',
 2336:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2337:                 $rudom,$runame) eq 'ok') {
 2338: 	    delete $userrolehash{$entry};
 2339:         }
 2340:     }
 2341: #
 2342: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2343: #
 2344:     my %domrolebuffer = ();
 2345:     foreach my $entry (keys %domainrolehash) {
 2346:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2347:         if ($domrolebuffer{$rudom}) {
 2348:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2349:                       '='.&escape($domainrolehash{$entry});
 2350:         } else {
 2351:             $domrolebuffer{$rudom}.=&escape($entry).
 2352:                       '='.&escape($domainrolehash{$entry});
 2353:         }
 2354:         delete $domainrolehash{$entry};
 2355:     }
 2356:     foreach my $dom (keys(%domrolebuffer)) {
 2357: 	my %servers = &get_servers($dom,'library');
 2358: 	foreach my $tryserver (keys(%servers)) {
 2359: 	    unless (&reply('domroleput:'.$dom.':'.
 2360: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2361: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2362: 	    }
 2363:         }
 2364:     }
 2365:     $dumpcount++;
 2366: }
 2367: 
 2368: sub courselog {
 2369:     my $what=shift;
 2370:     $what=time.':'.$what;
 2371:     unless ($env{'request.course.id'}) { return ''; }
 2372:     $coursedombuf{$env{'request.course.id'}}=
 2373:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2374:     $coursenumbuf{$env{'request.course.id'}}=
 2375:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2376:     $coursehombuf{$env{'request.course.id'}}=
 2377:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2378:     $coursedescrbuf{$env{'request.course.id'}}=
 2379:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2380:     $courseinstcodebuf{$env{'request.course.id'}}=
 2381:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2382:     $courseownerbuf{$env{'request.course.id'}}=
 2383:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2384:     $coursetypebuf{$env{'request.course.id'}}=
 2385:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2386:     if (defined $courselogs{$env{'request.course.id'}}) {
 2387: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2388:     } else {
 2389: 	$courselogs{$env{'request.course.id'}}.=$what;
 2390:     }
 2391:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2392: 	&flushcourselogs();
 2393:     }
 2394: }
 2395: 
 2396: sub courseacclog {
 2397:     my $fnsymb=shift;
 2398:     unless ($env{'request.course.id'}) { return ''; }
 2399:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2400:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2401:         $what.=':POST';
 2402:         # FIXME: Probably ought to escape things....
 2403: 	foreach my $key (keys(%env)) {
 2404:             if ($key=~/^form\.(.*)/) {
 2405: 		$what.=':'.$1.'='.$env{$key};
 2406:             }
 2407:         }
 2408:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2409:         # FIXME: We should not be depending on a form parameter that someone
 2410:         # editing lonsearchcat.pm might change in the future.
 2411:         if ($env{'form.phase'} eq 'course_search') {
 2412:             $what.= ':POST';
 2413:             # FIXME: Probably ought to escape things....
 2414:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2415:                                  'crsdiscuss') {
 2416:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2417:             }
 2418:         }
 2419:     }
 2420:     &courselog($what);
 2421: }
 2422: 
 2423: sub countacc {
 2424:     my $url=&declutter(shift);
 2425:     return if (! defined($url) || $url eq '');
 2426:     unless ($env{'request.course.id'}) { return ''; }
 2427:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2428:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2429:     $accesshash{$key}++;
 2430: }
 2431: 
 2432: sub linklog {
 2433:     my ($from,$to)=@_;
 2434:     $from=&declutter($from);
 2435:     $to=&declutter($to);
 2436:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2437:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2438: }
 2439:   
 2440: sub userrolelog {
 2441:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2442:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2443:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2444:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2445:         ($trole=~/^ta/)) {
 2446:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2447:        $userrolehash
 2448:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2449:                     =$tend.':'.$tstart;
 2450:     }
 2451:     if (($env{'request.role'} =~ /dc\./) &&
 2452: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2453: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2454: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2455:        $userrolehash
 2456:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2457:                     =$tend.':'.$tstart;
 2458:     }
 2459:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2460:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2461:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2462:         ($trole=~/^sc/)) {
 2463:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2464:        $domainrolehash
 2465:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2466:                     = $tend.':'.$tstart;
 2467:     }
 2468: }
 2469: 
 2470: sub get_course_adv_roles {
 2471:     my ($cid,$codes) = @_;
 2472:     $cid=$env{'request.course.id'} unless (defined($cid));
 2473:     my %coursehash=&coursedescription($cid);
 2474:     my %nothide=();
 2475:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2476:         if ($user !~ /:/) {
 2477: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2478:         } else {
 2479:             $nothide{$user}=1;
 2480:         }
 2481:     }
 2482:     my %returnhash=();
 2483:     my %dumphash=
 2484:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2485:     my $now=time;
 2486:     foreach my $entry (keys %dumphash) {
 2487: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2488:         if (($tstart) && ($tstart<0)) { next; }
 2489:         if (($tend) && ($tend<$now)) { next; }
 2490:         if (($tstart) && ($now<$tstart)) { next; }
 2491:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2492: 	if ($username eq '' || $domain eq '') { next; }
 2493: 	if ((&privileged($username,$domain)) && 
 2494: 	    (!$nothide{$username.':'.$domain})) { next; }
 2495: 	if ($role eq 'cr') { next; }
 2496:         if ($codes) {
 2497:             if ($section) { $role .= ':'.$section; }
 2498:             if ($returnhash{$role}) {
 2499:                 $returnhash{$role}.=','.$username.':'.$domain;
 2500:             } else {
 2501:                 $returnhash{$role}=$username.':'.$domain;
 2502:             }
 2503:         } else {
 2504:             my $key=&plaintext($role);
 2505:             if ($section) { $key.=' (Section '.$section.')'; }
 2506:             if ($returnhash{$key}) {
 2507: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2508:             } else {
 2509:                 $returnhash{$key}=$username.':'.$domain;
 2510:             }
 2511:         }
 2512:     }
 2513:     return %returnhash;
 2514: }
 2515: 
 2516: sub get_my_roles {
 2517:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2518:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2519:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2520:     my (%dumphash,%nothide);
 2521:     if ($context eq 'userroles') { 
 2522:         %dumphash = &dump('roles',$udom,$uname);
 2523:     } else {
 2524:         %dumphash=
 2525:             &dump('nohist_userroles',$udom,$uname);
 2526:         if ($hidepriv) {
 2527:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2528:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2529:                 if ($user !~ /:/) {
 2530:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2531:                 } else {
 2532:                     $nothide{$user} = 1;
 2533:                 }
 2534:             }
 2535:         }
 2536:     }
 2537:     my %returnhash=();
 2538:     my $now=time;
 2539:     foreach my $entry (keys(%dumphash)) {
 2540:         my ($role,$tend,$tstart);
 2541:         if ($context eq 'userroles') {
 2542: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2543:         } else {
 2544:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2545:         }
 2546:         if (($tstart) && ($tstart<0)) { next; }
 2547:         my $status = 'active';
 2548:         if (($tend) && ($tend<=$now)) {
 2549:             $status = 'previous';
 2550:         } 
 2551:         if (($tstart) && ($now<$tstart)) {
 2552:             $status = 'future';
 2553:         }
 2554:         if (ref($types) eq 'ARRAY') {
 2555:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2556:                 next;
 2557:             } 
 2558:         } else {
 2559:             if ($status ne 'active') {
 2560:                 next;
 2561:             }
 2562:         }
 2563:         my ($rolecode,$username,$domain,$section,$area);
 2564:         if ($context eq 'userroles') {
 2565:             ($area,$rolecode) = split(/_/,$entry);
 2566:             (undef,$domain,$username,$section) = split(/\//,$area);
 2567:         } else {
 2568:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2569:         }
 2570:         if (ref($roledoms) eq 'ARRAY') {
 2571:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2572:                 next;
 2573:             }
 2574:         }
 2575:         if (ref($roles) eq 'ARRAY') {
 2576:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2577:                 if ($role =~ /^cr\//) {
 2578:                     if (!grep(/^cr$/,@{$roles})) {
 2579:                         next;
 2580:                     }
 2581:                 } else {
 2582:                     next;
 2583:                 }
 2584:             }
 2585:         }
 2586:         if ($hidepriv) {
 2587:             if ((&privileged($username,$domain)) &&
 2588:                 (!$nothide{$username.':'.$domain})) { 
 2589:                 next;
 2590:             }
 2591:         }
 2592:         if ($withsec) {
 2593:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2594:                 $tstart.':'.$tend;
 2595:         } else {
 2596:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2597:         }
 2598:     }
 2599:     return %returnhash;
 2600: }
 2601: 
 2602: # ----------------------------------------------------- Frontpage Announcements
 2603: #
 2604: #
 2605: 
 2606: sub postannounce {
 2607:     my ($server,$text)=@_;
 2608:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2609:     unless ($text=~/\w/) { $text=''; }
 2610:     return &reply('setannounce:'.&escape($text),$server);
 2611: }
 2612: 
 2613: sub getannounce {
 2614: 
 2615:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2616: 	my $announcement='';
 2617: 	while (my $line = <$fh>) { $announcement .= $line; }
 2618: 	close($fh);
 2619: 	if ($announcement=~/\w/) { 
 2620: 	    return 
 2621:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2622:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2623: 	} else {
 2624: 	    return '';
 2625: 	}
 2626:     } else {
 2627: 	return '';
 2628:     }
 2629: }
 2630: 
 2631: # ---------------------------------------------------------- Course ID routines
 2632: # Deal with domain's nohist_courseid.db files
 2633: #
 2634: 
 2635: sub courseidput {
 2636:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2637:     my $outcome;
 2638:     if ($caller eq 'timeonly') {
 2639:         my $cids = '';
 2640:         foreach my $item (keys(%$storehash)) {
 2641:             $cids.=&escape($item).'&';
 2642:         }
 2643:         $cids=~s/\&$//;
 2644:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2645:                           $coursehome);       
 2646:     } else {
 2647:         my $items = '';
 2648:         foreach my $item (keys(%$storehash)) {
 2649:             $items.= &escape($item).'='.
 2650:                      &freeze_escape($$storehash{$item}).'&';
 2651:         }
 2652:         $items=~s/\&$//;
 2653:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2654:                           $coursehome);
 2655:     }
 2656:     if ($outcome eq 'unknown_cmd') {
 2657:         my $what;
 2658:         foreach my $cid (keys(%$storehash)) {
 2659:             $what .= &escape($cid).'=';
 2660:             foreach my $item ('description','inst_code','owner','type') {
 2661:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2662:             }
 2663:             $what =~ s/\:$/&/;
 2664:         }
 2665:         $what =~ s/\&$//;  
 2666:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2667:     } else {
 2668:         return $outcome;
 2669:     }
 2670: }
 2671: 
 2672: sub courseiddump {
 2673:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2674:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2675:         $selfenrollonly)=@_;
 2676:     my $as_hash = 1;
 2677:     my %returnhash;
 2678:     if (!$domfilter) { $domfilter=''; }
 2679:     my %libserv = &all_library();
 2680:     foreach my $tryserver (keys(%libserv)) {
 2681:         if ( (  $hostidflag == 1 
 2682: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2683: 	     || (!defined($hostidflag)) ) {
 2684: 
 2685: 	    if (($domfilter eq '') ||
 2686: 		(&host_domain($tryserver) eq $domfilter)) {
 2687:                 my $rep = 
 2688:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2689:                          $sincefilter.':'.&escape($descfilter).':'.
 2690:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2691:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2692:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2693:                          &escape($selfenrollonly),$tryserver);
 2694:                 my @pairs=split(/\&/,$rep);
 2695:                 foreach my $item (@pairs) {
 2696:                     my ($key,$value)=split(/\=/,$item,2);
 2697:                     $key = &unescape($key);
 2698:                     next if ($key =~ /^error: 2 /);
 2699:                     my $result = &thaw_unescape($value);
 2700:                     if (ref($result) eq 'HASH') {
 2701:                         $returnhash{$key}=$result;
 2702:                     } else {
 2703:                         my @responses = split(/:/,$value);
 2704:                         my @items = ('description','inst_code','owner','type');
 2705:                         for (my $i=0; $i<@responses; $i++) {
 2706:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2707:                         }
 2708:                     } 
 2709:                 }
 2710:             }
 2711:         }
 2712:     }
 2713:     return %returnhash;
 2714: }
 2715: 
 2716: # ---------------------------------------------------------- DC e-mail
 2717: 
 2718: sub dcmailput {
 2719:     my ($domain,$msgid,$message,$server)=@_;
 2720:     my $status = &Apache::lonnet::critical(
 2721:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2722:        &escape($message),$server);
 2723:     return $status;
 2724: }
 2725: 
 2726: sub dcmaildump {
 2727:     my ($dom,$startdate,$enddate,$senders) = @_;
 2728:     my %returnhash=();
 2729: 
 2730:     if (defined(&domain($dom,'primary'))) {
 2731:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2732:                                                          &escape($enddate).':';
 2733: 	my @esc_senders=map { &escape($_)} @$senders;
 2734: 	$cmd.=&escape(join('&',@esc_senders));
 2735: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2736:             my ($key,$value) = split(/\=/,$line,2);
 2737:             if (($key) && ($value)) {
 2738:                 $returnhash{&unescape($key)} = &unescape($value);
 2739:             }
 2740:         }
 2741:     }
 2742:     return %returnhash;
 2743: }
 2744: # ---------------------------------------------------------- Domain roles
 2745: 
 2746: sub get_domain_roles {
 2747:     my ($dom,$roles,$startdate,$enddate)=@_;
 2748:     if (undef($startdate) || $startdate eq '') {
 2749:         $startdate = '.';
 2750:     }
 2751:     if (undef($enddate) || $enddate eq '') {
 2752:         $enddate = '.';
 2753:     }
 2754:     my $rolelist;
 2755:     if (ref($roles) eq 'ARRAY') {
 2756:         $rolelist = join(':',@{$roles});
 2757:     }
 2758:     my %personnel = ();
 2759: 
 2760:     my %servers = &get_servers($dom,'library');
 2761:     foreach my $tryserver (keys(%servers)) {
 2762: 	%{$personnel{$tryserver}}=();
 2763: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2764: 					    &escape($startdate).':'.
 2765: 					    &escape($enddate).':'.
 2766: 					    &escape($rolelist), $tryserver))) {
 2767: 	    my ($key,$value) = split(/\=/,$line,2);
 2768: 	    if (($key) && ($value)) {
 2769: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2770: 	    }
 2771: 	}
 2772:     }
 2773:     return %personnel;
 2774: }
 2775: 
 2776: # ----------------------------------------------------------- Check out an item
 2777: 
 2778: sub get_first_access {
 2779:     my ($type,$argsymb)=@_;
 2780:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2781:     if ($argsymb) { $symb=$argsymb; }
 2782:     my ($map,$id,$res)=&decode_symb($symb);
 2783:     if ($type eq 'course') {
 2784: 	$res='course';
 2785:     } elsif ($type eq 'map') {
 2786: 	$res=&symbread($map);
 2787:     } else {
 2788: 	$res=$symb;
 2789:     }
 2790:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2791:     return $times{"$courseid\0$res"};
 2792: }
 2793: 
 2794: sub set_first_access {
 2795:     my ($type)=@_;
 2796:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2797:     my ($map,$id,$res)=&decode_symb($symb);
 2798:     if ($type eq 'course') {
 2799: 	$res='course';
 2800:     } elsif ($type eq 'map') {
 2801: 	$res=&symbread($map);
 2802:     } else {
 2803: 	$res=$symb;
 2804:     }
 2805:     my $firstaccess=&get_first_access($type,$symb);
 2806:     if (!$firstaccess) {
 2807: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2808:     }
 2809:     return 'already_set';
 2810: }
 2811: 
 2812: sub checkout {
 2813:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2814:     my $now=time;
 2815:     my $lonhost=$perlvar{'lonHostID'};
 2816:     my $infostr=&escape(
 2817:                  'CHECKOUTTOKEN&'.
 2818:                  $tuname.'&'.
 2819:                  $tudom.'&'.
 2820:                  $tcrsid.'&'.
 2821:                  $symb.'&'.
 2822: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2823:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2824:     if ($token=~/^error\:/) { 
 2825:         &logthis("<font color=\"blue\">WARNING: ".
 2826:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2827:                  "</font>");
 2828:         return ''; 
 2829:     }
 2830: 
 2831:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2832:     $token=~tr/a-z/A-Z/;
 2833: 
 2834:     my %infohash=('resource.0.outtoken' => $token,
 2835:                   'resource.0.checkouttime' => $now,
 2836:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2837: 
 2838:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2839:        return '';
 2840:     } else {
 2841:         &logthis("<font color=\"blue\">WARNING: ".
 2842:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2843:                  "</font>");
 2844:     }    
 2845: 
 2846:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2847:                          &escape('Checkout '.$infostr.' - '.
 2848:                                                  $token)) ne 'ok') {
 2849: 	return '';
 2850:     } else {
 2851:         &logthis("<font color=\"blue\">WARNING: ".
 2852:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2853:                  "</font>");
 2854:     }
 2855:     return $token;
 2856: }
 2857: 
 2858: # ------------------------------------------------------------ Check in an item
 2859: 
 2860: sub checkin {
 2861:     my $token=shift;
 2862:     my $now=time;
 2863:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2864:     $lonhost=~tr/A-Z/a-z/;
 2865:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2866:     $dtoken=~s/\W/\_/g;
 2867:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2868:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2869: 
 2870:     unless (($tuname) && ($tudom)) {
 2871:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2872:         return '';
 2873:     }
 2874:     
 2875:     unless (&allowed('mgr',$tcrsid)) {
 2876:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2877:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2878:         return '';
 2879:     }
 2880: 
 2881:     my %infohash=('resource.0.intoken' => $token,
 2882:                   'resource.0.checkintime' => $now,
 2883:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2884: 
 2885:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2886:        return '';
 2887:     }    
 2888: 
 2889:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2890:                          &escape('Checkin - '.$token)) ne 'ok') {
 2891: 	return '';
 2892:     }
 2893: 
 2894:     return ($symb,$tuname,$tudom,$tcrsid);    
 2895: }
 2896: 
 2897: # --------------------------------------------- Set Expire Date for Spreadsheet
 2898: 
 2899: sub expirespread {
 2900:     my ($uname,$udom,$stype,$usymb)=@_;
 2901:     my $cid=$env{'request.course.id'}; 
 2902:     if ($cid) {
 2903:        my $now=time;
 2904:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2905:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2906:                             $env{'course.'.$cid.'.num'}.
 2907: 	        	    ':nohist_expirationdates:'.
 2908:                             &escape($key).'='.$now,
 2909:                             $env{'course.'.$cid.'.home'})
 2910:     }
 2911:     return 'ok';
 2912: }
 2913: 
 2914: # ----------------------------------------------------- Devalidate Spreadsheets
 2915: 
 2916: sub devalidate {
 2917:     my ($symb,$uname,$udom)=@_;
 2918:     my $cid=$env{'request.course.id'}; 
 2919:     if ($cid) {
 2920:         # delete the stored spreadsheets for
 2921:         # - the student level sheet of this user in course's homespace
 2922:         # - the assessment level sheet for this resource 
 2923:         #   for this user in user's homespace
 2924: 	# - current conditional state info
 2925: 	my $key=$uname.':'.$udom.':';
 2926:         my $status=
 2927: 	    &del('nohist_calculatedsheets',
 2928: 		 [$key.'studentcalc:'],
 2929: 		 $env{'course.'.$cid.'.domain'},
 2930: 		 $env{'course.'.$cid.'.num'})
 2931: 		.' '.
 2932: 	    &del('nohist_calculatedsheets_'.$cid,
 2933: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2934:         unless ($status eq 'ok ok') {
 2935:            &logthis('Could not devalidate spreadsheet '.
 2936:                     $uname.' at '.$udom.' for '.
 2937: 		    $symb.': '.$status);
 2938:         }
 2939: 	&delenv('user.state.'.$cid);
 2940:     }
 2941: }
 2942: 
 2943: sub get_scalar {
 2944:     my ($string,$end) = @_;
 2945:     my $value;
 2946:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2947: 	$value = $1;
 2948:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2949: 	$value = $1;
 2950:     }
 2951:     return &unescape($value);
 2952: }
 2953: 
 2954: sub array2str {
 2955:   my (@array) = @_;
 2956:   my $result=&arrayref2str(\@array);
 2957:   $result=~s/^__ARRAY_REF__//;
 2958:   $result=~s/__END_ARRAY_REF__$//;
 2959:   return $result;
 2960: }
 2961: 
 2962: sub arrayref2str {
 2963:   my ($arrayref) = @_;
 2964:   my $result='__ARRAY_REF__';
 2965:   foreach my $elem (@$arrayref) {
 2966:     if(ref($elem) eq 'ARRAY') {
 2967:       $result.=&arrayref2str($elem).'&';
 2968:     } elsif(ref($elem) eq 'HASH') {
 2969:       $result.=&hashref2str($elem).'&';
 2970:     } elsif(ref($elem)) {
 2971:       #print("Got a ref of ".(ref($elem))." skipping.");
 2972:     } else {
 2973:       $result.=&escape($elem).'&';
 2974:     }
 2975:   }
 2976:   $result=~s/\&$//;
 2977:   $result .= '__END_ARRAY_REF__';
 2978:   return $result;
 2979: }
 2980: 
 2981: sub hash2str {
 2982:   my (%hash) = @_;
 2983:   my $result=&hashref2str(\%hash);
 2984:   $result=~s/^__HASH_REF__//;
 2985:   $result=~s/__END_HASH_REF__$//;
 2986:   return $result;
 2987: }
 2988: 
 2989: sub hashref2str {
 2990:   my ($hashref)=@_;
 2991:   my $result='__HASH_REF__';
 2992:   foreach my $key (sort(keys(%$hashref))) {
 2993:     if (ref($key) eq 'ARRAY') {
 2994:       $result.=&arrayref2str($key).'=';
 2995:     } elsif (ref($key) eq 'HASH') {
 2996:       $result.=&hashref2str($key).'=';
 2997:     } elsif (ref($key)) {
 2998:       $result.='=';
 2999:       #print("Got a ref of ".(ref($key))." skipping.");
 3000:     } else {
 3001: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3002:     }
 3003: 
 3004:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3005:       $result.=&arrayref2str($hashref->{$key}).'&';
 3006:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3007:       $result.=&hashref2str($hashref->{$key}).'&';
 3008:     } elsif(ref($hashref->{$key})) {
 3009:        $result.='&';
 3010:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3011:     } else {
 3012:       $result.=&escape($hashref->{$key}).'&';
 3013:     }
 3014:   }
 3015:   $result=~s/\&$//;
 3016:   $result .= '__END_HASH_REF__';
 3017:   return $result;
 3018: }
 3019: 
 3020: sub str2hash {
 3021:     my ($string)=@_;
 3022:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3023:     return %$hash;
 3024: }
 3025: 
 3026: sub str2hashref {
 3027:   my ($string) = @_;
 3028: 
 3029:   my %hash;
 3030: 
 3031:   if($string !~ /^__HASH_REF__/) {
 3032:       if (! ($string eq '' || !defined($string))) {
 3033: 	  $hash{'error'}='Not hash reference';
 3034:       }
 3035:       return (\%hash, $string);
 3036:   }
 3037: 
 3038:   $string =~ s/^__HASH_REF__//;
 3039: 
 3040:   while($string !~ /^__END_HASH_REF__/) {
 3041:       #key
 3042:       my $key='';
 3043:       if($string =~ /^__HASH_REF__/) {
 3044:           ($key, $string)=&str2hashref($string);
 3045:           if(defined($key->{'error'})) {
 3046:               $hash{'error'}='Bad data';
 3047:               return (\%hash, $string);
 3048:           }
 3049:       } elsif($string =~ /^__ARRAY_REF__/) {
 3050:           ($key, $string)=&str2arrayref($string);
 3051:           if($key->[0] eq 'Array reference error') {
 3052:               $hash{'error'}='Bad data';
 3053:               return (\%hash, $string);
 3054:           }
 3055:       } else {
 3056:           $string =~ s/^(.*?)=//;
 3057: 	  $key=&unescape($1);
 3058:       }
 3059:       $string =~ s/^=//;
 3060: 
 3061:       #value
 3062:       my $value='';
 3063:       if($string =~ /^__HASH_REF__/) {
 3064:           ($value, $string)=&str2hashref($string);
 3065:           if(defined($value->{'error'})) {
 3066:               $hash{'error'}='Bad data';
 3067:               return (\%hash, $string);
 3068:           }
 3069:       } elsif($string =~ /^__ARRAY_REF__/) {
 3070:           ($value, $string)=&str2arrayref($string);
 3071:           if($value->[0] eq 'Array reference error') {
 3072:               $hash{'error'}='Bad data';
 3073:               return (\%hash, $string);
 3074:           }
 3075:       } else {
 3076: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3077:       }
 3078:       $string =~ s/^&//;
 3079: 
 3080:       $hash{$key}=$value;
 3081:   }
 3082: 
 3083:   $string =~ s/^__END_HASH_REF__//;
 3084: 
 3085:   return (\%hash, $string);
 3086: }
 3087: 
 3088: sub str2array {
 3089:     my ($string)=@_;
 3090:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3091:     return @$array;
 3092: }
 3093: 
 3094: sub str2arrayref {
 3095:   my ($string) = @_;
 3096:   my @array;
 3097: 
 3098:   if($string !~ /^__ARRAY_REF__/) {
 3099:       if (! ($string eq '' || !defined($string))) {
 3100: 	  $array[0]='Array reference error';
 3101:       }
 3102:       return (\@array, $string);
 3103:   }
 3104: 
 3105:   $string =~ s/^__ARRAY_REF__//;
 3106: 
 3107:   while($string !~ /^__END_ARRAY_REF__/) {
 3108:       my $value='';
 3109:       if($string =~ /^__HASH_REF__/) {
 3110:           ($value, $string)=&str2hashref($string);
 3111:           if(defined($value->{'error'})) {
 3112:               $array[0] ='Array reference error';
 3113:               return (\@array, $string);
 3114:           }
 3115:       } elsif($string =~ /^__ARRAY_REF__/) {
 3116:           ($value, $string)=&str2arrayref($string);
 3117:           if($value->[0] eq 'Array reference error') {
 3118:               $array[0] ='Array reference error';
 3119:               return (\@array, $string);
 3120:           }
 3121:       } else {
 3122: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3123:       }
 3124:       $string =~ s/^&//;
 3125: 
 3126:       push(@array, $value);
 3127:   }
 3128: 
 3129:   $string =~ s/^__END_ARRAY_REF__//;
 3130: 
 3131:   return (\@array, $string);
 3132: }
 3133: 
 3134: # -------------------------------------------------------------------Temp Store
 3135: 
 3136: sub tmpreset {
 3137:   my ($symb,$namespace,$domain,$stuname) = @_;
 3138:   if (!$symb) {
 3139:     $symb=&symbread();
 3140:     if (!$symb) { $symb= $env{'request.url'}; }
 3141:   }
 3142:   $symb=escape($symb);
 3143: 
 3144:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3145:   $namespace=~s/\//\_/g;
 3146:   $namespace=~s/\W//g;
 3147: 
 3148:   if (!$domain) { $domain=$env{'user.domain'}; }
 3149:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3150:   if ($domain eq 'public' && $stuname eq 'public') {
 3151:       $stuname=$ENV{'REMOTE_ADDR'};
 3152:   }
 3153:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3154:   my %hash;
 3155:   if (tie(%hash,'GDBM_File',
 3156: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3157: 	  &GDBM_WRCREAT(),0640)) {
 3158:     foreach my $key (keys %hash) {
 3159:       if ($key=~ /:$symb/) {
 3160: 	delete($hash{$key});
 3161:       }
 3162:     }
 3163:   }
 3164: }
 3165: 
 3166: sub tmpstore {
 3167:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3168: 
 3169:   if (!$symb) {
 3170:     $symb=&symbread();
 3171:     if (!$symb) { $symb= $env{'request.url'}; }
 3172:   }
 3173:   $symb=escape($symb);
 3174: 
 3175:   if (!$namespace) {
 3176:     # I don't think we would ever want to store this for a course.
 3177:     # it seems this will only be used if we don't have a course.
 3178:     #$namespace=$env{'request.course.id'};
 3179:     #if (!$namespace) {
 3180:       $namespace=$env{'request.state'};
 3181:     #}
 3182:   }
 3183:   $namespace=~s/\//\_/g;
 3184:   $namespace=~s/\W//g;
 3185:   if (!$domain) { $domain=$env{'user.domain'}; }
 3186:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3187:   if ($domain eq 'public' && $stuname eq 'public') {
 3188:       $stuname=$ENV{'REMOTE_ADDR'};
 3189:   }
 3190:   my $now=time;
 3191:   my %hash;
 3192:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3193:   if (tie(%hash,'GDBM_File',
 3194: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3195: 	  &GDBM_WRCREAT(),0640)) {
 3196:     $hash{"version:$symb"}++;
 3197:     my $version=$hash{"version:$symb"};
 3198:     my $allkeys=''; 
 3199:     foreach my $key (keys(%$storehash)) {
 3200:       $allkeys.=$key.':';
 3201:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3202:     }
 3203:     $hash{"$version:$symb:timestamp"}=$now;
 3204:     $allkeys.='timestamp';
 3205:     $hash{"$version:keys:$symb"}=$allkeys;
 3206:     if (untie(%hash)) {
 3207:       return 'ok';
 3208:     } else {
 3209:       return "error:$!";
 3210:     }
 3211:   } else {
 3212:     return "error:$!";
 3213:   }
 3214: }
 3215: 
 3216: # -----------------------------------------------------------------Temp Restore
 3217: 
 3218: sub tmprestore {
 3219:   my ($symb,$namespace,$domain,$stuname) = @_;
 3220: 
 3221:   if (!$symb) {
 3222:     $symb=&symbread();
 3223:     if (!$symb) { $symb= $env{'request.url'}; }
 3224:   }
 3225:   $symb=escape($symb);
 3226: 
 3227:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3228: 
 3229:   if (!$domain) { $domain=$env{'user.domain'}; }
 3230:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3231:   if ($domain eq 'public' && $stuname eq 'public') {
 3232:       $stuname=$ENV{'REMOTE_ADDR'};
 3233:   }
 3234:   my %returnhash;
 3235:   $namespace=~s/\//\_/g;
 3236:   $namespace=~s/\W//g;
 3237:   my %hash;
 3238:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3239:   if (tie(%hash,'GDBM_File',
 3240: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3241: 	  &GDBM_READER(),0640)) {
 3242:     my $version=$hash{"version:$symb"};
 3243:     $returnhash{'version'}=$version;
 3244:     my $scope;
 3245:     for ($scope=1;$scope<=$version;$scope++) {
 3246:       my $vkeys=$hash{"$scope:keys:$symb"};
 3247:       my @keys=split(/:/,$vkeys);
 3248:       my $key;
 3249:       $returnhash{"$scope:keys"}=$vkeys;
 3250:       foreach $key (@keys) {
 3251: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3252: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3253:       }
 3254:     }
 3255:     if (!(untie(%hash))) {
 3256:       return "error:$!";
 3257:     }
 3258:   } else {
 3259:     return "error:$!";
 3260:   }
 3261:   return %returnhash;
 3262: }
 3263: 
 3264: # ----------------------------------------------------------------------- Store
 3265: 
 3266: sub store {
 3267:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3268:     my $home='';
 3269: 
 3270:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3271: 
 3272:     $symb=&symbclean($symb);
 3273:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3274: 
 3275:     if (!$domain) { $domain=$env{'user.domain'}; }
 3276:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3277: 
 3278:     &devalidate($symb,$stuname,$domain);
 3279: 
 3280:     $symb=escape($symb);
 3281:     if (!$namespace) { 
 3282:        unless ($namespace=$env{'request.course.id'}) { 
 3283:           return ''; 
 3284:        } 
 3285:     }
 3286:     if (!$home) { $home=$env{'user.home'}; }
 3287: 
 3288:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3289:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3290: 
 3291:     my $namevalue='';
 3292:     foreach my $key (keys(%$storehash)) {
 3293:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3294:     }
 3295:     $namevalue=~s/\&$//;
 3296:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3297:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3298: }
 3299: 
 3300: # -------------------------------------------------------------- Critical Store
 3301: 
 3302: sub cstore {
 3303:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3304:     my $home='';
 3305: 
 3306:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3307: 
 3308:     $symb=&symbclean($symb);
 3309:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3310: 
 3311:     if (!$domain) { $domain=$env{'user.domain'}; }
 3312:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3313: 
 3314:     &devalidate($symb,$stuname,$domain);
 3315: 
 3316:     $symb=escape($symb);
 3317:     if (!$namespace) { 
 3318:        unless ($namespace=$env{'request.course.id'}) { 
 3319:           return ''; 
 3320:        } 
 3321:     }
 3322:     if (!$home) { $home=$env{'user.home'}; }
 3323: 
 3324:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3325:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3326: 
 3327:     my $namevalue='';
 3328:     foreach my $key (keys(%$storehash)) {
 3329:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3330:     }
 3331:     $namevalue=~s/\&$//;
 3332:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3333:     return critical
 3334:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3335: }
 3336: 
 3337: # --------------------------------------------------------------------- Restore
 3338: 
 3339: sub restore {
 3340:     my ($symb,$namespace,$domain,$stuname) = @_;
 3341:     my $home='';
 3342: 
 3343:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3344: 
 3345:     if (!$symb) {
 3346:       unless ($symb=escape(&symbread())) { return ''; }
 3347:     } else {
 3348:       $symb=&escape(&symbclean($symb));
 3349:     }
 3350:     if (!$namespace) { 
 3351:        unless ($namespace=$env{'request.course.id'}) { 
 3352:           return ''; 
 3353:        } 
 3354:     }
 3355:     if (!$domain) { $domain=$env{'user.domain'}; }
 3356:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3357:     if (!$home) { $home=$env{'user.home'}; }
 3358:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3359: 
 3360:     my %returnhash=();
 3361:     foreach my $line (split(/\&/,$answer)) {
 3362: 	my ($name,$value)=split(/\=/,$line);
 3363:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3364:     }
 3365:     my $version;
 3366:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3367:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3368:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3369:        }
 3370:     }
 3371:     return %returnhash;
 3372: }
 3373: 
 3374: # ---------------------------------------------------------- Course Description
 3375: 
 3376: sub coursedescription {
 3377:     my ($courseid,$args)=@_;
 3378:     $courseid=~s/^\///;
 3379:     $courseid=~s/\_/\//g;
 3380:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3381:     my $chome=&homeserver($cnum,$cdomain);
 3382:     my $normalid=$cdomain.'_'.$cnum;
 3383:     # need to always cache even if we get errors otherwise we keep 
 3384:     # trying and trying and trying to get the course description.
 3385:     my %envhash=();
 3386:     my %returnhash=();
 3387:     
 3388:     my $expiretime=600;
 3389:     if ($env{'request.course.id'} eq $normalid) {
 3390: 	$expiretime=120;
 3391:     }
 3392: 
 3393:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3394:     if (!$args->{'freshen_cache'}
 3395: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3396: 	foreach my $key (keys(%env)) {
 3397: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3398: 	    my ($setting) = $1;
 3399: 	    $returnhash{$setting} = $env{$key};
 3400: 	}
 3401: 	return %returnhash;
 3402:     }
 3403: 
 3404:     # get the data agin
 3405:     if (!$args->{'one_time'}) {
 3406: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3407:     }
 3408: 
 3409:     if ($chome ne 'no_host') {
 3410:        %returnhash=&dump('environment',$cdomain,$cnum);
 3411:        if (!exists($returnhash{'con_lost'})) {
 3412:            $returnhash{'home'}= $chome;
 3413: 	   $returnhash{'domain'} = $cdomain;
 3414: 	   $returnhash{'num'} = $cnum;
 3415:            if (!defined($returnhash{'type'})) {
 3416:                $returnhash{'type'} = 'Course';
 3417:            }
 3418:            while (my ($name,$value) = each %returnhash) {
 3419:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3420:            }
 3421:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3422:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3423: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3424:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3425:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3426:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3427:        }
 3428:     }
 3429:     if (!$args->{'one_time'}) {
 3430: 	&appenv(\%envhash);
 3431:     }
 3432:     return %returnhash;
 3433: }
 3434: 
 3435: # -------------------------------------------------See if a user is privileged
 3436: 
 3437: sub privileged {
 3438:     my ($username,$domain)=@_;
 3439:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3440: 			&homeserver($username,$domain));
 3441:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3442:     my $now=time;
 3443:     if ($rolesdump ne '') {
 3444:         foreach my $entry (split(/&/,$rolesdump)) {
 3445: 	    if ($entry!~/^rolesdef_/) {
 3446: 		my ($area,$role)=split(/=/,$entry);
 3447: 		$area=~s/\_\w\w$//;
 3448: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3449: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3450: 		    my $active=1;
 3451: 		    if ($tend) {
 3452: 			if ($tend<$now) { $active=0; }
 3453: 		    }
 3454: 		    if ($tstart) {
 3455: 			if ($tstart>$now) { $active=0; }
 3456: 		    }
 3457: 		    if ($active) { return 1; }
 3458: 		}
 3459: 	    }
 3460: 	}
 3461:     }
 3462:     return 0;
 3463: }
 3464: 
 3465: # -------------------------------------------------------- Get user privileges
 3466: 
 3467: sub rolesinit {
 3468:     my ($domain,$username,$authhost)=@_;
 3469:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3470:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3471:     my %allroles=();
 3472:     my %allgroups=();   
 3473:     my $now=time;
 3474:     my %userroles = ('user.login.time' => $now);
 3475:     my $group_privs;
 3476: 
 3477:     if ($rolesdump ne '') {
 3478:         foreach my $entry (split(/&/,$rolesdump)) {
 3479: 	  if ($entry!~/^rolesdef_/) {
 3480:             my ($area,$role)=split(/=/,$entry);
 3481: 	    $area=~s/\_\w\w$//;
 3482:             my ($trole,$tend,$tstart,$group_privs);
 3483: 	    if ($role=~/^cr/) { 
 3484: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3485: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3486: 		    ($tend,$tstart)=split('_',$trest);
 3487: 		} else {
 3488: 		    $trole=$role;
 3489: 		}
 3490:             } elsif ($role =~ m|^gr/|) {
 3491:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3492:                 ($trole,$group_privs) = split(/\//,$trole);
 3493:                 $group_privs = &unescape($group_privs);
 3494: 	    } else {
 3495: 		($trole,$tend,$tstart)=split(/_/,$role);
 3496: 	    }
 3497: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3498: 					 $username);
 3499: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3500:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3501:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3502:             if (($area ne '') && ($trole ne '')) {
 3503: 		my $spec=$trole.'.'.$area;
 3504: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3505: 		if ($trole =~ /^cr\//) {
 3506:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3507:                 } elsif ($trole eq 'gr') {
 3508:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3509: 		} else {
 3510:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3511: 		}
 3512:             }
 3513:           }
 3514:         }
 3515:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3516:         $userroles{'user.adv'}    = $adv;
 3517: 	$userroles{'user.author'} = $author;
 3518:         $env{'user.adv'}=$adv;
 3519:     }
 3520:     return \%userroles;  
 3521: }
 3522: 
 3523: sub set_arearole {
 3524:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3525: # log the associated role with the area
 3526:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3527:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3528: }
 3529: 
 3530: sub custom_roleprivs {
 3531:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3532:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3533:     my $homsvr=homeserver($rauthor,$rdomain);
 3534:     if (&hostname($homsvr) ne '') {
 3535:         my ($rdummy,$roledef)=
 3536:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3537:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3538:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3539:             if (defined($syspriv)) {
 3540:                 $$allroles{'cm./'}.=':'.$syspriv;
 3541:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3542:             }
 3543:             if ($tdomain ne '') {
 3544:                 if (defined($dompriv)) {
 3545:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3546:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3547:                 }
 3548:                 if (($trest ne '') && (defined($coursepriv))) {
 3549:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3550:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3551:                 }
 3552:             }
 3553:         }
 3554:     }
 3555: }
 3556: 
 3557: sub group_roleprivs {
 3558:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3559:     my $access = 1;
 3560:     my $now = time;
 3561:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3562:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3563:     if ($access) {
 3564:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3565:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3566:     }
 3567: }
 3568: 
 3569: sub standard_roleprivs {
 3570:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3571:     if (defined($pr{$trole.':s'})) {
 3572:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3573:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3574:     }
 3575:     if ($tdomain ne '') {
 3576:         if (defined($pr{$trole.':d'})) {
 3577:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3578:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3579:         }
 3580:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3581:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3582:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3583:         }
 3584:     }
 3585: }
 3586: 
 3587: sub set_userprivs {
 3588:     my ($userroles,$allroles,$allgroups) = @_; 
 3589:     my $author=0;
 3590:     my $adv=0;
 3591:     my %grouproles = ();
 3592:     if (keys(%{$allgroups}) > 0) {
 3593:         foreach my $role (keys %{$allroles}) {
 3594:             my ($trole,$area,$sec,$extendedarea);
 3595:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3596:                 $trole = $1;
 3597:                 $area = $2;
 3598:                 $sec = $3;
 3599:                 $extendedarea = $area.$sec;
 3600:                 if (exists($$allgroups{$area})) {
 3601:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3602:                         my $spec = $trole.'.'.$extendedarea;
 3603:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3604:                                                 $$allgroups{$area}{$group};
 3605:                     }
 3606:                 }
 3607:             }
 3608:         }
 3609:     }
 3610:     foreach my $group (keys(%grouproles)) {
 3611:         $$allroles{$group} = $grouproles{$group};
 3612:     }
 3613:     foreach my $role (keys(%{$allroles})) {
 3614:         my %thesepriv;
 3615:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3616:         foreach my $item (split(/:/,$$allroles{$role})) {
 3617:             if ($item ne '') {
 3618:                 my ($privilege,$restrictions)=split(/&/,$item);
 3619:                 if ($restrictions eq '') {
 3620:                     $thesepriv{$privilege}='F';
 3621:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3622:                     $thesepriv{$privilege}.=$restrictions;
 3623:                 }
 3624:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3625:             }
 3626:         }
 3627:         my $thesestr='';
 3628:         foreach my $priv (keys(%thesepriv)) {
 3629: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3630: 	}
 3631:         $userroles->{'user.priv.'.$role} = $thesestr;
 3632:     }
 3633:     return ($author,$adv);
 3634: }
 3635: 
 3636: # --------------------------------------------------------------- get interface
 3637: 
 3638: sub get {
 3639:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3640:    my $items='';
 3641:    foreach my $item (@$storearr) {
 3642:        $items.=&escape($item).'&';
 3643:    }
 3644:    $items=~s/\&$//;
 3645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3646:    if (!$uname) { $uname=$env{'user.name'}; }
 3647:    my $uhome=&homeserver($uname,$udomain);
 3648: 
 3649:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3650:    my @pairs=split(/\&/,$rep);
 3651:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3652:      return @pairs;
 3653:    }
 3654:    my %returnhash=();
 3655:    my $i=0;
 3656:    foreach my $item (@$storearr) {
 3657:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3658:       $i++;
 3659:    }
 3660:    return %returnhash;
 3661: }
 3662: 
 3663: # --------------------------------------------------------------- del interface
 3664: 
 3665: sub del {
 3666:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3667:    my $items='';
 3668:    foreach my $item (@$storearr) {
 3669:        $items.=&escape($item).'&';
 3670:    }
 3671:    $items=~s/\&$//;
 3672:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3673:    if (!$uname) { $uname=$env{'user.name'}; }
 3674:    my $uhome=&homeserver($uname,$udomain);
 3675: 
 3676:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3677: }
 3678: 
 3679: # -------------------------------------------------------------- dump interface
 3680: 
 3681: sub dump {
 3682:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3683:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3684:     if (!$uname) { $uname=$env{'user.name'}; }
 3685:     my $uhome=&homeserver($uname,$udomain);
 3686:     if ($regexp) {
 3687: 	$regexp=&escape($regexp);
 3688:     } else {
 3689: 	$regexp='.';
 3690:     }
 3691:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3692:     my @pairs=split(/\&/,$rep);
 3693:     my %returnhash=();
 3694:     foreach my $item (@pairs) {
 3695: 	my ($key,$value)=split(/=/,$item,2);
 3696: 	$key = &unescape($key);
 3697: 	next if ($key =~ /^error: 2 /);
 3698: 	$returnhash{$key}=&thaw_unescape($value);
 3699:     }
 3700:     return %returnhash;
 3701: }
 3702: 
 3703: # --------------------------------------------------------- dumpstore interface
 3704: 
 3705: sub dumpstore {
 3706:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3707:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3708:    if (!$uname) { $uname=$env{'user.name'}; }
 3709:    my $uhome=&homeserver($uname,$udomain);
 3710:    if ($regexp) {
 3711:        $regexp=&escape($regexp);
 3712:    } else {
 3713:        $regexp='.';
 3714:    }
 3715:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3716:    my @pairs=split(/\&/,$rep);
 3717:    my %returnhash=();
 3718:    foreach my $item (@pairs) {
 3719:        my ($key,$value)=split(/=/,$item,2);
 3720:        next if ($key =~ /^error: 2 /);
 3721:        $returnhash{$key}=&thaw_unescape($value);
 3722:    }
 3723:    return %returnhash;
 3724: }
 3725: 
 3726: # -------------------------------------------------------------- keys interface
 3727: 
 3728: sub getkeys {
 3729:    my ($namespace,$udomain,$uname)=@_;
 3730:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3731:    if (!$uname) { $uname=$env{'user.name'}; }
 3732:    my $uhome=&homeserver($uname,$udomain);
 3733:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3734:    my @keyarray=();
 3735:    foreach my $key (split(/\&/,$rep)) {
 3736:       next if ($key =~ /^error: 2 /);
 3737:       push(@keyarray,&unescape($key));
 3738:    }
 3739:    return @keyarray;
 3740: }
 3741: 
 3742: # --------------------------------------------------------------- currentdump
 3743: sub currentdump {
 3744:    my ($courseid,$sdom,$sname)=@_;
 3745:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3746:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3747:    $sname    = $env{'user.name'}         if (! defined($sname));
 3748:    my $uhome = &homeserver($sname,$sdom);
 3749:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3750:    return if ($rep =~ /^(error:|no_such_host)/);
 3751:    #
 3752:    my %returnhash=();
 3753:    #
 3754:    if ($rep eq "unknown_cmd") { 
 3755:        # an old lond will not know currentdump
 3756:        # Do a dump and make it look like a currentdump
 3757:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3758:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3759:        my %hash = @tmp;
 3760:        @tmp=();
 3761:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3762:    } else {
 3763:        my @pairs=split(/\&/,$rep);
 3764:        foreach my $pair (@pairs) {
 3765:            my ($key,$value)=split(/=/,$pair,2);
 3766:            my ($symb,$param) = split(/:/,$key);
 3767:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3768:                                                         &thaw_unescape($value);
 3769:        }
 3770:    }
 3771:    return %returnhash;
 3772: }
 3773: 
 3774: sub convert_dump_to_currentdump{
 3775:     my %hash = %{shift()};
 3776:     my %returnhash;
 3777:     # Code ripped from lond, essentially.  The only difference
 3778:     # here is the unescaping done by lonnet::dump().  Conceivably
 3779:     # we might run in to problems with parameter names =~ /^v\./
 3780:     while (my ($key,$value) = each(%hash)) {
 3781:         my ($v,$symb,$param) = split(/:/,$key);
 3782: 	$symb  = &unescape($symb);
 3783: 	$param = &unescape($param);
 3784:         next if ($v eq 'version' || $symb eq 'keys');
 3785:         next if (exists($returnhash{$symb}) &&
 3786:                  exists($returnhash{$symb}->{$param}) &&
 3787:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3788:         $returnhash{$symb}->{$param}=$value;
 3789:         $returnhash{$symb}->{'v.'.$param}=$v;
 3790:     }
 3791:     #
 3792:     # Remove all of the keys in the hashes which keep track of
 3793:     # the version of the parameter.
 3794:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3795:         # use a foreach because we are going to delete from the hash.
 3796:         foreach my $key (keys(%$param_hash)) {
 3797:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3798:         }
 3799:     }
 3800:     return \%returnhash;
 3801: }
 3802: 
 3803: # ------------------------------------------------------ critical inc interface
 3804: 
 3805: sub cinc {
 3806:     return &inc(@_,'critical');
 3807: }
 3808: 
 3809: # --------------------------------------------------------------- inc interface
 3810: 
 3811: sub inc {
 3812:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3813:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3814:     if (!$uname) { $uname=$env{'user.name'}; }
 3815:     my $uhome=&homeserver($uname,$udomain);
 3816:     my $items='';
 3817:     if (! ref($store)) {
 3818:         # got a single value, so use that instead
 3819:         $items = &escape($store).'=&';
 3820:     } elsif (ref($store) eq 'SCALAR') {
 3821:         $items = &escape($$store).'=&';        
 3822:     } elsif (ref($store) eq 'ARRAY') {
 3823:         $items = join('=&',map {&escape($_);} @{$store});
 3824:     } elsif (ref($store) eq 'HASH') {
 3825:         while (my($key,$value) = each(%{$store})) {
 3826:             $items.= &escape($key).'='.&escape($value).'&';
 3827:         }
 3828:     }
 3829:     $items=~s/\&$//;
 3830:     if ($critical) {
 3831: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3832:     } else {
 3833: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3834:     }
 3835: }
 3836: 
 3837: # --------------------------------------------------------------- put interface
 3838: 
 3839: sub put {
 3840:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3842:    if (!$uname) { $uname=$env{'user.name'}; }
 3843:    my $uhome=&homeserver($uname,$udomain);
 3844:    my $items='';
 3845:    foreach my $item (keys(%$storehash)) {
 3846:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3847:    }
 3848:    $items=~s/\&$//;
 3849:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3850: }
 3851: 
 3852: # ------------------------------------------------------------ newput interface
 3853: 
 3854: sub newput {
 3855:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3856:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3857:    if (!$uname) { $uname=$env{'user.name'}; }
 3858:    my $uhome=&homeserver($uname,$udomain);
 3859:    my $items='';
 3860:    foreach my $key (keys(%$storehash)) {
 3861:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3862:    }
 3863:    $items=~s/\&$//;
 3864:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3865: }
 3866: 
 3867: # ---------------------------------------------------------  putstore interface
 3868: 
 3869: sub putstore {
 3870:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3871:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3872:    if (!$uname) { $uname=$env{'user.name'}; }
 3873:    my $uhome=&homeserver($uname,$udomain);
 3874:    my $items='';
 3875:    foreach my $key (keys(%$storehash)) {
 3876:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3877:    }
 3878:    $items=~s/\&$//;
 3879:    my $esc_symb=&escape($symb);
 3880:    my $esc_v=&escape($version);
 3881:    my $reply =
 3882:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3883: 	      $uhome);
 3884:    if ($reply eq 'unknown_cmd') {
 3885:        # gfall back to way things use to be done
 3886:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3887: 			    $uname);
 3888:    }
 3889:    return $reply;
 3890: }
 3891: 
 3892: sub old_putstore {
 3893:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3894:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3895:     if (!$uname) { $uname=$env{'user.name'}; }
 3896:     my $uhome=&homeserver($uname,$udomain);
 3897:     my %newstorehash;
 3898:     foreach my $item (keys(%$storehash)) {
 3899: 	my $key = $version.':'.&escape($symb).':'.$item;
 3900: 	$newstorehash{$key} = $storehash->{$item};
 3901:     }
 3902:     my $items='';
 3903:     my %allitems = ();
 3904:     foreach my $item (keys(%newstorehash)) {
 3905: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3906: 	    my $key = $1.':keys:'.$2;
 3907: 	    $allitems{$key} .= $3.':';
 3908: 	}
 3909: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3910:     }
 3911:     foreach my $item (keys(%allitems)) {
 3912: 	$allitems{$item} =~ s/\:$//;
 3913: 	$items.= $item.'='.$allitems{$item}.'&';
 3914:     }
 3915:     $items=~s/\&$//;
 3916:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3917: }
 3918: 
 3919: # ------------------------------------------------------ critical put interface
 3920: 
 3921: sub cput {
 3922:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3923:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3924:    if (!$uname) { $uname=$env{'user.name'}; }
 3925:    my $uhome=&homeserver($uname,$udomain);
 3926:    my $items='';
 3927:    foreach my $item (keys(%$storehash)) {
 3928:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3929:    }
 3930:    $items=~s/\&$//;
 3931:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3932: }
 3933: 
 3934: # -------------------------------------------------------------- eget interface
 3935: 
 3936: sub eget {
 3937:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3938:    my $items='';
 3939:    foreach my $item (@$storearr) {
 3940:        $items.=&escape($item).'&';
 3941:    }
 3942:    $items=~s/\&$//;
 3943:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3944:    if (!$uname) { $uname=$env{'user.name'}; }
 3945:    my $uhome=&homeserver($uname,$udomain);
 3946:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3947:    my @pairs=split(/\&/,$rep);
 3948:    my %returnhash=();
 3949:    my $i=0;
 3950:    foreach my $item (@$storearr) {
 3951:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3952:       $i++;
 3953:    }
 3954:    return %returnhash;
 3955: }
 3956: 
 3957: # ------------------------------------------------------------ tmpput interface
 3958: sub tmpput {
 3959:     my ($storehash,$server,$context)=@_;
 3960:     my $items='';
 3961:     foreach my $item (keys(%$storehash)) {
 3962: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3963:     }
 3964:     $items=~s/\&$//;
 3965:     if (defined($context)) {
 3966:         $items .= ':'.&escape($context);
 3967:     }
 3968:     return &reply("tmpput:$items",$server);
 3969: }
 3970: 
 3971: # ------------------------------------------------------------ tmpget interface
 3972: sub tmpget {
 3973:     my ($token,$server)=@_;
 3974:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3975:     my $rep=&reply("tmpget:$token",$server);
 3976:     my %returnhash;
 3977:     foreach my $item (split(/\&/,$rep)) {
 3978: 	my ($key,$value)=split(/=/,$item);
 3979:         next if ($key =~ /^error: 2 /);
 3980: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3981:     }
 3982:     return %returnhash;
 3983: }
 3984: 
 3985: # ------------------------------------------------------------ tmpget interface
 3986: sub tmpdel {
 3987:     my ($token,$server)=@_;
 3988:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3989:     return &reply("tmpdel:$token",$server);
 3990: }
 3991: 
 3992: # -------------------------------------------------- portfolio access checking
 3993: 
 3994: sub portfolio_access {
 3995:     my ($requrl) = @_;
 3996:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3997:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3998:     if ($result) {
 3999:         my %setters;
 4000:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4001:             my ($startblock,$endblock) =
 4002:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4003:             if ($startblock && $endblock) {
 4004:                 return 'B';
 4005:             }
 4006:         } else {
 4007:             my ($startblock,$endblock) =
 4008:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4009:             if ($startblock && $endblock) {
 4010:                 return 'B';
 4011:             }
 4012:         }
 4013:     }
 4014:     if ($result eq 'ok') {
 4015:        return 'F';
 4016:     } elsif ($result =~ /^[^:]+:guest_/) {
 4017:        return 'A';
 4018:     }
 4019:     return '';
 4020: }
 4021: 
 4022: sub get_portfolio_access {
 4023:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4024: 
 4025:     if (!ref($access_hash)) {
 4026: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4027: 	my %access_controls = &get_access_controls($current_perms,$group,
 4028: 						   $file_name);
 4029: 	$access_hash = $access_controls{$file_name};
 4030:     }
 4031: 
 4032:     my ($public,$guest,@domains,@users,@courses,@groups);
 4033:     my $now = time;
 4034:     if (ref($access_hash) eq 'HASH') {
 4035:         foreach my $key (keys(%{$access_hash})) {
 4036:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4037:             if ($start > $now) {
 4038:                 next;
 4039:             }
 4040:             if ($end && $end<$now) {
 4041:                 next;
 4042:             }
 4043:             if ($scope eq 'public') {
 4044:                 $public = $key;
 4045:                 last;
 4046:             } elsif ($scope eq 'guest') {
 4047:                 $guest = $key;
 4048:             } elsif ($scope eq 'domains') {
 4049:                 push(@domains,$key);
 4050:             } elsif ($scope eq 'users') {
 4051:                 push(@users,$key);
 4052:             } elsif ($scope eq 'course') {
 4053:                 push(@courses,$key);
 4054:             } elsif ($scope eq 'group') {
 4055:                 push(@groups,$key);
 4056:             }
 4057:         }
 4058:         if ($public) {
 4059:             return 'ok';
 4060:         }
 4061:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4062:             if ($guest) {
 4063:                 return $guest;
 4064:             }
 4065:         } else {
 4066:             if (@domains > 0) {
 4067:                 foreach my $domkey (@domains) {
 4068:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4069:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4070:                             return 'ok';
 4071:                         }
 4072:                     }
 4073:                 }
 4074:             }
 4075:             if (@users > 0) {
 4076:                 foreach my $userkey (@users) {
 4077:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4078:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4079:                             if (ref($item) eq 'HASH') {
 4080:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4081:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4082:                                     return 'ok';
 4083:                                 }
 4084:                             }
 4085:                         }
 4086:                     } 
 4087:                 }
 4088:             }
 4089:             my %roleshash;
 4090:             my @courses_and_groups = @courses;
 4091:             push(@courses_and_groups,@groups); 
 4092:             if (@courses_and_groups > 0) {
 4093:                 my (%allgroups,%allroles); 
 4094:                 my ($start,$end,$role,$sec,$group);
 4095:                 foreach my $envkey (%env) {
 4096:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4097:                         my $cid = $2.'_'.$3; 
 4098:                         if ($1 eq 'gr') {
 4099:                             $group = $4;
 4100:                             $allgroups{$cid}{$group} = $env{$envkey};
 4101:                         } else {
 4102:                             if ($4 eq '') {
 4103:                                 $sec = 'none';
 4104:                             } else {
 4105:                                 $sec = $4;
 4106:                             }
 4107:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4108:                         }
 4109:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4110:                         my $cid = $2.'_'.$3;
 4111:                         if ($4 eq '') {
 4112:                             $sec = 'none';
 4113:                         } else {
 4114:                             $sec = $4;
 4115:                         }
 4116:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4117:                     }
 4118:                 }
 4119:                 if (keys(%allroles) == 0) {
 4120:                     return;
 4121:                 }
 4122:                 foreach my $key (@courses_and_groups) {
 4123:                     my %content = %{$$access_hash{$key}};
 4124:                     my $cnum = $content{'number'};
 4125:                     my $cdom = $content{'domain'};
 4126:                     my $cid = $cdom.'_'.$cnum;
 4127:                     if (!exists($allroles{$cid})) {
 4128:                         next;
 4129:                     }    
 4130:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4131:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4132:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4133:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4134:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4135:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4136:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4137:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4138:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4139:                                         if (grep/^all$/,@sections) {
 4140:                                             return 'ok';
 4141:                                         } else {
 4142:                                             if (grep/^$sec$/,@sections) {
 4143:                                                 return 'ok';
 4144:                                             }
 4145:                                         }
 4146:                                     }
 4147:                                 }
 4148:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4149:                                     if (grep/^none$/,@groups) {
 4150:                                         return 'ok';
 4151:                                     }
 4152:                                 } else {
 4153:                                     if (grep/^all$/,@groups) {
 4154:                                         return 'ok';
 4155:                                     } 
 4156:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4157:                                         if (grep/^$group$/,@groups) {
 4158:                                             return 'ok';
 4159:                                         }
 4160:                                     }
 4161:                                 } 
 4162:                             }
 4163:                         }
 4164:                     }
 4165:                 }
 4166:             }
 4167:             if ($guest) {
 4168:                 return $guest;
 4169:             }
 4170:         }
 4171:     }
 4172:     return;
 4173: }
 4174: 
 4175: sub course_group_datechecker {
 4176:     my ($dates,$now,$status) = @_;
 4177:     my ($start,$end) = split(/\./,$dates);
 4178:     if (!$start && !$end) {
 4179:         return 'ok';
 4180:     }
 4181:     if (grep/^active$/,@{$status}) {
 4182:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4183:             return 'ok';
 4184:         }
 4185:     }
 4186:     if (grep/^previous$/,@{$status}) {
 4187:         if ($end > $now ) {
 4188:             return 'ok';
 4189:         }
 4190:     }
 4191:     if (grep/^future$/,@{$status}) {
 4192:         if ($start > $now) {
 4193:             return 'ok';
 4194:         }
 4195:     }
 4196:     return; 
 4197: }
 4198: 
 4199: sub parse_portfolio_url {
 4200:     my ($url) = @_;
 4201: 
 4202:     my ($type,$udom,$unum,$group,$file_name);
 4203:     
 4204:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4205: 	$type = 1;
 4206:         $udom = $1;
 4207:         $unum = $2;
 4208:         $file_name = $3;
 4209:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4210: 	$type = 2;
 4211:         $udom = $1;
 4212:         $unum = $2;
 4213:         $group = $3;
 4214:         $file_name = $3.'/'.$4;
 4215:     }
 4216:     if (wantarray) {
 4217: 	return ($type,$udom,$unum,$file_name,$group);
 4218:     }
 4219:     return $type;
 4220: }
 4221: 
 4222: sub is_portfolio_url {
 4223:     my ($url) = @_;
 4224:     return scalar(&parse_portfolio_url($url));
 4225: }
 4226: 
 4227: sub is_portfolio_file {
 4228:     my ($file) = @_;
 4229:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4230:         return 1;
 4231:     }
 4232:     return;
 4233: }
 4234: 
 4235: 
 4236: # ---------------------------------------------- Custom access rule evaluation
 4237: 
 4238: sub customaccess {
 4239:     my ($priv,$uri)=@_;
 4240:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4241:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4242:     $udom = &LONCAPA::clean_domain($udom);
 4243:     $ucrs = &LONCAPA::clean_username($ucrs);
 4244:     my $access=0;
 4245:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4246: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4247: 	if ($type eq 'user') {
 4248: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4249: 		my ($tdom,$tuname)=split(m{/},$scope);
 4250: 		if ($tdom) {
 4251: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4252: 		}
 4253: 		if ($tuname) {
 4254: 		    if ($tuname ne $env{'user.name'}) { next; }
 4255: 		}
 4256: 		$access=($effect eq 'allow');
 4257: 		last;
 4258: 	    }
 4259: 	} else {
 4260: 	    if ($role) {
 4261: 		if ($role ne $urole) { next; }
 4262: 	    }
 4263: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4264: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4265: 		if ($tdom) {
 4266: 		    if ($tdom ne $udom) { next; }
 4267: 		}
 4268: 		if ($tcrs) {
 4269: 		    if ($tcrs ne $ucrs) { next; }
 4270: 		}
 4271: 		if ($tsec) {
 4272: 		    if ($tsec ne $usec) { next; }
 4273: 		}
 4274: 		$access=($effect eq 'allow');
 4275: 		last;
 4276: 	    }
 4277: 	    if ($realm eq '' && $role eq '') {
 4278: 		$access=($effect eq 'allow');
 4279: 	    }
 4280: 	}
 4281:     }
 4282:     return $access;
 4283: }
 4284: 
 4285: # ------------------------------------------------- Check for a user privilege
 4286: 
 4287: sub allowed {
 4288:     my ($priv,$uri,$symb,$role)=@_;
 4289:     my $ver_orguri=$uri;
 4290:     $uri=&deversion($uri);
 4291:     my $orguri=$uri;
 4292:     $uri=&declutter($uri);
 4293: 
 4294:     if ($priv eq 'evb') {
 4295: # Evade communication block restrictions for specified role in a course
 4296:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4297:             return $1;
 4298:         } else {
 4299:             return;
 4300:         }
 4301:     }
 4302: 
 4303:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4304: # Free bre access to adm and meta resources
 4305:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4306: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4307: 	&& ($priv eq 'bre')) {
 4308: 	return 'F';
 4309:     }
 4310: 
 4311: # Free bre access to user's own portfolio contents
 4312:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4313:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4314: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4315:         my %setters;
 4316:         my ($startblock,$endblock) = 
 4317:             &Apache::loncommon::blockcheck(\%setters,'port');
 4318:         if ($startblock && $endblock) {
 4319:             return 'B';
 4320:         } else {
 4321:             return 'F';
 4322:         }
 4323:     }
 4324: 
 4325: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4326:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4327:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4328:         if (exists($env{'request.course.id'})) {
 4329:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4330:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4331:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4332:                 my $courseprivid=$env{'request.course.id'};
 4333:                 $courseprivid=~s/\_/\//;
 4334:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4335:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4336:                     return $1; 
 4337:                 } else {
 4338:                     if ($env{'request.course.sec'}) {
 4339:                         $courseprivid.='/'.$env{'request.course.sec'};
 4340:                     }
 4341:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4342:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4343:                         return $2;
 4344:                     }
 4345:                 }
 4346:             }
 4347:         }
 4348:     }
 4349: 
 4350: # Free bre to public access
 4351: 
 4352:     if ($priv eq 'bre') {
 4353:         my $copyright=&metadata($uri,'copyright');
 4354: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4355:            return 'F'; 
 4356:         }
 4357:         if ($copyright eq 'priv') {
 4358:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4359: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4360: 		return '';
 4361:             }
 4362:         }
 4363:         if ($copyright eq 'domain') {
 4364:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4365: 	    unless (($env{'user.domain'} eq $1) ||
 4366:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4367: 		return '';
 4368:             }
 4369:         }
 4370:         if ($env{'request.role'}=~ /li\.\//) {
 4371:             # Library role, so allow browsing of resources in this domain.
 4372:             return 'F';
 4373:         }
 4374:         if ($copyright eq 'custom') {
 4375: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4376:         }
 4377:     }
 4378:     # Domain coordinator is trying to create a course
 4379:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4380:         # uri is the requested domain in this case.
 4381:         # comparison to 'request.role.domain' shows if the user has selected
 4382:         # a role of dc for the domain in question.
 4383:         return 'F' if ($uri eq $env{'request.role.domain'});
 4384:     }
 4385: 
 4386:     my $thisallowed='';
 4387:     my $statecond=0;
 4388:     my $courseprivid='';
 4389: 
 4390: # Course
 4391: 
 4392:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4393:        $thisallowed.=$1;
 4394:     }
 4395: 
 4396: # Domain
 4397: 
 4398:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4399:        =~/\Q$priv\E\&([^\:]*)/) {
 4400:        $thisallowed.=$1;
 4401:     }
 4402: 
 4403: # Course: uri itself is a course
 4404:     my $courseuri=$uri;
 4405:     $courseuri=~s/\_(\d)/\/$1/;
 4406:     $courseuri=~s/^([^\/])/\/$1/;
 4407: 
 4408:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4409:        =~/\Q$priv\E\&([^\:]*)/) {
 4410:        $thisallowed.=$1;
 4411:     }
 4412: 
 4413: # URI is an uploaded document for this course, default permissions don't matter
 4414: # not allowing 'edit' access (editupload) to uploaded course docs
 4415:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4416: 	$thisallowed='';
 4417:         my ($match)=&is_on_map($uri);
 4418:         if ($match) {
 4419:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4420:                   =~/\Q$priv\E\&([^\:]*)/) {
 4421:                 $thisallowed.=$1;
 4422:             }
 4423:         } else {
 4424:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4425:             if ($refuri) {
 4426:                 if ($refuri =~ m|^/adm/|) {
 4427:                     $thisallowed='F';
 4428:                 } else {
 4429:                     $refuri=&declutter($refuri);
 4430:                     my ($match) = &is_on_map($refuri);
 4431:                     if ($match) {
 4432:                         $thisallowed='F';
 4433:                     }
 4434:                 }
 4435:             }
 4436:         }
 4437:     }
 4438: 
 4439:     if ($priv eq 'bre'
 4440: 	&& $thisallowed ne 'F' 
 4441: 	&& $thisallowed ne '2'
 4442: 	&& &is_portfolio_url($uri)) {
 4443: 	$thisallowed = &portfolio_access($uri);
 4444:     }
 4445:     
 4446: # Full access at system, domain or course-wide level? Exit.
 4447: 
 4448:     if ($thisallowed=~/F/) {
 4449: 	return 'F';
 4450:     }
 4451: 
 4452: # If this is generating or modifying users, exit with special codes
 4453: 
 4454:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4455: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4456: 	    my ($audom,$auname)=split('/',$uri);
 4457: # no author name given, so this just checks on the general right to make a co-author in this domain
 4458: 	    unless ($auname) { return $thisallowed; }
 4459: # an author name is given, so we are about to actually make a co-author for a certain account
 4460: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4461: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4462: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4463: 	}
 4464: 	return $thisallowed;
 4465:     }
 4466: #
 4467: # Gathered so far: system, domain and course wide privileges
 4468: #
 4469: # Course: See if uri or referer is an individual resource that is part of 
 4470: # the course
 4471: 
 4472:     if ($env{'request.course.id'}) {
 4473: 
 4474:        $courseprivid=$env{'request.course.id'};
 4475:        if ($env{'request.course.sec'}) {
 4476:           $courseprivid.='/'.$env{'request.course.sec'};
 4477:        }
 4478:        $courseprivid=~s/\_/\//;
 4479:        my $checkreferer=1;
 4480:        my ($match,$cond)=&is_on_map($uri);
 4481:        if ($match) {
 4482:            $statecond=$cond;
 4483:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4484:                =~/\Q$priv\E\&([^\:]*)/) {
 4485:                $thisallowed.=$1;
 4486:                $checkreferer=0;
 4487:            }
 4488:        }
 4489:        
 4490:        if ($checkreferer) {
 4491: 	  my $refuri=$env{'httpref.'.$orguri};
 4492:             unless ($refuri) {
 4493:                 foreach my $key (keys(%env)) {
 4494: 		    if ($key=~/^httpref\..*\*/) {
 4495: 			my $pattern=$key;
 4496:                         $pattern=~s/^httpref\.\/res\///;
 4497:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4498:                         $pattern=~s/\//\\\//g;
 4499:                         if ($orguri=~/$pattern/) {
 4500: 			    $refuri=$env{$key};
 4501:                         }
 4502:                     }
 4503:                 }
 4504:             }
 4505: 
 4506:          if ($refuri) { 
 4507: 	  $refuri=&declutter($refuri);
 4508:           my ($match,$cond)=&is_on_map($refuri);
 4509:             if ($match) {
 4510:               my $refstatecond=$cond;
 4511:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4512:                   =~/\Q$priv\E\&([^\:]*)/) {
 4513:                   $thisallowed.=$1;
 4514:                   $uri=$refuri;
 4515:                   $statecond=$refstatecond;
 4516:               }
 4517:           }
 4518:         }
 4519:        }
 4520:    }
 4521: 
 4522: #
 4523: # Gathered now: all privileges that could apply, and condition number
 4524: # 
 4525: #
 4526: # Full or no access?
 4527: #
 4528: 
 4529:     if ($thisallowed=~/F/) {
 4530: 	return 'F';
 4531:     }
 4532: 
 4533:     unless ($thisallowed) {
 4534:         return '';
 4535:     }
 4536: 
 4537: # Restrictions exist, deal with them
 4538: #
 4539: #   C:according to course preferences
 4540: #   R:according to resource settings
 4541: #   L:unless locked
 4542: #   X:according to user session state
 4543: #
 4544: 
 4545: # Possibly locked functionality, check all courses
 4546: # Locks might take effect only after 10 minutes cache expiration for other
 4547: # courses, and 2 minutes for current course
 4548: 
 4549:     my $envkey;
 4550:     if ($thisallowed=~/L/) {
 4551:         foreach $envkey (keys %env) {
 4552:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4553:                my $courseid=$2;
 4554:                my $roleid=$1.'.'.$2;
 4555:                $courseid=~s/^\///;
 4556:                my $expiretime=600;
 4557:                if ($env{'request.role'} eq $roleid) {
 4558: 		  $expiretime=120;
 4559:                }
 4560: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4561:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4562:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4563: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4564:                }
 4565:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4566:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4567: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4568:                        &log($env{'user.domain'},$env{'user.name'},
 4569:                             $env{'user.home'},
 4570:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4571:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4572:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4573: 		       return '';
 4574:                    }
 4575:                }
 4576:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4577:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4578: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4579:                        &log($env{'user.domain'},$env{'user.name'},
 4580:                             $env{'user.home'},
 4581:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4582:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4583:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4584: 		       return '';
 4585:                    }
 4586:                }
 4587: 	   }
 4588:        }
 4589:     }
 4590:    
 4591: #
 4592: # Rest of the restrictions depend on selected course
 4593: #
 4594: 
 4595:     unless ($env{'request.course.id'}) {
 4596: 	if ($thisallowed eq 'A') {
 4597: 	    return 'A';
 4598:         } elsif ($thisallowed eq 'B') {
 4599:             return 'B';
 4600: 	} else {
 4601: 	    return '1';
 4602: 	}
 4603:     }
 4604: 
 4605: #
 4606: # Now user is definitely in a course
 4607: #
 4608: 
 4609: 
 4610: # Course preferences
 4611: 
 4612:    if ($thisallowed=~/C/) {
 4613:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4614:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4615:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4616: 	   =~/\Q$rolecode\E/) {
 4617: 	   if ($priv ne 'pch') { 
 4618: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4619: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4620: 			$env{'request.course.id'});
 4621: 	   }
 4622:            return '';
 4623:        }
 4624: 
 4625:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4626: 	   =~/\Q$unamedom\E/) {
 4627: 	   if ($priv ne 'pch') { 
 4628: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4629: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4630: 			$env{'request.course.id'});
 4631: 	   }
 4632:            return '';
 4633:        }
 4634:    }
 4635: 
 4636: # Resource preferences
 4637: 
 4638:    if ($thisallowed=~/R/) {
 4639:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4640:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4641: 	   if ($priv ne 'pch') { 
 4642: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4643: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4644: 	   }
 4645: 	   return '';
 4646:        }
 4647:    }
 4648: 
 4649: # Restricted by state or randomout?
 4650: 
 4651:    if ($thisallowed=~/X/) {
 4652:       if ($env{'acc.randomout'}) {
 4653: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4654:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4655:             return ''; 
 4656:          }
 4657:       }
 4658:       if (&condval($statecond)) {
 4659: 	 return '2';
 4660:       } else {
 4661:          return '';
 4662:       }
 4663:    }
 4664: 
 4665:     if ($thisallowed eq 'A') {
 4666: 	return 'A';
 4667:     } elsif ($thisallowed eq 'B') {
 4668:         return 'B';
 4669:     }
 4670:    return 'F';
 4671: }
 4672: 
 4673: sub split_uri_for_cond {
 4674:     my $uri=&deversion(&declutter(shift));
 4675:     my @uriparts=split(/\//,$uri);
 4676:     my $filename=pop(@uriparts);
 4677:     my $pathname=join('/',@uriparts);
 4678:     return ($pathname,$filename);
 4679: }
 4680: # --------------------------------------------------- Is a resource on the map?
 4681: 
 4682: sub is_on_map {
 4683:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4684:     #Trying to find the conditional for the file
 4685:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4686: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4687:     if ($match) {
 4688: 	return (1,$1);
 4689:     } else {
 4690: 	return (0,0);
 4691:     }
 4692: }
 4693: 
 4694: # --------------------------------------------------------- Get symb from alias
 4695: 
 4696: sub get_symb_from_alias {
 4697:     my $symb=shift;
 4698:     my ($map,$resid,$url)=&decode_symb($symb);
 4699: # Already is a symb
 4700:     if ($url) { return $symb; }
 4701: # Must be an alias
 4702:     my $aliassymb='';
 4703:     my %bighash;
 4704:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4705:                             &GDBM_READER(),0640)) {
 4706:         my $rid=$bighash{'mapalias_'.$symb};
 4707: 	if ($rid) {
 4708: 	    my ($mapid,$resid)=split(/\./,$rid);
 4709: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4710: 				    $resid,$bighash{'src_'.$rid});
 4711: 	}
 4712:         untie %bighash;
 4713:     }
 4714:     return $aliassymb;
 4715: }
 4716: 
 4717: # ----------------------------------------------------------------- Define Role
 4718: 
 4719: sub definerole {
 4720:   if (allowed('mcr','/')) {
 4721:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4722:     foreach my $role (split(':',$sysrole)) {
 4723: 	my ($crole,$cqual)=split(/\&/,$role);
 4724:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4725:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4726: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4727:                return "refused:s:$crole&$cqual"; 
 4728:             }
 4729:         }
 4730:     }
 4731:     foreach my $role (split(':',$domrole)) {
 4732: 	my ($crole,$cqual)=split(/\&/,$role);
 4733:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4734:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4735: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4736:                return "refused:d:$crole&$cqual"; 
 4737:             }
 4738:         }
 4739:     }
 4740:     foreach my $role (split(':',$courole)) {
 4741: 	my ($crole,$cqual)=split(/\&/,$role);
 4742:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4743:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4744: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4745:                return "refused:c:$crole&$cqual"; 
 4746:             }
 4747:         }
 4748:     }
 4749:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4750:                 "$env{'user.domain'}:$env{'user.name'}:".
 4751: 	        "rolesdef_$rolename=".
 4752:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4753:     return reply($command,$env{'user.home'});
 4754:   } else {
 4755:     return 'refused';
 4756:   }
 4757: }
 4758: 
 4759: # ---------------- Make a metadata query against the network of library servers
 4760: 
 4761: sub metadata_query {
 4762:     my ($query,$custom,$customshow,$server_array)=@_;
 4763:     my %rhash;
 4764:     my %libserv = &all_library();
 4765:     my @server_list = (defined($server_array) ? @$server_array
 4766:                                               : keys(%libserv) );
 4767:     for my $server (@server_list) {
 4768: 	unless ($custom or $customshow) {
 4769: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4770: 	    $rhash{$server}=$reply;
 4771: 	}
 4772: 	else {
 4773: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4774: 			     &escape($custom).':'.&escape($customshow),
 4775: 			     $server);
 4776: 	    $rhash{$server}=$reply;
 4777: 	}
 4778:     }
 4779:     return \%rhash;
 4780: }
 4781: 
 4782: # ----------------------------------------- Send log queries and wait for reply
 4783: 
 4784: sub log_query {
 4785:     my ($uname,$udom,$query,%filters)=@_;
 4786:     my $uhome=&homeserver($uname,$udom);
 4787:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4788:     my $uhost=&hostname($uhome);
 4789:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4790:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4791:                        $uhome);
 4792:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4793:     return get_query_reply($queryid);
 4794: }
 4795: 
 4796: # -------------------------- Update MySQL table for portfolio file
 4797: 
 4798: sub update_portfolio_table {
 4799:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4800:     my $homeserver = &homeserver($uname,$udom);
 4801:     my $queryid=
 4802:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4803:                ':'.&escape($file_name).':'.$action,$homeserver);
 4804:     my $reply = &get_query_reply($queryid);
 4805:     return $reply;
 4806: }
 4807: 
 4808: # -------------------------- Update MySQL allusers table
 4809: 
 4810: sub update_allusers_table {
 4811:     my ($uname,$udom,$names) = @_;
 4812:     my $homeserver = &homeserver($uname,$udom);
 4813:     my $queryid=
 4814:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4815:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4816:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4817:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4818:                'generation='.&escape($names->{'generation'}).'%%'.
 4819:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4820:                'id='.&escape($names->{'id'}),$homeserver);
 4821:     my $reply = &get_query_reply($queryid);
 4822:     return $reply;
 4823: }
 4824: 
 4825: # ------- Request retrieval of institutional classlists for course(s)
 4826: 
 4827: sub fetch_enrollment_query {
 4828:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4829:     my $homeserver;
 4830:     my $maxtries = 1;
 4831:     if ($context eq 'automated') {
 4832:         $homeserver = $perlvar{'lonHostID'};
 4833:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4834:     } else {
 4835:         $homeserver = &homeserver($cnum,$dom);
 4836:     }
 4837:     my $host=&hostname($homeserver);
 4838:     my $cmd = '';
 4839:     foreach my $affiliate (keys %{$affiliatesref}) {
 4840:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4841:     }
 4842:     $cmd =~ s/%%$//;
 4843:     $cmd = &escape($cmd);
 4844:     my $query = 'fetchenrollment';
 4845:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4846:     unless ($queryid=~/^\Q$host\E\_/) { 
 4847:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4848:         return 'error: '.$queryid;
 4849:     }
 4850:     my $reply = &get_query_reply($queryid);
 4851:     my $tries = 1;
 4852:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4853:         $reply = &get_query_reply($queryid);
 4854:         $tries ++;
 4855:     }
 4856:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4857:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4858:     } else {
 4859:         my @responses = split(/:/,$reply);
 4860:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4861:             foreach my $line (@responses) {
 4862:                 my ($key,$value) = split(/=/,$line,2);
 4863:                 $$replyref{$key} = $value;
 4864:             }
 4865:         } else {
 4866:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4867:             foreach my $line (@responses) {
 4868:                 my ($key,$value) = split(/=/,$line);
 4869:                 $$replyref{$key} = $value;
 4870:                 if ($value > 0) {
 4871:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4872:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4873:                         my $destname = $pathname.'/'.$filename;
 4874:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4875:                         if ($xml_classlist =~ /^error/) {
 4876:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4877:                         } else {
 4878:                             if ( open(FILE,">$destname") ) {
 4879:                                 print FILE &unescape($xml_classlist);
 4880:                                 close(FILE);
 4881:                             } else {
 4882:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4883:                             }
 4884:                         }
 4885:                     }
 4886:                 }
 4887:             }
 4888:         }
 4889:         return 'ok';
 4890:     }
 4891:     return 'error';
 4892: }
 4893: 
 4894: sub get_query_reply {
 4895:     my $queryid=shift;
 4896:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4897:     my $reply='';
 4898:     for (1..100) {
 4899: 	sleep 2;
 4900:         if (-e $replyfile.'.end') {
 4901: 	    if (open(my $fh,$replyfile)) {
 4902: 		$reply = join('',<$fh>);
 4903: 		close($fh);
 4904: 	   } else { return 'error: reply_file_error'; }
 4905:            return &unescape($reply);
 4906: 	}
 4907:     }
 4908:     return 'timeout:'.$queryid;
 4909: }
 4910: 
 4911: sub courselog_query {
 4912: #
 4913: # possible filters:
 4914: # url: url or symb
 4915: # username
 4916: # domain
 4917: # action: view, submit, grade
 4918: # start: timestamp
 4919: # end: timestamp
 4920: #
 4921:     my (%filters)=@_;
 4922:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4923:     if ($filters{'url'}) {
 4924: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4925:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4926:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4927:     }
 4928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4930:     return &log_query($cname,$cdom,'courselog',%filters);
 4931: }
 4932: 
 4933: sub userlog_query {
 4934: #
 4935: # possible filters:
 4936: # action: log check role
 4937: # start: timestamp
 4938: # end: timestamp
 4939: #
 4940:     my ($uname,$udom,%filters)=@_;
 4941:     return &log_query($uname,$udom,'userlog',%filters);
 4942: }
 4943: 
 4944: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4945: 
 4946: sub auto_run {
 4947:     my ($cnum,$cdom) = @_;
 4948:     my $response = 0;
 4949:     my $settings;
 4950:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4951:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4952:         $settings = $domconfig{'autoenroll'};
 4953:         if ($settings->{'run'} eq '1') {
 4954:             $response = 1;
 4955:         }
 4956:     } else {
 4957:         my $homeserver;
 4958:         if (&is_course($cdom,$cnum)) {
 4959:             $homeserver = &homeserver($cnum,$cdom);
 4960:         } else {
 4961:             $homeserver = &domain($cdom,'primary');
 4962:         }
 4963:         if ($homeserver ne 'no_host') {
 4964:             $response = &reply('autorun:'.$cdom,$homeserver);
 4965:         }
 4966:     }
 4967:     return $response;
 4968: }
 4969: 
 4970: sub auto_get_sections {
 4971:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4972:     my $homeserver = &homeserver($cnum,$cdom);
 4973:     my @secs = ();
 4974:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4975:     unless ($response eq 'refused') {
 4976:         @secs = split(/:/,$response);
 4977:     }
 4978:     return @secs;
 4979: }
 4980: 
 4981: sub auto_new_course {
 4982:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4983:     my $homeserver = &homeserver($cnum,$cdom);
 4984:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4985:     return $response;
 4986: }
 4987: 
 4988: sub auto_validate_courseID {
 4989:     my ($cnum,$cdom,$inst_course_id) = @_;
 4990:     my $homeserver = &homeserver($cnum,$cdom);
 4991:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4992:     return $response;
 4993: }
 4994: 
 4995: sub auto_create_password {
 4996:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4997:     my ($homeserver,$response);
 4998:     my $create_passwd = 0;
 4999:     my $authchk = '';
 5000:     if ($udom =~ /^$match_domain$/) {
 5001:         $homeserver = &domain($udom,'primary');
 5002:     }
 5003:     if ($homeserver eq '') {
 5004:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5005:             $homeserver = &homeserver($cnum,$cdom);
 5006:         }
 5007:     }
 5008:     if ($homeserver eq '') {
 5009:         $authchk = 'nodomain';
 5010:     } else {
 5011:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5012:         if ($response eq 'refused') {
 5013:             $authchk = 'refused';
 5014:         } else {
 5015:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5016:         }
 5017:     }
 5018:     return ($authparam,$create_passwd,$authchk);
 5019: }
 5020: 
 5021: sub auto_photo_permission {
 5022:     my ($cnum,$cdom,$students) = @_;
 5023:     my $homeserver = &homeserver($cnum,$cdom);
 5024:     my ($outcome,$perm_reqd,$conditions) = 
 5025: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5026:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5027: 	return (undef,undef);
 5028:     }
 5029:     return ($outcome,$perm_reqd,$conditions);
 5030: }
 5031: 
 5032: sub auto_checkphotos {
 5033:     my ($uname,$udom,$pid) = @_;
 5034:     my $homeserver = &homeserver($uname,$udom);
 5035:     my ($result,$resulttype);
 5036:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5037: 				   &escape($uname).':'.&escape($pid),
 5038: 				   $homeserver));
 5039:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5040: 	return (undef,undef);
 5041:     }
 5042:     if ($outcome) {
 5043:         ($result,$resulttype) = split(/:/,$outcome);
 5044:     } 
 5045:     return ($result,$resulttype);
 5046: }
 5047: 
 5048: sub auto_photochoice {
 5049:     my ($cnum,$cdom) = @_;
 5050:     my $homeserver = &homeserver($cnum,$cdom);
 5051:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5052: 						       &escape($cdom),
 5053: 						       $homeserver)));
 5054:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5055: 	return (undef,undef);
 5056:     }
 5057:     return ($update,$comment);
 5058: }
 5059: 
 5060: sub auto_photoupdate {
 5061:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5062:     my $homeserver = &homeserver($cnum,$dom);
 5063:     my $host=&hostname($homeserver);
 5064:     my $cmd = '';
 5065:     my $maxtries = 1;
 5066:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5067:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5068:     }
 5069:     $cmd =~ s/%%$//;
 5070:     $cmd = &escape($cmd);
 5071:     my $query = 'institutionalphotos';
 5072:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5073:     unless ($queryid=~/^\Q$host\E\_/) {
 5074:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5075:         return 'error: '.$queryid;
 5076:     }
 5077:     my $reply = &get_query_reply($queryid);
 5078:     my $tries = 1;
 5079:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5080:         $reply = &get_query_reply($queryid);
 5081:         $tries ++;
 5082:     }
 5083:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5084:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5085:     } else {
 5086:         my @responses = split(/:/,$reply);
 5087:         my $outcome = shift(@responses); 
 5088:         foreach my $item (@responses) {
 5089:             my ($key,$value) = split(/=/,$item);
 5090:             $$photo{$key} = $value;
 5091:         }
 5092:         return $outcome;
 5093:     }
 5094:     return 'error';
 5095: }
 5096: 
 5097: sub auto_instcode_format {
 5098:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5099: 	$cat_order) = @_;
 5100:     my $courses = '';
 5101:     my @homeservers;
 5102:     if ($caller eq 'global') {
 5103: 	my %servers = &get_servers($codedom,'library');
 5104: 	foreach my $tryserver (keys(%servers)) {
 5105: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5106: 		push(@homeservers,$tryserver);
 5107: 	    }
 5108:         }
 5109:     } else {
 5110:         push(@homeservers,&homeserver($caller,$codedom));
 5111:     }
 5112:     foreach my $code (keys(%{$instcodes})) {
 5113:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5114:     }
 5115:     chop($courses);
 5116:     my $ok_response = 0;
 5117:     my $response;
 5118:     while (@homeservers > 0 && $ok_response == 0) {
 5119:         my $server = shift(@homeservers); 
 5120:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5121:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5122:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5123: 		split(/:/,$response);
 5124:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5125:             push(@{$codetitles},&str2array($codetitles_str));
 5126:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5127:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5128:             $ok_response = 1;
 5129:         }
 5130:     }
 5131:     if ($ok_response) {
 5132:         return 'ok';
 5133:     } else {
 5134:         return $response;
 5135:     }
 5136: }
 5137: 
 5138: sub auto_instcode_defaults {
 5139:     my ($domain,$returnhash,$code_order) = @_;
 5140:     my @homeservers;
 5141: 
 5142:     my %servers = &get_servers($domain,'library');
 5143:     foreach my $tryserver (keys(%servers)) {
 5144: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5145: 	    push(@homeservers,$tryserver);
 5146: 	}
 5147:     }
 5148: 
 5149:     my $response;
 5150:     foreach my $server (@homeservers) {
 5151:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5152:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5153: 	
 5154: 	foreach my $pair (split(/\&/,$response)) {
 5155: 	    my ($name,$value)=split(/\=/,$pair);
 5156: 	    if ($name eq 'code_order') {
 5157: 		@{$code_order} = split(/\&/,&unescape($value));
 5158: 	    } else {
 5159: 		$returnhash->{&unescape($name)}=&unescape($value);
 5160: 	    }
 5161: 	}
 5162: 	return 'ok';
 5163:     }
 5164: 
 5165:     return $response;
 5166: } 
 5167: 
 5168: sub auto_validate_class_sec {
 5169:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5170:     my $homeserver = &homeserver($cnum,$cdom);
 5171:     my $ownerlist;
 5172:     if (ref($owners) eq 'ARRAY') {
 5173:         $ownerlist = join(',',@{$owners});
 5174:     } else {
 5175:         $ownerlist = $owners;
 5176:     }
 5177:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5178:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5179:     return $response;
 5180: }
 5181: 
 5182: # ------------------------------------------------------- Course Group routines
 5183: 
 5184: sub get_coursegroups {
 5185:     my ($cdom,$cnum,$group,$namespace) = @_;
 5186:     return(&dump($namespace,$cdom,$cnum,$group));
 5187: }
 5188: 
 5189: sub modify_coursegroup {
 5190:     my ($cdom,$cnum,$groupsettings) = @_;
 5191:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5192: }
 5193: 
 5194: sub toggle_coursegroup_status {
 5195:     my ($cdom,$cnum,$group,$action) = @_;
 5196:     my ($from_namespace,$to_namespace);
 5197:     if ($action eq 'delete') {
 5198:         $from_namespace = 'coursegroups';
 5199:         $to_namespace = 'deleted_groups';
 5200:     } else {
 5201:         $from_namespace = 'deleted_groups';
 5202:         $to_namespace = 'coursegroups';
 5203:     }
 5204:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5205:     if (my $tmp = &error(%curr_group)) {
 5206:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5207:         return ('read error',$tmp);
 5208:     } else {
 5209:         my %savedsettings = %curr_group; 
 5210:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5211:         my $deloutcome;
 5212:         if ($result eq 'ok') {
 5213:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5214:         } else {
 5215:             return ('write error',$result);
 5216:         }
 5217:         if ($deloutcome eq 'ok') {
 5218:             return 'ok';
 5219:         } else {
 5220:             return ('delete error',$deloutcome);
 5221:         }
 5222:     }
 5223: }
 5224: 
 5225: sub modify_group_roles {
 5226:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5227:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5228:     my $role = 'gr/'.&escape($userprivs);
 5229:     my ($uname,$udom) = split(/:/,$user);
 5230:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5231:     if ($result eq 'ok') {
 5232:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5233:     }
 5234:     return $result;
 5235: }
 5236: 
 5237: sub modify_coursegroup_membership {
 5238:     my ($cdom,$cnum,$membership) = @_;
 5239:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5240:     return $result;
 5241: }
 5242: 
 5243: sub get_active_groups {
 5244:     my ($udom,$uname,$cdom,$cnum) = @_;
 5245:     my $now = time;
 5246:     my %groups = ();
 5247:     foreach my $key (keys(%env)) {
 5248:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5249:             my ($start,$end) = split(/\./,$env{$key});
 5250:             if (($end!=0) && ($end<$now)) { next; }
 5251:             if (($start!=0) && ($start>$now)) { next; }
 5252:             if ($1 eq $cdom && $2 eq $cnum) {
 5253:                 $groups{$3} = $env{$key} ;
 5254:             }
 5255:         }
 5256:     }
 5257:     return %groups;
 5258: }
 5259: 
 5260: sub get_group_membership {
 5261:     my ($cdom,$cnum,$group) = @_;
 5262:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5263: }
 5264: 
 5265: sub get_users_groups {
 5266:     my ($udom,$uname,$courseid) = @_;
 5267:     my @usersgroups;
 5268:     my $cachetime=1800;
 5269: 
 5270:     my $hashid="$udom:$uname:$courseid";
 5271:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5272:     if (defined($cached)) {
 5273:         @usersgroups = split(/:/,$grouplist);
 5274:     } else {  
 5275:         $grouplist = '';
 5276:         my $courseurl = &courseid_to_courseurl($courseid);
 5277:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5278:         my $access_end = $env{'course.'.$courseid.
 5279:                               '.default_enrollment_end_date'};
 5280:         my $now = time;
 5281:         foreach my $key (keys(%roleshash)) {
 5282:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5283:                 my $group = $1;
 5284:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5285:                     my $start = $2;
 5286:                     my $end = $1;
 5287:                     if ($start == -1) { next; } # deleted from group
 5288:                     if (($start!=0) && ($start>$now)) { next; }
 5289:                     if (($end!=0) && ($end<$now)) {
 5290:                         if ($access_end && $access_end < $now) {
 5291:                             if ($access_end - $end < 86400) {
 5292:                                 push(@usersgroups,$group);
 5293:                             }
 5294:                         }
 5295:                         next;
 5296:                     }
 5297:                     push(@usersgroups,$group);
 5298:                 }
 5299:             }
 5300:         }
 5301:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5302:         $grouplist = join(':',@usersgroups);
 5303:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5304:     }
 5305:     return @usersgroups;
 5306: }
 5307: 
 5308: sub devalidate_getgroups_cache {
 5309:     my ($udom,$uname,$cdom,$cnum)=@_;
 5310:     my $courseid = $cdom.'_'.$cnum;
 5311: 
 5312:     my $hashid="$udom:$uname:$courseid";
 5313:     &devalidate_cache_new('getgroups',$hashid);
 5314: }
 5315: 
 5316: # ------------------------------------------------------------------ Plain Text
 5317: 
 5318: sub plaintext {
 5319:     my ($short,$type,$cid) = @_;
 5320:     if ($short =~ /^cr/) {
 5321: 	return (split('/',$short))[-1];
 5322:     }
 5323:     if (!defined($cid)) {
 5324:         $cid = $env{'request.course.id'};
 5325:     }
 5326:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5327:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5328:                                           '.plaintext'});
 5329:     }
 5330:     my %rolenames = (
 5331:                       Course => 'std',
 5332:                       Group => 'alt1',
 5333:                     );
 5334:     if (defined($type) && 
 5335:          defined($rolenames{$type}) && 
 5336:          defined($prp{$short}{$rolenames{$type}})) {
 5337:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5338:     } else {
 5339:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5340:     }
 5341: }
 5342: 
 5343: # ----------------------------------------------------------------- Assign Role
 5344: 
 5345: sub assignrole {
 5346:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
 5347:     my $mrole;
 5348:     if ($role =~ /^cr\//) {
 5349:         my $cwosec=$url;
 5350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5351: 	unless (&allowed('ccr',$cwosec)) {
 5352:            &logthis('Refused custom assignrole: '.
 5353:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5354: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5355:            return 'refused'; 
 5356:         }
 5357:         $mrole='cr';
 5358:     } elsif ($role =~ /^gr\//) {
 5359:         my $cwogrp=$url;
 5360:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5361:         unless (&allowed('mdg',$cwogrp)) {
 5362:             &logthis('Refused group assignrole: '.
 5363:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5364:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5365:             return 'refused';
 5366:         }
 5367:         $mrole='gr';
 5368:     } else {
 5369:         my $cwosec=$url;
 5370:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5371:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5372:             my $refused;
 5373:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5374:                 if (!(&allowed('c'.$role,$url))) {
 5375:                     $refused = 1;
 5376:                 }
 5377:             } else {
 5378:                 $refused = 1;
 5379:             }
 5380:             if ($refused) {
 5381:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5382:                     $refused = '';
 5383:                 } else {
 5384:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5385:                              ' '.$role.' '.$end.' '.$start.' by '.
 5386: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5387:                     return 'refused';
 5388:                 }
 5389:             }
 5390:         }
 5391:         $mrole=$role;
 5392:     }
 5393:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5394:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5395:     if ($end) { $command.='_'.$end; }
 5396:     if ($start) {
 5397: 	if ($end) { 
 5398:            $command.='_'.$start; 
 5399:         } else {
 5400:            $command.='_0_'.$start;
 5401:         }
 5402:     }
 5403:     my $origstart = $start;
 5404:     my $origend = $end;
 5405: # actually delete
 5406:     if ($deleteflag) {
 5407: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5408: # modify command to delete the role
 5409:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5410:                 "$udom:$uname:$url".'_'."$mrole";
 5411: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5412: # set start and finish to negative values for userrolelog
 5413:            $start=-1;
 5414:            $end=-1;
 5415:         }
 5416:     }
 5417: # send command
 5418:     my $answer=&reply($command,&homeserver($uname,$udom));
 5419: # log new user role if status is ok
 5420:     if ($answer eq 'ok') {
 5421: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5422: # for course roles, perform group memberships changes triggered by role change.
 5423:         unless ($role =~ /^gr/) {
 5424:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5425:                                              $origstart);
 5426:         }
 5427:     }
 5428:     return $answer;
 5429: }
 5430: 
 5431: # -------------------------------------------------- Modify user authentication
 5432: # Overrides without validation
 5433: 
 5434: sub modifyuserauth {
 5435:     my ($udom,$uname,$umode,$upass)=@_;
 5436:     my $uhome=&homeserver($uname,$udom);
 5437:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5438:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5439:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5440:              ' in domain '.$env{'request.role.domain'});  
 5441:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5442: 		     &escape($upass),$uhome);
 5443:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5444:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5445:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5446:     &log($udom,,$uname,$uhome,
 5447:         'Authentication changed by '.$env{'user.domain'}.', '.
 5448:                                      $env{'user.name'}.', '.$umode.
 5449:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5450:     unless ($reply eq 'ok') {
 5451:         &logthis('Authentication mode error: '.$reply);
 5452: 	return 'error: '.$reply;
 5453:     }   
 5454:     return 'ok';
 5455: }
 5456: 
 5457: # --------------------------------------------------------------- Modify a user
 5458: 
 5459: sub modifyuser {
 5460:     my ($udom,    $uname, $uid,
 5461:         $umode,   $upass, $first,
 5462:         $middle,  $last,  $gene,
 5463:         $forceid, $desiredhome, $email)=@_;
 5464:     $udom= &LONCAPA::clean_domain($udom);
 5465:     $uname=&LONCAPA::clean_username($uname);
 5466:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5467:              $umode.', '.$first.', '.$middle.', '.
 5468: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5469:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5470:                                      ' desiredhome not specified'). 
 5471:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5472:              ' in domain '.$env{'request.role.domain'});
 5473:     my $uhome=&homeserver($uname,$udom,'true');
 5474: # ----------------------------------------------------------------- Create User
 5475:     if (($uhome eq 'no_host') && 
 5476: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5477:         my $unhome='';
 5478:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5479:             $unhome = $desiredhome;
 5480: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5481: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5482:         } else { # load balancing routine for determining $unhome
 5483:             my $loadm=10000000;
 5484: 	    my %servers = &get_servers($udom,'library');
 5485: 	    foreach my $tryserver (keys(%servers)) {
 5486: 		my $answer=reply('load',$tryserver);
 5487: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5488: 		    $loadm=$answer;
 5489: 		    $unhome=$tryserver;
 5490: 		}
 5491: 	    }
 5492:         }
 5493:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5494: 	    return 'error: unable to find a home server for '.$uname.
 5495:                    ' in domain '.$udom;
 5496:         }
 5497:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5498:                          &escape($upass),$unhome);
 5499: 	unless ($reply eq 'ok') {
 5500:             return 'error: '.$reply;
 5501:         }   
 5502:         $uhome=&homeserver($uname,$udom,'true');
 5503:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5504: 	    return 'error: unable verify users home machine.';
 5505:         }
 5506:     }   # End of creation of new user
 5507: # ---------------------------------------------------------------------- Add ID
 5508:     if ($uid) {
 5509:        $uid=~tr/A-Z/a-z/;
 5510:        my %uidhash=&idrget($udom,$uname);
 5511:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5512:          && (!$forceid)) {
 5513: 	  unless ($uid eq $uidhash{$uname}) {
 5514: 	      return 'error: user id "'.$uid.'" does not match '.
 5515:                   'current user id "'.$uidhash{$uname}.'".';
 5516:           }
 5517:        } else {
 5518: 	  &idput($udom,($uname => $uid));
 5519:        }
 5520:     }
 5521: # -------------------------------------------------------------- Add names, etc
 5522:     my @tmp=&get('environment',
 5523: 		   ['firstname','middlename','lastname','generation','id',
 5524:                     'permanentemail'],
 5525: 		   $udom,$uname);
 5526:     my %names;
 5527:     if ($tmp[0] =~ m/^error:.*/) { 
 5528:         %names=(); 
 5529:     } else {
 5530:         %names = @tmp;
 5531:     }
 5532: #
 5533: # Make sure to not trash student environment if instructor does not bother
 5534: # to supply name and email information
 5535: #
 5536:     if ($first)  { $names{'firstname'}  = $first; }
 5537:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5538:     if ($last)   { $names{'lastname'}   = $last; }
 5539:     if (defined($gene))   { $names{'generation'} = $gene; }
 5540:     if ($email) {
 5541:        $email=~s/[^\w\@\.\-\,]//gs;
 5542:        if ($email=~/\@/) { $names{'notification'} = $email;
 5543: 			   $names{'critnotification'} = $email;
 5544: 			   $names{'permanentemail'} = $email; }
 5545:     }
 5546:     if ($uid) { $names{'id'}  = $uid; }
 5547:     my $reply = &put('environment', \%names, $udom,$uname);
 5548:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5549:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5550:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5551:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5552:              $umode.', '.$first.', '.$middle.', '.
 5553: 	     $last.', '.$gene.' by '.
 5554:              $env{'user.name'}.' at '.$env{'user.domain'});
 5555:     return 'ok';
 5556: }
 5557: 
 5558: # -------------------------------------------------------------- Modify student
 5559: 
 5560: sub modifystudent {
 5561:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5562:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5563:     if (!$cid) {
 5564: 	unless ($cid=$env{'request.course.id'}) {
 5565: 	    return 'not_in_class';
 5566: 	}
 5567:     }
 5568: # --------------------------------------------------------------- Make the user
 5569:     my $reply=&modifyuser
 5570: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5571:          $desiredhome,$email);
 5572:     unless ($reply eq 'ok') { return $reply; }
 5573:     # This will cause &modify_student_enrollment to get the uid from the
 5574:     # students environment
 5575:     $uid = undef if (!$forceid);
 5576:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5577: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5578:     return $reply;
 5579: }
 5580: 
 5581: sub modify_student_enrollment {
 5582:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
 5583:     my ($cdom,$cnum,$chome);
 5584:     if (!$cid) {
 5585: 	unless ($cid=$env{'request.course.id'}) {
 5586: 	    return 'not_in_class';
 5587: 	}
 5588: 	$cdom=$env{'course.'.$cid.'.domain'};
 5589: 	$cnum=$env{'course.'.$cid.'.num'};
 5590:     } else {
 5591: 	($cdom,$cnum)=split(/_/,$cid);
 5592:     }
 5593:     $chome=$env{'course.'.$cid.'.home'};
 5594:     if (!$chome) {
 5595: 	$chome=&homeserver($cnum,$cdom);
 5596:     }
 5597:     if (!$chome) { return 'unknown_course'; }
 5598:     # Make sure the user exists
 5599:     my $uhome=&homeserver($uname,$udom);
 5600:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5601: 	return 'error: no such user';
 5602:     }
 5603:     # Get student data if we were not given enough information
 5604:     if (!defined($first)  || $first  eq '' || 
 5605:         !defined($last)   || $last   eq '' || 
 5606:         !defined($uid)    || $uid    eq '' || 
 5607:         !defined($middle) || $middle eq '' || 
 5608:         !defined($gene)   || $gene   eq '') {
 5609:         # They did not supply us with enough data to enroll the student, so
 5610:         # we need to pick up more information.
 5611:         my %tmp = &get('environment',
 5612:                        ['firstname','middlename','lastname', 'generation','id']
 5613:                        ,$udom,$uname);
 5614: 
 5615:         #foreach my $key (keys(%tmp)) {
 5616:         #    &logthis("key $key = ".$tmp{$key});
 5617:         #}
 5618:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5619:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5620:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5621:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5622:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5623:     }
 5624:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5625:     my $reply=cput('classlist',
 5626: 		   {"$uname:$udom" => 
 5627: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5628: 		   $cdom,$cnum);
 5629:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5630: 	return 'error: '.$reply;
 5631:     } else {
 5632: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5633:     }
 5634:     # Add student role to user
 5635:     my $uurl='/'.$cid;
 5636:     $uurl=~s/\_/\//g;
 5637:     if ($usec) {
 5638: 	$uurl.='/'.$usec;
 5639:     }
 5640:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
 5641: }
 5642: 
 5643: sub format_name {
 5644:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5645:     my $name;
 5646:     if ($first ne 'lastname') {
 5647: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5648:     } else {
 5649: 	if ($lastname=~/\S/) {
 5650: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5651: 	    $name=~s/\s+,/,/;
 5652: 	} else {
 5653: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5654: 	}
 5655:     }
 5656:     $name=~s/^\s+//;
 5657:     $name=~s/\s+$//;
 5658:     $name=~s/\s+/ /g;
 5659:     return $name;
 5660: }
 5661: 
 5662: # ------------------------------------------------- Write to course preferences
 5663: 
 5664: sub writecoursepref {
 5665:     my ($courseid,%prefs)=@_;
 5666:     $courseid=~s/^\///;
 5667:     $courseid=~s/\_/\//g;
 5668:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5669:     my $chome=homeserver($cnum,$cdomain);
 5670:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5671: 	return 'error: no such course';
 5672:     }
 5673:     my $cstring='';
 5674:     foreach my $pref (keys(%prefs)) {
 5675: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5676:     }
 5677:     $cstring=~s/\&$//;
 5678:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5679: }
 5680: 
 5681: # ---------------------------------------------------------- Make/modify course
 5682: 
 5683: sub createcourse {
 5684:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5685:         $course_owner,$crstype)=@_;
 5686:     $url=&declutter($url);
 5687:     my $cid='';
 5688:     unless (&allowed('ccc',$udom)) {
 5689:         return 'refused';
 5690:     }
 5691: # ------------------------------------------------------------------- Create ID
 5692:    my $uname=int(1+rand(9)).
 5693:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5694:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5695:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5696: # ----------------------------------------------- Make sure that does not exist
 5697:    my $uhome=&homeserver($uname,$udom,'true');
 5698:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5699:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5700:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5701:        $uhome=&homeserver($uname,$udom,'true');       
 5702:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5703:            return 'error: unable to generate unique course-ID';
 5704:        } 
 5705:    }
 5706: # ------------------------------------------------ Check supplied server name
 5707:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5708:     if (! &is_library($course_server)) {
 5709:         return 'error:bad server name '.$course_server;
 5710:     }
 5711: # ------------------------------------------------------------- Make the course
 5712:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5713:                       $course_server);
 5714:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5715:     $uhome=&homeserver($uname,$udom,'true');
 5716:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5717: 	return 'error: no such course';
 5718:     }
 5719: # ----------------------------------------------------------------- Course made
 5720: # log existence
 5721:     my $newcourse = {
 5722:                     $udom.'_'.$uname => {
 5723:                                      description => $description,
 5724:                                      inst_code   => $inst_code,
 5725:                                      owner       => $course_owner,
 5726:                                      type        => $crstype,
 5727:                                                 },
 5728:                     };
 5729:     &courseidput($udom,$newcourse,$uhome,'notime');
 5730: # set toplevel url
 5731:     my $topurl=$url;
 5732:     unless ($nonstandard) {
 5733: # ------------------------------------------ For standard courses, make top url
 5734:         my $mapurl=&clutter($url);
 5735:         if ($mapurl eq '/res/') { $mapurl=''; }
 5736:         $env{'form.initmap'}=(<<ENDINITMAP);
 5737: <map>
 5738: <resource id="1" type="start"></resource>
 5739: <resource id="2" src="$mapurl"></resource>
 5740: <resource id="3" type="finish"></resource>
 5741: <link index="1" from="1" to="2"></link>
 5742: <link index="2" from="2" to="3"></link>
 5743: </map>
 5744: ENDINITMAP
 5745:         $topurl=&declutter(
 5746:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5747:                           );
 5748:     }
 5749: # ----------------------------------------------------------- Write preferences
 5750:     &writecoursepref($udom.'_'.$uname,
 5751:                      ('description' => $description,
 5752:                       'url'         => $topurl));
 5753:     return '/'.$udom.'/'.$uname;
 5754: }
 5755: 
 5756: sub is_course {
 5757:     my ($cdom,$cnum) = @_;
 5758:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5759: 				undef,'.');
 5760:     if (exists($courses{$cdom.'_'.$cnum})) {
 5761:         return 1;
 5762:     }
 5763:     return 0;
 5764: }
 5765: 
 5766: # ---------------------------------------------------------- Assign Custom Role
 5767: 
 5768: sub assigncustomrole {
 5769:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5770:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5771:                        $end,$start,$deleteflag);
 5772: }
 5773: 
 5774: # ----------------------------------------------------------------- Revoke Role
 5775: 
 5776: sub revokerole {
 5777:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5778:     my $now=time;
 5779:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5780: }
 5781: 
 5782: # ---------------------------------------------------------- Revoke Custom Role
 5783: 
 5784: sub revokecustomrole {
 5785:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5786:     my $now=time;
 5787:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5788:            $deleteflag);
 5789: }
 5790: 
 5791: # ------------------------------------------------------------ Disk usage
 5792: sub diskusage {
 5793:     my ($udom,$uname,$directoryRoot)=@_;
 5794:     $directoryRoot =~ s/\/$//;
 5795:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5796:     return $listing;
 5797: }
 5798: 
 5799: sub is_locked {
 5800:     my ($file_name, $domain, $user) = @_;
 5801:     my @check;
 5802:     my $is_locked;
 5803:     push @check, $file_name;
 5804:     my %locked = &get('file_permissions',\@check,
 5805: 		      $env{'user.domain'},$env{'user.name'});
 5806:     my ($tmp)=keys(%locked);
 5807:     if ($tmp=~/^error:/) { undef(%locked); }
 5808:     
 5809:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5810:         $is_locked = 'false';
 5811:         foreach my $entry (@{$locked{$file_name}}) {
 5812:            if (ref($entry) eq 'ARRAY') { 
 5813:                $is_locked = 'true';
 5814:                last;
 5815:            }
 5816:        }
 5817:     } else {
 5818:         $is_locked = 'false';
 5819:     }
 5820: }
 5821: 
 5822: sub declutter_portfile {
 5823:     my ($file) = @_;
 5824:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5825:     return $file;
 5826: }
 5827: 
 5828: # ------------------------------------------------------------- Mark as Read Only
 5829: 
 5830: sub mark_as_readonly {
 5831:     my ($domain,$user,$files,$what) = @_;
 5832:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5833:     my ($tmp)=keys(%current_permissions);
 5834:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5835:     foreach my $file (@{$files}) {
 5836: 	$file = &declutter_portfile($file);
 5837:         push(@{$current_permissions{$file}},$what);
 5838:     }
 5839:     &put('file_permissions',\%current_permissions,$domain,$user);
 5840:     return;
 5841: }
 5842: 
 5843: # ------------------------------------------------------------Save Selected Files
 5844: 
 5845: sub save_selected_files {
 5846:     my ($user, $path, @files) = @_;
 5847:     my $filename = $user."savedfiles";
 5848:     my @other_files = &files_not_in_path($user, $path);
 5849:     open (OUT, '>'.$tmpdir.$filename);
 5850:     foreach my $file (@files) {
 5851:         print (OUT $env{'form.currentpath'}.$file."\n");
 5852:     }
 5853:     foreach my $file (@other_files) {
 5854:         print (OUT $file."\n");
 5855:     }
 5856:     close (OUT);
 5857:     return 'ok';
 5858: }
 5859: 
 5860: sub clear_selected_files {
 5861:     my ($user) = @_;
 5862:     my $filename = $user."savedfiles";
 5863:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5864:     print (OUT undef);
 5865:     close (OUT);
 5866:     return ("ok");    
 5867: }
 5868: 
 5869: sub files_in_path {
 5870:     my ($user, $path) = @_;
 5871:     my $filename = $user."savedfiles";
 5872:     my %return_files;
 5873:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5874:     while (my $line_in = <IN>) {
 5875:         chomp ($line_in);
 5876:         my @paths_and_file = split (m!/!, $line_in);
 5877:         my $file_part = pop (@paths_and_file);
 5878:         my $path_part = join ('/', @paths_and_file);
 5879:         $path_part.='/';
 5880:         my $path_and_file = $path_part.$file_part;
 5881:         if ($path_part eq $path) {
 5882:             $return_files{$file_part}= 'selected';
 5883:         }
 5884:     }
 5885:     close (IN);
 5886:     return (\%return_files);
 5887: }
 5888: 
 5889: # called in portfolio select mode, to show files selected NOT in current directory
 5890: sub files_not_in_path {
 5891:     my ($user, $path) = @_;
 5892:     my $filename = $user."savedfiles";
 5893:     my @return_files;
 5894:     my $path_part;
 5895:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5896:     while (my $line = <IN>) {
 5897:         #ok, I know it's clunky, but I want it to work
 5898:         my @paths_and_file = split(m|/|, $line);
 5899:         my $file_part = pop(@paths_and_file);
 5900:         chomp($file_part);
 5901:         my $path_part = join('/', @paths_and_file);
 5902:         $path_part .= '/';
 5903:         my $path_and_file = $path_part.$file_part;
 5904:         if ($path_part ne $path) {
 5905:             push(@return_files, ($path_and_file));
 5906:         }
 5907:     }
 5908:     close(OUT);
 5909:     return (@return_files);
 5910: }
 5911: 
 5912: #----------------------------------------------Get portfolio file permissions
 5913: 
 5914: sub get_portfile_permissions {
 5915:     my ($domain,$user) = @_;
 5916:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5917:     my ($tmp)=keys(%current_permissions);
 5918:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5919:     return \%current_permissions;
 5920: }
 5921: 
 5922: #---------------------------------------------Get portfolio file access controls
 5923: 
 5924: sub get_access_controls {
 5925:     my ($current_permissions,$group,$file) = @_;
 5926:     my %access;
 5927:     my $real_file = $file;
 5928:     $file =~ s/\.meta$//;
 5929:     if (defined($file)) {
 5930:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5931:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5932:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5933:             }
 5934:         }
 5935:     } else {
 5936:         foreach my $key (keys(%{$current_permissions})) {
 5937:             if ($key =~ /\0accesscontrol$/) {
 5938:                 if (defined($group)) {
 5939:                     if ($key !~ m-^\Q$group\E/-) {
 5940:                         next;
 5941:                     }
 5942:                 }
 5943:                 my ($fullpath) = split(/\0/,$key);
 5944:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5945:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5946:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5947:                     }
 5948:                 }
 5949:             }
 5950:         }
 5951:     }
 5952:     return %access;
 5953: }
 5954: 
 5955: sub modify_access_controls {
 5956:     my ($file_name,$changes,$domain,$user)=@_;
 5957:     my ($outcome,$deloutcome);
 5958:     my %store_permissions;
 5959:     my %new_values;
 5960:     my %new_control;
 5961:     my %translation;
 5962:     my @deletions = ();
 5963:     my $now = time;
 5964:     if (exists($$changes{'activate'})) {
 5965:         if (ref($$changes{'activate'}) eq 'HASH') {
 5966:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5967:             my $numnew = scalar(@newitems);
 5968:             for (my $i=0; $i<$numnew; $i++) {
 5969:                 my $newkey = $newitems[$i];
 5970:                 my $newid = &Apache::loncommon::get_cgi_id();
 5971:                 if ($newkey =~ /^\d+:/) { 
 5972:                     $newkey =~ s/^(\d+)/$newid/;
 5973:                     $translation{$1} = $newid;
 5974:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5975:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5976:                     $translation{$1} = $newid;
 5977:                 }
 5978:                 $new_values{$file_name."\0".$newkey} = 
 5979:                                           $$changes{'activate'}{$newitems[$i]};
 5980:                 $new_control{$newkey} = $now;
 5981:             }
 5982:         }
 5983:     }
 5984:     my %todelete;
 5985:     my %changed_items;
 5986:     foreach my $action ('delete','update') {
 5987:         if (exists($$changes{$action})) {
 5988:             if (ref($$changes{$action}) eq 'HASH') {
 5989:                 foreach my $key (keys(%{$$changes{$action}})) {
 5990:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5991:                     if ($action eq 'delete') { 
 5992:                         $todelete{$itemnum} = 1;
 5993:                     } else {
 5994:                         $changed_items{$itemnum} = $key;
 5995:                     }
 5996:                 }
 5997:             }
 5998:         }
 5999:     }
 6000:     # get lock on access controls for file.
 6001:     my $lockhash = {
 6002:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6003:                                                        ':'.$env{'user.domain'},
 6004:                    }; 
 6005:     my $tries = 0;
 6006:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6007:    
 6008:     while (($gotlock ne 'ok') && $tries <3) {
 6009:         $tries ++;
 6010:         sleep 1;
 6011:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6012:     }
 6013:     if ($gotlock eq 'ok') {
 6014:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6015:         my ($tmp)=keys(%curr_permissions);
 6016:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6017:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6018:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6019:             if (ref($curr_controls) eq 'HASH') {
 6020:                 foreach my $control_item (keys(%{$curr_controls})) {
 6021:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6022:                     if (defined($todelete{$itemnum})) {
 6023:                         push(@deletions,$file_name."\0".$control_item);
 6024:                     } else {
 6025:                         if (defined($changed_items{$itemnum})) {
 6026:                             $new_control{$changed_items{$itemnum}} = $now;
 6027:                             push(@deletions,$file_name."\0".$control_item);
 6028:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6029:                         } else {
 6030:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6031:                         }
 6032:                     }
 6033:                 }
 6034:             }
 6035:         }
 6036:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6037:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6038:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6039:         #  remove lock
 6040:         my @del_lock = ($file_name."\0".'locked_access_records');
 6041:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6042:         my ($file,$group);
 6043:         if (&is_course($domain,$user)) {
 6044:             ($group,$file) = split(/\//,$file_name,2);
 6045:         } else {
 6046:             $file = $file_name;
 6047:         }
 6048:         my $sqlresult =
 6049:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 6050:                                     $group);
 6051:     } else {
 6052:         $outcome = "error: could not obtain lockfile\n";  
 6053:     }
 6054:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6055: }
 6056: 
 6057: sub make_public_indefinitely {
 6058:     my ($requrl) = @_;
 6059:     my $now = time;
 6060:     my $action = 'activate';
 6061:     my $aclnum = 0;
 6062:     if (&is_portfolio_url($requrl)) {
 6063:         my (undef,$udom,$unum,$file_name,$group) =
 6064:             &parse_portfolio_url($requrl);
 6065:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6066:         my %access_controls = &get_access_controls($current_perms,
 6067:                                                    $group,$file_name);
 6068:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6069:             my ($num,$scope,$end,$start) = 
 6070:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6071:             if ($scope eq 'public') {
 6072:                 if ($start <= $now && $end == 0) {
 6073:                     $action = 'none';
 6074:                 } else {
 6075:                     $action = 'update';
 6076:                     $aclnum = $num;
 6077:                 }
 6078:                 last;
 6079:             }
 6080:         }
 6081:         if ($action eq 'none') {
 6082:              return 'ok';
 6083:         } else {
 6084:             my %changes;
 6085:             my $newend = 0;
 6086:             my $newstart = $now;
 6087:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6088:             $changes{$action}{$newkey} = {
 6089:                 type => 'public',
 6090:                 time => {
 6091:                     start => $newstart,
 6092:                     end   => $newend,
 6093:                 },
 6094:             };
 6095:             my ($outcome,$deloutcome,$new_values,$translation) =
 6096:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6097:             return $outcome;
 6098:         }
 6099:     } else {
 6100:         return 'invalid';
 6101:     }
 6102: }
 6103: 
 6104: #------------------------------------------------------Get Marked as Read Only
 6105: 
 6106: sub get_marked_as_readonly {
 6107:     my ($domain,$user,$what,$group) = @_;
 6108:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6109:     my @readonly_files;
 6110:     my $cmp1=$what;
 6111:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6112:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6113:         if (defined($group)) {
 6114:             if ($file_name !~ m-^\Q$group\E/-) {
 6115:                 next;
 6116:             }
 6117:         }
 6118:         if (ref($value) eq "ARRAY"){
 6119:             foreach my $stored_what (@{$value}) {
 6120:                 my $cmp2=$stored_what;
 6121:                 if (ref($stored_what) eq 'ARRAY') {
 6122:                     $cmp2=join('',@{$stored_what});
 6123:                 }
 6124:                 if ($cmp1 eq $cmp2) {
 6125:                     push(@readonly_files, $file_name);
 6126:                     last;
 6127:                 } elsif (!defined($what)) {
 6128:                     push(@readonly_files, $file_name);
 6129:                     last;
 6130:                 }
 6131:             }
 6132:         }
 6133:     }
 6134:     return @readonly_files;
 6135: }
 6136: #-----------------------------------------------------------Get Marked as Read Only Hash
 6137: 
 6138: sub get_marked_as_readonly_hash {
 6139:     my ($current_permissions,$group,$what) = @_;
 6140:     my %readonly_files;
 6141:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6142:         if (defined($group)) {
 6143:             if ($file_name !~ m-^\Q$group\E/-) {
 6144:                 next;
 6145:             }
 6146:         }
 6147:         if (ref($value) eq "ARRAY"){
 6148:             foreach my $stored_what (@{$value}) {
 6149:                 if (ref($stored_what) eq 'ARRAY') {
 6150:                     foreach my $lock_descriptor(@{$stored_what}) {
 6151:                         if ($lock_descriptor eq 'graded') {
 6152:                             $readonly_files{$file_name} = 'graded';
 6153:                         } elsif ($lock_descriptor eq 'handback') {
 6154:                             $readonly_files{$file_name} = 'handback';
 6155:                         } else {
 6156:                             if (!exists($readonly_files{$file_name})) {
 6157:                                 $readonly_files{$file_name} = 'locked';
 6158:                             }
 6159:                         }
 6160:                     }
 6161:                 } 
 6162:             }
 6163:         } 
 6164:     }
 6165:     return %readonly_files;
 6166: }
 6167: # ------------------------------------------------------------ Unmark as Read Only
 6168: 
 6169: sub unmark_as_readonly {
 6170:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6171:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6172:     my ($domain,$user,$what,$file_name,$group) = @_;
 6173:     $file_name = &declutter_portfile($file_name);
 6174:     my $symb_crs = $what;
 6175:     if (ref($what)) { $symb_crs=join('',@$what); }
 6176:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6177:     my ($tmp)=keys(%current_permissions);
 6178:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6179:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6180:     foreach my $file (@readonly_files) {
 6181: 	my $clean_file = &declutter_portfile($file);
 6182: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6183: 	my $current_locks = $current_permissions{$file};
 6184:         my @new_locks;
 6185:         my @del_keys;
 6186:         if (ref($current_locks) eq "ARRAY"){
 6187:             foreach my $locker (@{$current_locks}) {
 6188:                 my $compare=$locker;
 6189:                 if (ref($locker) eq 'ARRAY') {
 6190:                     $compare=join('',@{$locker});
 6191:                     if ($compare ne $symb_crs) {
 6192:                         push(@new_locks, $locker);
 6193:                     }
 6194:                 }
 6195:             }
 6196:             if (scalar(@new_locks) > 0) {
 6197:                 $current_permissions{$file} = \@new_locks;
 6198:             } else {
 6199:                 push(@del_keys, $file);
 6200:                 &del('file_permissions',\@del_keys, $domain, $user);
 6201:                 delete($current_permissions{$file});
 6202:             }
 6203:         }
 6204:     }
 6205:     &put('file_permissions',\%current_permissions,$domain,$user);
 6206:     return;
 6207: }
 6208: 
 6209: # ------------------------------------------------------------ Directory lister
 6210: 
 6211: sub dirlist {
 6212:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6213: 
 6214:     $uri=~s/^\///;
 6215:     $uri=~s/\/$//;
 6216:     my ($udom, $uname);
 6217:     (undef,$udom,$uname)=split(/\//,$uri);
 6218:     if(defined($userdomain)) {
 6219:         $udom = $userdomain;
 6220:     }
 6221:     if(defined($username)) {
 6222:         $uname = $username;
 6223:     }
 6224: 
 6225:     my $dirRoot = $perlvar{'lonDocRoot'};
 6226:     if(defined($alternateDirectoryRoot)) {
 6227:         $dirRoot = $alternateDirectoryRoot;
 6228:         $dirRoot =~ s/\/$//;
 6229:     }
 6230: 
 6231:     if($udom) {
 6232:         if($uname) {
 6233:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6234: 				 &homeserver($uname,$udom));
 6235:             my @listing_results;
 6236:             if ($listing eq 'unknown_cmd') {
 6237:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6238: 				  &homeserver($uname,$udom));
 6239:                 @listing_results = split(/:/,$listing);
 6240:             } else {
 6241:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6242:             }
 6243:             return @listing_results;
 6244:         } elsif(!defined($alternateDirectoryRoot)) {
 6245:             my %allusers;
 6246: 	    my %servers = &get_servers($udom,'library');
 6247: 	    foreach my $tryserver (keys(%servers)) {
 6248: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6249: 				     $udom, $tryserver);
 6250: 		my @listing_results;
 6251: 		if ($listing eq 'unknown_cmd') {
 6252: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6253: 				      $udom, $tryserver);
 6254: 		    @listing_results = split(/:/,$listing);
 6255: 		} else {
 6256: 		    @listing_results =
 6257: 			map { &unescape($_); } split(/:/,$listing);
 6258: 		}
 6259: 		if ($listing_results[0] ne 'no_such_dir' && 
 6260: 		    $listing_results[0] ne 'empty'       &&
 6261: 		    $listing_results[0] ne 'con_lost') {
 6262: 		    foreach my $line (@listing_results) {
 6263: 			my ($entry) = split(/&/,$line,2);
 6264: 			$allusers{$entry} = 1;
 6265: 		    }
 6266: 		}
 6267:             }
 6268:             my $alluserstr='';
 6269:             foreach my $user (sort(keys(%allusers))) {
 6270:                 $alluserstr.=$user.'&user:';
 6271:             }
 6272:             $alluserstr=~s/:$//;
 6273:             return split(/:/,$alluserstr);
 6274:         } else {
 6275:             return ('missing user name');
 6276:         }
 6277:     } elsif(!defined($alternateDirectoryRoot)) {
 6278:         my @all_domains = sort(&all_domains());
 6279:          foreach my $domain (@all_domains) {
 6280:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6281:          }
 6282:          return @all_domains;
 6283:      } else {
 6284:         return ('missing domain');
 6285:     }
 6286: }
 6287: 
 6288: # --------------------------------------------- GetFileTimestamp
 6289: # This function utilizes dirlist and returns the date stamp for
 6290: # when it was last modified.  It will also return an error of -1
 6291: # if an error occurs
 6292: 
 6293: ##
 6294: ## FIXME: This subroutine assumes its caller knows something about the
 6295: ## directory structure of the home server for the student ($root).
 6296: ## Not a good assumption to make.  Since this is for looking up files
 6297: ## in user directories, the full path should be constructed by lond, not
 6298: ## whatever machine we request data from.
 6299: ##
 6300: sub GetFileTimestamp {
 6301:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6302:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6303:     $studentName   = &LONCAPA::clean_username($studentName);
 6304:     my $subdir=$studentName.'__';
 6305:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6306:     my $proname="$studentDomain/$subdir/$studentName";
 6307:     $proname .= '/'.$filename;
 6308:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6309:                                               $studentName, $root);
 6310:     my @stats = split('&', $fileStat);
 6311:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6312:         # @stats contains first the filename, then the stat output
 6313:         return $stats[10]; # so this is 10 instead of 9.
 6314:     } else {
 6315:         return -1;
 6316:     }
 6317: }
 6318: 
 6319: sub stat_file {
 6320:     my ($uri) = @_;
 6321:     $uri = &clutter_with_no_wrapper($uri);
 6322: 
 6323:     my ($udom,$uname,$file,$dir);
 6324:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6325: 	($udom,$uname,$file) =
 6326: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6327: 	$file = 'userfiles/'.$file;
 6328: 	$dir = &propath($udom,$uname);
 6329:     }
 6330:     if ($uri =~ m-^/res/-) {
 6331: 	($udom,$uname) = 
 6332: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6333: 	$file = $uri;
 6334:     }
 6335: 
 6336:     if (!$udom || !$uname || !$file) {
 6337: 	# unable to handle the uri
 6338: 	return ();
 6339:     }
 6340: 
 6341:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6342:     my @stats = split('&', $result);
 6343:     
 6344:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6345: 	shift(@stats); #filename is first
 6346: 	return @stats;
 6347:     }
 6348:     return ();
 6349: }
 6350: 
 6351: # -------------------------------------------------------- Value of a Condition
 6352: 
 6353: # gets the value of a specific preevaluated condition
 6354: #    stored in the string  $env{user.state.<cid>}
 6355: # or looks up a condition reference in the bighash and if if hasn't
 6356: # already been evaluated recurses into docondval to get the value of
 6357: # the condition, then memoizing it to 
 6358: #   $env{user.state.<cid>.<condition>}
 6359: sub directcondval {
 6360:     my $number=shift;
 6361:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6362: 	&Apache::lonuserstate::evalstate();
 6363:     }
 6364:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6365: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6366:     } elsif ($number =~ /^_/) {
 6367: 	my $sub_condition;
 6368: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6369: 		&GDBM_READER(),0640)) {
 6370: 	    $sub_condition=$bighash{'conditions'.$number};
 6371: 	    untie(%bighash);
 6372: 	}
 6373: 	my $value = &docondval($sub_condition);
 6374: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6375: 	return $value;
 6376:     }
 6377:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6378:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6379:     } else {
 6380:        return 2;
 6381:     }
 6382: }
 6383: 
 6384: # get the collection of conditions for this resource
 6385: sub condval {
 6386:     my $condidx=shift;
 6387:     my $allpathcond='';
 6388:     foreach my $cond (split(/\|/,$condidx)) {
 6389: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6390: 	    $allpathcond.=
 6391: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6392: 	}
 6393:     }
 6394:     $allpathcond=~s/\|$//;
 6395:     return &docondval($allpathcond);
 6396: }
 6397: 
 6398: #evaluates an expression of conditions
 6399: sub docondval {
 6400:     my ($allpathcond) = @_;
 6401:     my $result=0;
 6402:     if ($env{'request.course.id'}
 6403: 	&& defined($allpathcond)) {
 6404: 	my $operand='|';
 6405: 	my @stack;
 6406: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6407: 	    if ($chunk eq '(') {
 6408: 		push @stack,($operand,$result);
 6409: 	    } elsif ($chunk eq ')') {
 6410: 		my $before=pop @stack;
 6411: 		if (pop @stack eq '&') {
 6412: 		    $result=$result>$before?$before:$result;
 6413: 		} else {
 6414: 		    $result=$result>$before?$result:$before;
 6415: 		}
 6416: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6417: 		$operand=$chunk;
 6418: 	    } else {
 6419: 		my $new=directcondval($chunk);
 6420: 		if ($operand eq '&') {
 6421: 		    $result=$result>$new?$new:$result;
 6422: 		} else {
 6423: 		    $result=$result>$new?$result:$new;
 6424: 		}
 6425: 	    }
 6426: 	}
 6427:     }
 6428:     return $result;
 6429: }
 6430: 
 6431: # ---------------------------------------------------- Devalidate courseresdata
 6432: 
 6433: sub devalidatecourseresdata {
 6434:     my ($coursenum,$coursedomain)=@_;
 6435:     my $hashid=$coursenum.':'.$coursedomain;
 6436:     &devalidate_cache_new('courseres',$hashid);
 6437: }
 6438: 
 6439: 
 6440: # --------------------------------------------------- Course Resourcedata Query
 6441: #
 6442: #  Parameters:
 6443: #      $coursenum    - Number of the course.
 6444: #      $coursedomain - Domain at which the course was created.
 6445: #  Returns:
 6446: #     A hash of the course parameters along (I think) with timestamps
 6447: #     and version info.
 6448: 
 6449: sub get_courseresdata {
 6450:     my ($coursenum,$coursedomain)=@_;
 6451:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6452:     my $hashid=$coursenum.':'.$coursedomain;
 6453:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6454:     my %dumpreply;
 6455:     unless (defined($cached)) {
 6456: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6457: 	$result=\%dumpreply;
 6458: 	my ($tmp) = keys(%dumpreply);
 6459: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6460: 	    &do_cache_new('courseres',$hashid,$result,600);
 6461: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6462: 	    return $tmp;
 6463: 	} elsif ($tmp =~ /^(error)/) {
 6464: 	    $result=undef;
 6465: 	    &do_cache_new('courseres',$hashid,$result,600);
 6466: 	}
 6467:     }
 6468:     return $result;
 6469: }
 6470: 
 6471: sub devalidateuserresdata {
 6472:     my ($uname,$udom)=@_;
 6473:     my $hashid="$udom:$uname";
 6474:     &devalidate_cache_new('userres',$hashid);
 6475: }
 6476: 
 6477: sub get_userresdata {
 6478:     my ($uname,$udom)=@_;
 6479:     #most student don\'t have any data set, check if there is some data
 6480:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6481: 
 6482:     my $hashid="$udom:$uname";
 6483:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6484:     if (!defined($cached)) {
 6485: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6486: 	$result=\%resourcedata;
 6487: 	&do_cache_new('userres',$hashid,$result,600);
 6488:     }
 6489:     my ($tmp)=keys(%$result);
 6490:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6491: 	return $result;
 6492:     }
 6493:     #error 2 occurs when the .db doesn't exist
 6494:     if ($tmp!~/error: 2 /) {
 6495: 	&logthis("<font color=\"blue\">WARNING:".
 6496: 		 " Trying to get resource data for ".
 6497: 		 $uname." at ".$udom.": ".
 6498: 		 $tmp."</font>");
 6499:     } elsif ($tmp=~/error: 2 /) {
 6500: 	#&EXT_cache_set($udom,$uname);
 6501: 	&do_cache_new('userres',$hashid,undef,600);
 6502: 	undef($tmp); # not really an error so don't send it back
 6503:     }
 6504:     return $tmp;
 6505: }
 6506: #----------------------------------------------- resdata - return resource data
 6507: #  Purpose:
 6508: #    Return resource data for either users or for a course.
 6509: #  Parameters:
 6510: #     $name      - Course/user name.
 6511: #     $domain    - Name of the domain the user/course is registered on.
 6512: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6513: #     @which     - Array of names of resources desired.
 6514: #  Returns:
 6515: #     The value of the first reasource in @which that is found in the
 6516: #     resource hash.
 6517: #  Exceptional Conditions:
 6518: #     If the $type passed in is not valid (not the string 'course' or 
 6519: #     'user', an undefined  reference is returned.
 6520: #     If none of the resources are found, an undef is returned
 6521: sub resdata {
 6522:     my ($name,$domain,$type,@which)=@_;
 6523:     my $result;
 6524:     if ($type eq 'course') {
 6525: 	$result=&get_courseresdata($name,$domain);
 6526:     } elsif ($type eq 'user') {
 6527: 	$result=&get_userresdata($name,$domain);
 6528:     }
 6529:     if (!ref($result)) { return $result; }    
 6530:     foreach my $item (@which) {
 6531: 	if (defined($result->{$item->[0]})) {
 6532: 	    return [$result->{$item->[0]},$item->[1]];
 6533: 	}
 6534:     }
 6535:     return undef;
 6536: }
 6537: 
 6538: #
 6539: # EXT resource caching routines
 6540: #
 6541: 
 6542: sub clear_EXT_cache_status {
 6543:     &delenv('cache.EXT.');
 6544: }
 6545: 
 6546: sub EXT_cache_status {
 6547:     my ($target_domain,$target_user) = @_;
 6548:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6549:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6550:         # We know already the user has no data
 6551:         return 1;
 6552:     } else {
 6553:         return 0;
 6554:     }
 6555: }
 6556: 
 6557: sub EXT_cache_set {
 6558:     my ($target_domain,$target_user) = @_;
 6559:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6560:     #&appenv({$cachename => time});
 6561: }
 6562: 
 6563: # --------------------------------------------------------- Value of a Variable
 6564: sub EXT {
 6565: 
 6566:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6567:     unless ($varname) { return ''; }
 6568:     #get real user name/domain, courseid and symb
 6569:     my $courseid;
 6570:     my $publicuser;
 6571:     if ($symbparm) {
 6572: 	$symbparm=&get_symb_from_alias($symbparm);
 6573:     }
 6574:     if (!($uname && $udom)) {
 6575:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6576:       if (!$symbparm) {	$symbparm=$cursymb; }
 6577:     } else {
 6578: 	$courseid=$env{'request.course.id'};
 6579:     }
 6580:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6581:     my $rest;
 6582:     if (defined($therest[0])) {
 6583:        $rest=join('.',@therest);
 6584:     } else {
 6585:        $rest='';
 6586:     }
 6587: 
 6588:     my $qualifierrest=$qualifier;
 6589:     if ($rest) { $qualifierrest.='.'.$rest; }
 6590:     my $spacequalifierrest=$space;
 6591:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6592:     if ($realm eq 'user') {
 6593: # --------------------------------------------------------------- user.resource
 6594: 	if ($space eq 'resource') {
 6595: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6596: 		  || defined($Apache::lonhomework::parsing_a_task))
 6597: 		 &&
 6598: 		 ($symbparm eq &symbread()) ) {	
 6599: 		# if we are in the middle of processing the resource the
 6600: 		# get the value we are planning on committing
 6601:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6602:                     return $Apache::lonhomework::results{$qualifierrest};
 6603:                 } else {
 6604:                     return $Apache::lonhomework::history{$qualifierrest};
 6605:                 }
 6606: 	    } else {
 6607: 		my %restored;
 6608: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6609: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6610: 		} else {
 6611: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6612: 		}
 6613: 		return $restored{$qualifierrest};
 6614: 	    }
 6615: # ----------------------------------------------------------------- user.access
 6616:         } elsif ($space eq 'access') {
 6617: 	    # FIXME - not supporting calls for a specific user
 6618:             return &allowed($qualifier,$rest);
 6619: # ------------------------------------------ user.preferences, user.environment
 6620:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6621: 	    if (($uname eq $env{'user.name'}) &&
 6622: 		($udom eq $env{'user.domain'})) {
 6623: 		return $env{join('.',('environment',$qualifierrest))};
 6624: 	    } else {
 6625: 		my %returnhash;
 6626: 		if (!$publicuser) {
 6627: 		    %returnhash=&userenvironment($udom,$uname,
 6628: 						 $qualifierrest);
 6629: 		}
 6630: 		return $returnhash{$qualifierrest};
 6631: 	    }
 6632: # ----------------------------------------------------------------- user.course
 6633:         } elsif ($space eq 'course') {
 6634: 	    # FIXME - not supporting calls for a specific user
 6635:             return $env{join('.',('request.course',$qualifier))};
 6636: # ------------------------------------------------------------------- user.role
 6637:         } elsif ($space eq 'role') {
 6638: 	    # FIXME - not supporting calls for a specific user
 6639:             my ($role,$where)=split(/\./,$env{'request.role'});
 6640:             if ($qualifier eq 'value') {
 6641: 		return $role;
 6642:             } elsif ($qualifier eq 'extent') {
 6643:                 return $where;
 6644:             }
 6645: # ----------------------------------------------------------------- user.domain
 6646:         } elsif ($space eq 'domain') {
 6647:             return $udom;
 6648: # ------------------------------------------------------------------- user.name
 6649:         } elsif ($space eq 'name') {
 6650:             return $uname;
 6651: # ---------------------------------------------------- Any other user namespace
 6652:         } else {
 6653: 	    my %reply;
 6654: 	    if (!$publicuser) {
 6655: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6656: 	    }
 6657: 	    return $reply{$qualifierrest};
 6658:         }
 6659:     } elsif ($realm eq 'query') {
 6660: # ---------------------------------------------- pull stuff out of query string
 6661:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6662: 						[$spacequalifierrest]);
 6663: 	return $env{'form.'.$spacequalifierrest}; 
 6664:    } elsif ($realm eq 'request') {
 6665: # ------------------------------------------------------------- request.browser
 6666:         if ($space eq 'browser') {
 6667: 	    if ($qualifier eq 'textremote') {
 6668: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6669: 		    return 1;
 6670: 		} else {
 6671: 		    return 0;
 6672: 		}
 6673: 	    } else {
 6674: 		return $env{'browser.'.$qualifier};
 6675: 	    }
 6676: # ------------------------------------------------------------ request.filename
 6677:         } else {
 6678:             return $env{'request.'.$spacequalifierrest};
 6679:         }
 6680:     } elsif ($realm eq 'course') {
 6681: # ---------------------------------------------------------- course.description
 6682:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6683:     } elsif ($realm eq 'resource') {
 6684: 
 6685: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6686: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6687: 	}
 6688: 
 6689: 	if ($space eq 'title') {
 6690: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6691: 	    return &gettitle($symbparm);
 6692: 	}
 6693: 	
 6694: 	if ($space eq 'map') {
 6695: 	    my ($map) = &decode_symb($symbparm);
 6696: 	    return &symbread($map);
 6697: 	}
 6698: 	if ($space eq 'filename') {
 6699: 	    if ($symbparm) {
 6700: 		return &clutter((&decode_symb($symbparm))[2]);
 6701: 	    }
 6702: 	    return &hreflocation('',$env{'request.filename'});
 6703: 	}
 6704: 
 6705: 	my ($section, $group, @groups);
 6706: 	my ($courselevelm,$courselevel);
 6707: 	if ($symbparm && defined($courseid) && 
 6708: 	    $courseid eq $env{'request.course.id'}) {
 6709: 
 6710: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6711: 
 6712: # ----------------------------------------------------- Cascading lookup scheme
 6713: 	    my $symbp=$symbparm;
 6714: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6715: 
 6716: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6717: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6718: 
 6719: 	    if (($env{'user.name'} eq $uname) &&
 6720: 		($env{'user.domain'} eq $udom)) {
 6721: 		$section=$env{'request.course.sec'};
 6722:                 @groups = split(/:/,$env{'request.course.groups'});  
 6723:                 @groups=&sort_course_groups($courseid,@groups); 
 6724: 	    } else {
 6725: 		if (! defined($usection)) {
 6726: 		    $section=&getsection($udom,$uname,$courseid);
 6727: 		} else {
 6728: 		    $section = $usection;
 6729: 		}
 6730:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6731: 	    }
 6732: 
 6733: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6734: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6735: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6736: 
 6737: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6738: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6739: 	    $courselevelm=$courseid.'.'.$mapparm;
 6740: 
 6741: # ----------------------------------------------------------- first, check user
 6742: 
 6743: 	    my $userreply=&resdata($uname,$udom,'user',
 6744: 				       ([$courselevelr,'resource'],
 6745: 					[$courselevelm,'map'     ],
 6746: 					[$courselevel, 'course'  ]));
 6747: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6748: 
 6749: # ------------------------------------------------ second, check some of course
 6750:             my $coursereply;
 6751:             if (@groups > 0) {
 6752:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6753:                                        $mapparm,$spacequalifierrest);
 6754:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6755:             }
 6756: 
 6757: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6758: 				  $env{'course.'.$courseid.'.domain'},
 6759: 				  'course',
 6760: 				  ([$seclevelr,   'resource'],
 6761: 				   [$seclevelm,   'map'     ],
 6762: 				   [$seclevel,    'course'  ],
 6763: 				   [$courselevelr,'resource']));
 6764: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6765: 
 6766: # ------------------------------------------------------ third, check map parms
 6767: 	    my %parmhash=();
 6768: 	    my $thisparm='';
 6769: 	    if (tie(%parmhash,'GDBM_File',
 6770: 		    $env{'request.course.fn'}.'_parms.db',
 6771: 		    &GDBM_READER(),0640)) {
 6772: 		$thisparm=$parmhash{$symbparm};
 6773: 		untie(%parmhash);
 6774: 	    }
 6775: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6776: 	}
 6777: # ------------------------------------------ fourth, look in resource metadata
 6778: 
 6779: 	$spacequalifierrest=~s/\./\_/;
 6780: 	my $filename;
 6781: 	if (!$symbparm) { $symbparm=&symbread(); }
 6782: 	if ($symbparm) {
 6783: 	    $filename=(&decode_symb($symbparm))[2];
 6784: 	} else {
 6785: 	    $filename=$env{'request.filename'};
 6786: 	}
 6787: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6788: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6789: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6790: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6791: 
 6792: # ---------------------------------------------- fourth, look in rest of course
 6793: 	if ($symbparm && defined($courseid) && 
 6794: 	    $courseid eq $env{'request.course.id'}) {
 6795: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6796: 				     $env{'course.'.$courseid.'.domain'},
 6797: 				     'course',
 6798: 				     ([$courselevelm,'map'   ],
 6799: 				      [$courselevel, 'course']));
 6800: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6801: 	}
 6802: # ------------------------------------------------------------------ Cascade up
 6803: 	unless ($space eq '0') {
 6804: 	    my @parts=split(/_/,$space);
 6805: 	    my $id=pop(@parts);
 6806: 	    my $part=join('_',@parts);
 6807: 	    if ($part eq '') { $part='0'; }
 6808: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6809: 				 $symbparm,$udom,$uname,$section,1);
 6810: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6811: 	}
 6812: 	if ($recurse) { return undef; }
 6813: 	my $pack_def=&packages_tab_default($filename,$varname);
 6814: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6815: # ---------------------------------------------------- Any other user namespace
 6816:     } elsif ($realm eq 'environment') {
 6817: # ----------------------------------------------------------------- environment
 6818: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6819: 	    return $env{'environment.'.$spacequalifierrest};
 6820: 	} else {
 6821: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6822: 		return '';
 6823: 	    }
 6824: 	    my %returnhash=&userenvironment($udom,$uname,
 6825: 					    $spacequalifierrest);
 6826: 	    return $returnhash{$spacequalifierrest};
 6827: 	}
 6828:     } elsif ($realm eq 'system') {
 6829: # ----------------------------------------------------------------- system.time
 6830: 	if ($space eq 'time') {
 6831: 	    return time;
 6832:         }
 6833:     } elsif ($realm eq 'server') {
 6834: # ----------------------------------------------------------------- system.time
 6835: 	if ($space eq 'name') {
 6836: 	    return $ENV{'SERVER_NAME'};
 6837:         }
 6838:     }
 6839:     return '';
 6840: }
 6841: 
 6842: sub get_reply {
 6843:     my ($reply_value) = @_;
 6844:     if (ref($reply_value) eq 'ARRAY') {
 6845:         if (wantarray) {
 6846: 	    return @$reply_value;
 6847:         }
 6848:         return $reply_value->[0];
 6849:     } else {
 6850:         return $reply_value;
 6851:     }
 6852: }
 6853: 
 6854: sub check_group_parms {
 6855:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6856:     my @groupitems = ();
 6857:     my $resultitem;
 6858:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6859:     foreach my $group (@{$groups}) {
 6860:         foreach my $level (@levels) {
 6861:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6862:              push(@groupitems,[$item,$level->[1]]);
 6863:         }
 6864:     }
 6865:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6866:                             $env{'course.'.$courseid.'.domain'},
 6867:                                      'course',@groupitems);
 6868:     return $coursereply;
 6869: }
 6870: 
 6871: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6872:     my ($courseid,@groups) = @_;
 6873:     @groups = sort(@groups);
 6874:     return @groups;
 6875: }
 6876: 
 6877: sub packages_tab_default {
 6878:     my ($uri,$varname)=@_;
 6879:     my (undef,$part,$name)=split(/\./,$varname);
 6880: 
 6881:     my (@extension,@specifics,$do_default);
 6882:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6883: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6884: 	if ($pack_type eq 'default') {
 6885: 	    $do_default=1;
 6886: 	} elsif ($pack_type eq 'extension') {
 6887: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6888: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6889: 	    # only look at packages defaults for packages that this id is
 6890: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6891: 	}
 6892:     }
 6893:     # first look for a package that matches the requested part id
 6894:     foreach my $package (@specifics) {
 6895: 	my (undef,$pack_type,$pack_part)=@{$package};
 6896: 	next if ($pack_part ne $part);
 6897: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6898: 	    return $packagetab{"$pack_type&$name&default"};
 6899: 	}
 6900:     }
 6901:     # look for any possible matching non extension_ package
 6902:     foreach my $package (@specifics) {
 6903: 	my (undef,$pack_type,$pack_part)=@{$package};
 6904: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6905: 	    return $packagetab{"$pack_type&$name&default"};
 6906: 	}
 6907: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6908: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6909: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6910: 	}
 6911:     }
 6912:     # look for any posible extension_ match
 6913:     foreach my $package (@extension) {
 6914: 	my ($package,$pack_type)=@{$package};
 6915: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6916: 	    return $packagetab{"$pack_type&$name&default"};
 6917: 	}
 6918: 	if (defined($packagetab{$package."&$name&default"})) {
 6919: 	    return $packagetab{$package."&$name&default"};
 6920: 	}
 6921:     }
 6922:     # look for a global default setting
 6923:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6924: 	return $packagetab{"default&$name&default"};
 6925:     }
 6926:     return undef;
 6927: }
 6928: 
 6929: sub add_prefix_and_part {
 6930:     my ($prefix,$part)=@_;
 6931:     my $keyroot;
 6932:     if (defined($prefix) && $prefix !~ /^__/) {
 6933: 	# prefix that has a part already
 6934: 	$keyroot=$prefix;
 6935:     } elsif (defined($prefix)) {
 6936: 	# prefix that is missing a part
 6937: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6938:     } else {
 6939: 	# no prefix at all
 6940: 	if (defined($part)) { $keyroot='_'.$part; }
 6941:     }
 6942:     return $keyroot;
 6943: }
 6944: 
 6945: # ---------------------------------------------------------------- Get metadata
 6946: 
 6947: my %metaentry;
 6948: sub metadata {
 6949:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6950:     $uri=&declutter($uri);
 6951:     # if it is a non metadata possible uri return quickly
 6952:     if (($uri eq '') || 
 6953: 	(($uri =~ m|^/*adm/|) && 
 6954: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6955:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6956: 	return undef;
 6957:     }
 6958:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6959: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6960: 	return undef;
 6961:     }
 6962:     my $filename=$uri;
 6963:     $uri=~s/\.meta$//;
 6964: #
 6965: # Is the metadata already cached?
 6966: # Look at timestamp of caching
 6967: # Everything is cached by the main uri, libraries are never directly cached
 6968: #
 6969:     if (!defined($liburi)) {
 6970: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6971: 	if (defined($cached)) { return $result->{':'.$what}; }
 6972:     }
 6973:     {
 6974: #
 6975: # Is this a recursive call for a library?
 6976: #
 6977: #	if (! exists($metacache{$uri})) {
 6978: #	    $metacache{$uri}={};
 6979: #	}
 6980: 	my $cachetime = 60*60;
 6981:         if ($liburi) {
 6982: 	    $liburi=&declutter($liburi);
 6983:             $filename=$liburi;
 6984:         } else {
 6985: 	    &devalidate_cache_new('meta',$uri);
 6986: 	    undef(%metaentry);
 6987: 	}
 6988:         my %metathesekeys=();
 6989:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6990: 	my $metastring;
 6991: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6992: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6993: 	    $metastring = 
 6994: 		&Apache::lonnet::ssi_body($which,
 6995: 					  ('grade_target' => 'meta'));
 6996: 	    $cachetime = 1; # only want this cached in the child not long term
 6997: 	} elsif ($uri !~ m -^(editupload)/-) {
 6998: 	    my $file=&filelocation('',&clutter($filename));
 6999: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7000: 	    $metastring=&getfile($file);
 7001: 	}
 7002:         my $parser=HTML::LCParser->new(\$metastring);
 7003:         my $token;
 7004:         undef %metathesekeys;
 7005:         while ($token=$parser->get_token) {
 7006: 	    if ($token->[0] eq 'S') {
 7007: 		if (defined($token->[2]->{'package'})) {
 7008: #
 7009: # This is a package - get package info
 7010: #
 7011: 		    my $package=$token->[2]->{'package'};
 7012: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7013: 		    if (defined($token->[2]->{'id'})) { 
 7014: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7015: 		    }
 7016: 		    if ($metaentry{':packages'}) {
 7017: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7018: 		    } else {
 7019: 			$metaentry{':packages'}=$package.$keyroot;
 7020: 		    }
 7021: 		    foreach my $pack_entry (keys(%packagetab)) {
 7022: 			my $part=$keyroot;
 7023: 			$part=~s/^\_//;
 7024: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7025: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7026: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7027: 			    # ignore package.tab specified default values
 7028:                             # here &package_tab_default() will fetch those
 7029: 			    if ($subp eq 'default') { next; }
 7030: 			    my $value=$packagetab{$pack_entry};
 7031: 			    my $unikey;
 7032: 			    if ($pack =~ /_0$/) {
 7033: 				$unikey='parameter_0_'.$name;
 7034: 				$part=0;
 7035: 			    } else {
 7036: 				$unikey='parameter'.$keyroot.'_'.$name;
 7037: 			    }
 7038: 			    if ($subp eq 'display') {
 7039: 				$value.=' [Part: '.$part.']';
 7040: 			    }
 7041: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7042: 			    $metathesekeys{$unikey}=1;
 7043: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7044: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7045: 			    }
 7046: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7047: 				$metaentry{':'.$unikey}=
 7048: 				    $metaentry{':'.$unikey.'.default'};
 7049: 			    }
 7050: 			}
 7051: 		    }
 7052: 		} else {
 7053: #
 7054: # This is not a package - some other kind of start tag
 7055: #
 7056: 		    my $entry=$token->[1];
 7057: 		    my $unikey;
 7058: 		    if ($entry eq 'import') {
 7059: 			$unikey='';
 7060: 		    } else {
 7061: 			$unikey=$entry;
 7062: 		    }
 7063: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7064: 
 7065: 		    if (defined($token->[2]->{'id'})) { 
 7066: 			$unikey.='_'.$token->[2]->{'id'}; 
 7067: 		    }
 7068: 
 7069: 		    if ($entry eq 'import') {
 7070: #
 7071: # Importing a library here
 7072: #
 7073: 			if ($depthcount<20) {
 7074: 			    my $location=$parser->get_text('/import');
 7075: 			    my $dir=$filename;
 7076: 			    $dir=~s|[^/]*$||;
 7077: 			    $location=&filelocation($dir,$location);
 7078: 			    my $metadata = 
 7079: 				&metadata($uri,'keys', $location,$unikey,
 7080: 					  $depthcount+1);
 7081: 			    foreach my $meta (split(',',$metadata)) {
 7082: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7083: 				$metathesekeys{$meta}=1;
 7084: 			    }
 7085: 			}
 7086: 		    } else { 
 7087: 			
 7088: 			if (defined($token->[2]->{'name'})) { 
 7089: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7090: 			}
 7091: 			$metathesekeys{$unikey}=1;
 7092: 			foreach my $param (@{$token->[3]}) {
 7093: 			    $metaentry{':'.$unikey.'.'.$param} =
 7094: 				$token->[2]->{$param};
 7095: 			}
 7096: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7097: 			my $default=$metaentry{':'.$unikey.'.default'};
 7098: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7099: 		 # only ws inside the tag, and not in default, so use default
 7100: 		 # as value
 7101: 			    $metaentry{':'.$unikey}=$default;
 7102: 			} elsif ( $internaltext =~ /\S/ ) {
 7103: 		  # something interesting inside the tag
 7104: 			    $metaentry{':'.$unikey}=$internaltext;
 7105: 			} else {
 7106: 		  # no interesting values, don't set a default
 7107: 			}
 7108: # end of not-a-package not-a-library import
 7109: 		    }
 7110: # end of not-a-package start tag
 7111: 		}
 7112: # the next is the end of "start tag"
 7113: 	    }
 7114: 	}
 7115: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7116: 	$extension = lc($extension);
 7117: 	if ($extension eq 'htm') { $extension='html'; }
 7118: 
 7119: 	foreach my $key (keys(%packagetab)) {
 7120: 	    #no specific packages #how's our extension
 7121: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7122: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7123: 					 \%metathesekeys);
 7124: 	}
 7125: 
 7126: 	if (!exists($metaentry{':packages'})
 7127: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7128: 	    foreach my $key (keys(%packagetab)) {
 7129: 		#no specific packages well let's get default then
 7130: 		if ($key!~/^default&/) { next; }
 7131: 		&metadata_create_package_def($uri,$key,'default',
 7132: 					     \%metathesekeys);
 7133: 	    }
 7134: 	}
 7135: # are there custom rights to evaluate
 7136: 	if ($metaentry{':copyright'} eq 'custom') {
 7137: 
 7138:     #
 7139:     # Importing a rights file here
 7140:     #
 7141: 	    unless ($depthcount) {
 7142: 		my $location=$metaentry{':customdistributionfile'};
 7143: 		my $dir=$filename;
 7144: 		$dir=~s|[^/]*$||;
 7145: 		$location=&filelocation($dir,$location);
 7146: 		my $rights_metadata =
 7147: 		    &metadata($uri,'keys',$location,'_rights',
 7148: 			      $depthcount+1);
 7149: 		foreach my $rights (split(',',$rights_metadata)) {
 7150: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7151: 		    $metathesekeys{$rights}=1;
 7152: 		}
 7153: 	    }
 7154: 	}
 7155: 	# uniqifiy package listing
 7156: 	my %seen;
 7157: 	my @uniq_packages =
 7158: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7159: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7160: 
 7161: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7162: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7163: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7164: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7165: # this is the end of "was not already recently cached
 7166:     }
 7167:     return $metaentry{':'.$what};
 7168: }
 7169: 
 7170: sub metadata_create_package_def {
 7171:     my ($uri,$key,$package,$metathesekeys)=@_;
 7172:     my ($pack,$name,$subp)=split(/\&/,$key);
 7173:     if ($subp eq 'default') { next; }
 7174:     
 7175:     if (defined($metaentry{':packages'})) {
 7176: 	$metaentry{':packages'}.=','.$package;
 7177:     } else {
 7178: 	$metaentry{':packages'}=$package;
 7179:     }
 7180:     my $value=$packagetab{$key};
 7181:     my $unikey;
 7182:     $unikey='parameter_0_'.$name;
 7183:     $metaentry{':'.$unikey.'.part'}=0;
 7184:     $$metathesekeys{$unikey}=1;
 7185:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7186: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7187:     }
 7188:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7189: 	$metaentry{':'.$unikey}=
 7190: 	    $metaentry{':'.$unikey.'.default'};
 7191:     }
 7192: }
 7193: 
 7194: sub metadata_generate_part0 {
 7195:     my ($metadata,$metacache,$uri) = @_;
 7196:     my %allnames;
 7197:     foreach my $metakey (keys(%$metadata)) {
 7198: 	if ($metakey=~/^parameter\_(.*)/) {
 7199: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7200: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7201: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7202: 	    $allnames{$name}=$part;
 7203: 	  }
 7204: 	}
 7205:     }
 7206:     foreach my $name (keys(%allnames)) {
 7207:       $$metadata{"parameter_0_$name"}=1;
 7208:       my $key=":parameter_0_$name";
 7209:       $$metacache{"$key.part"}='0';
 7210:       $$metacache{"$key.name"}=$name;
 7211:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7212: 					   $allnames{$name}.'_'.$name.
 7213: 					   '.type'};
 7214:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7215: 			     '.display'};
 7216:       my $expr='[Part: '.$allnames{$name}.']';
 7217:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7218:       $$metacache{"$key.display"}=$olddis;
 7219:     }
 7220: }
 7221: 
 7222: # ------------------------------------------------------ Devalidate title cache
 7223: 
 7224: sub devalidate_title_cache {
 7225:     my ($url)=@_;
 7226:     if (!$env{'request.course.id'}) { return; }
 7227:     my $symb=&symbread($url);
 7228:     if (!$symb) { return; }
 7229:     my $key=$env{'request.course.id'}."\0".$symb;
 7230:     &devalidate_cache_new('title',$key);
 7231: }
 7232: 
 7233: # ------------------------------------------------- Get the title of a resource
 7234: 
 7235: sub gettitle {
 7236:     my $urlsymb=shift;
 7237:     my $symb=&symbread($urlsymb);
 7238:     if ($symb) {
 7239: 	my $key=$env{'request.course.id'}."\0".$symb;
 7240: 	my ($result,$cached)=&is_cached_new('title',$key);
 7241: 	if (defined($cached)) { 
 7242: 	    return $result;
 7243: 	}
 7244: 	my ($map,$resid,$url)=&decode_symb($symb);
 7245: 	my $title='';
 7246: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7247: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7248: 	} else {
 7249: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7250: 		    &GDBM_READER(),0640)) {
 7251: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7252: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7253: 		untie(%bighash);
 7254: 	    }
 7255: 	}
 7256: 	$title=~s/\&colon\;/\:/gs;
 7257: 	if ($title) {
 7258: 	    return &do_cache_new('title',$key,$title,600);
 7259: 	}
 7260: 	$urlsymb=$url;
 7261:     }
 7262:     my $title=&metadata($urlsymb,'title');
 7263:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7264:     return $title;
 7265: }
 7266: 
 7267: sub get_slot {
 7268:     my ($which,$cnum,$cdom)=@_;
 7269:     if (!$cnum || !$cdom) {
 7270: 	(undef,my $courseid)=&whichuser();
 7271: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7272: 	$cnum=$env{'course.'.$courseid.'.num'};
 7273:     }
 7274:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7275:     my %slotinfo;
 7276:     if (exists($remembered{$key})) {
 7277: 	$slotinfo{$which} = $remembered{$key};
 7278:     } else {
 7279: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7280: 	&Apache::lonhomework::showhash(%slotinfo);
 7281: 	my ($tmp)=keys(%slotinfo);
 7282: 	if ($tmp=~/^error:/) { return (); }
 7283: 	$remembered{$key} = $slotinfo{$which};
 7284:     }
 7285:     if (ref($slotinfo{$which}) eq 'HASH') {
 7286: 	return %{$slotinfo{$which}};
 7287:     }
 7288:     return $slotinfo{$which};
 7289: }
 7290: # ------------------------------------------------- Update symbolic store links
 7291: 
 7292: sub symblist {
 7293:     my ($mapname,%newhash)=@_;
 7294:     $mapname=&deversion(&declutter($mapname));
 7295:     my %hash;
 7296:     if (($env{'request.course.fn'}) && (%newhash)) {
 7297:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7298:                       &GDBM_WRCREAT(),0640)) {
 7299: 	    foreach my $url (keys %newhash) {
 7300: 		next if ($url eq 'last_known'
 7301: 			 && $env{'form.no_update_last_known'});
 7302: 		$hash{declutter($url)}=&encode_symb($mapname,
 7303: 						    $newhash{$url}->[1],
 7304: 						    $newhash{$url}->[0]);
 7305:             }
 7306:             if (untie(%hash)) {
 7307: 		return 'ok';
 7308:             }
 7309:         }
 7310:     }
 7311:     return 'error';
 7312: }
 7313: 
 7314: # --------------------------------------------------------------- Verify a symb
 7315: 
 7316: sub symbverify {
 7317:     my ($symb,$thisurl)=@_;
 7318:     my $thisfn=$thisurl;
 7319:     $thisfn=&declutter($thisfn);
 7320: # direct jump to resource in page or to a sequence - will construct own symbs
 7321:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7322: # check URL part
 7323:     my ($map,$resid,$url)=&decode_symb($symb);
 7324: 
 7325:     unless ($url eq $thisfn) { return 0; }
 7326: 
 7327:     $symb=&symbclean($symb);
 7328:     $thisurl=&deversion($thisurl);
 7329:     $thisfn=&deversion($thisfn);
 7330: 
 7331:     my %bighash;
 7332:     my $okay=0;
 7333: 
 7334:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7335:                             &GDBM_READER(),0640)) {
 7336:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7337:         unless ($ids) { 
 7338:            $ids=$bighash{'ids_/'.$thisurl};
 7339:         }
 7340:         if ($ids) {
 7341: # ------------------------------------------------------------------- Has ID(s)
 7342: 	    foreach my $id (split(/\,/,$ids)) {
 7343: 	       my ($mapid,$resid)=split(/\./,$id);
 7344:                if (
 7345:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7346:    eq $symb) { 
 7347: 		   if (($env{'request.role.adv'}) ||
 7348: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7349: 		       $okay=1; 
 7350: 		   }
 7351: 	       }
 7352: 	   }
 7353:         }
 7354: 	untie(%bighash);
 7355:     }
 7356:     return $okay;
 7357: }
 7358: 
 7359: # --------------------------------------------------------------- Clean-up symb
 7360: 
 7361: sub symbclean {
 7362:     my $symb=shift;
 7363:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7364: # remove version from map
 7365:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7366: 
 7367: # remove version from URL
 7368:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7369: 
 7370: # remove wrapper
 7371: 
 7372:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7373:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7374:     return $symb;
 7375: }
 7376: 
 7377: # ---------------------------------------------- Split symb to find map and url
 7378: 
 7379: sub encode_symb {
 7380:     my ($map,$resid,$url)=@_;
 7381:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7382: }
 7383: 
 7384: sub decode_symb {
 7385:     my $symb=shift;
 7386:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7387:     my ($map,$resid,$url)=split(/___/,$symb);
 7388:     return (&fixversion($map),$resid,&fixversion($url));
 7389: }
 7390: 
 7391: sub fixversion {
 7392:     my $fn=shift;
 7393:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7394:     my %bighash;
 7395:     my $uri=&clutter($fn);
 7396:     my $key=$env{'request.course.id'}.'_'.$uri;
 7397: # is this cached?
 7398:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7399:     if (defined($cached)) { return $result; }
 7400: # unfortunately not cached, or expired
 7401:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7402: 	    &GDBM_READER(),0640)) {
 7403:  	if ($bighash{'version_'.$uri}) {
 7404:  	    my $version=$bighash{'version_'.$uri};
 7405:  	    unless (($version eq 'mostrecent') || 
 7406: 		    ($version==&getversion($uri))) {
 7407:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7408:  	    }
 7409:  	}
 7410:  	untie %bighash;
 7411:     }
 7412:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7413: }
 7414: 
 7415: sub deversion {
 7416:     my $url=shift;
 7417:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7418:     return $url;
 7419: }
 7420: 
 7421: # ------------------------------------------------------ Return symb list entry
 7422: 
 7423: sub symbread {
 7424:     my ($thisfn,$donotrecurse)=@_;
 7425:     my $cache_str='request.symbread.cached.'.$thisfn;
 7426:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7427: # no filename provided? try from environment
 7428:     unless ($thisfn) {
 7429:         if ($env{'request.symb'}) {
 7430: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7431: 	}
 7432: 	$thisfn=$env{'request.filename'};
 7433:     }
 7434:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7435: # is that filename actually a symb? Verify, clean, and return
 7436:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7437: 	if (&symbverify($thisfn,$1)) {
 7438: 	    return $env{$cache_str}=&symbclean($thisfn);
 7439: 	}
 7440:     }
 7441:     $thisfn=declutter($thisfn);
 7442:     my %hash;
 7443:     my %bighash;
 7444:     my $syval='';
 7445:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7446:         my $targetfn = $thisfn;
 7447:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7448:             $targetfn = 'adm/wrapper/'.$thisfn;
 7449:         }
 7450: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7451: 	    $targetfn=$1;
 7452: 	}
 7453:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7454:                       &GDBM_READER(),0640)) {
 7455: 	    $syval=$hash{$targetfn};
 7456:             untie(%hash);
 7457:         }
 7458: # ---------------------------------------------------------- There was an entry
 7459:         if ($syval) {
 7460: 	    #unless ($syval=~/\_\d+$/) {
 7461: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7462: 		    #&appenv({'request.ambiguous' => $thisfn});
 7463: 		    #return $env{$cache_str}='';
 7464: 		#}    
 7465: 		#$syval.=$1;
 7466: 	    #}
 7467:         } else {
 7468: # ------------------------------------------------------- Was not in symb table
 7469:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7470:                             &GDBM_READER(),0640)) {
 7471: # ---------------------------------------------- Get ID(s) for current resource
 7472:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7473:               unless ($ids) { 
 7474:                  $ids=$bighash{'ids_/'.$thisfn};
 7475:               }
 7476:               unless ($ids) {
 7477: # alias?
 7478: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7479:               }
 7480:               if ($ids) {
 7481: # ------------------------------------------------------------------- Has ID(s)
 7482:                  my @possibilities=split(/\,/,$ids);
 7483:                  if ($#possibilities==0) {
 7484: # ----------------------------------------------- There is only one possibility
 7485: 		     my ($mapid,$resid)=split(/\./,$ids);
 7486: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7487: 						    $resid,$thisfn);
 7488:                  } elsif (!$donotrecurse) {
 7489: # ------------------------------------------ There is more than one possibility
 7490:                      my $realpossible=0;
 7491:                      foreach my $id (@possibilities) {
 7492: 			 my $file=$bighash{'src_'.$id};
 7493:                          if (&allowed('bre',$file)) {
 7494:          		    my ($mapid,$resid)=split(/\./,$id);
 7495:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7496: 				$realpossible++;
 7497:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7498: 						    $resid,$thisfn);
 7499:                             }
 7500: 			 }
 7501:                      }
 7502: 		     if ($realpossible!=1) { $syval=''; }
 7503:                  } else {
 7504:                      $syval='';
 7505:                  }
 7506: 	      }
 7507:               untie(%bighash)
 7508:            }
 7509:         }
 7510:         if ($syval) {
 7511: 	    return $env{$cache_str}=$syval;
 7512:         }
 7513:     }
 7514:     &appenv({'request.ambiguous' => $thisfn});
 7515:     return $env{$cache_str}='';
 7516: }
 7517: 
 7518: # ---------------------------------------------------------- Return random seed
 7519: 
 7520: sub numval {
 7521:     my $txt=shift;
 7522:     $txt=~tr/A-J/0-9/;
 7523:     $txt=~tr/a-j/0-9/;
 7524:     $txt=~tr/K-T/0-9/;
 7525:     $txt=~tr/k-t/0-9/;
 7526:     $txt=~tr/U-Z/0-5/;
 7527:     $txt=~tr/u-z/0-5/;
 7528:     $txt=~s/\D//g;
 7529:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7530:     return int($txt);
 7531: }
 7532: 
 7533: sub numval2 {
 7534:     my $txt=shift;
 7535:     $txt=~tr/A-J/0-9/;
 7536:     $txt=~tr/a-j/0-9/;
 7537:     $txt=~tr/K-T/0-9/;
 7538:     $txt=~tr/k-t/0-9/;
 7539:     $txt=~tr/U-Z/0-5/;
 7540:     $txt=~tr/u-z/0-5/;
 7541:     $txt=~s/\D//g;
 7542:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7543:     my $total;
 7544:     foreach my $val (@txts) { $total+=$val; }
 7545:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7546:     return int($total);
 7547: }
 7548: 
 7549: sub numval3 {
 7550:     use integer;
 7551:     my $txt=shift;
 7552:     $txt=~tr/A-J/0-9/;
 7553:     $txt=~tr/a-j/0-9/;
 7554:     $txt=~tr/K-T/0-9/;
 7555:     $txt=~tr/k-t/0-9/;
 7556:     $txt=~tr/U-Z/0-5/;
 7557:     $txt=~tr/u-z/0-5/;
 7558:     $txt=~s/\D//g;
 7559:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7560:     my $total;
 7561:     foreach my $val (@txts) { $total+=$val; }
 7562:     if ($_64bit) { $total=(($total<<32)>>32); }
 7563:     return $total;
 7564: }
 7565: 
 7566: sub digest {
 7567:     my ($data)=@_;
 7568:     my $digest=&Digest::MD5::md5($data);
 7569:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7570:     my ($e,$f);
 7571:     {
 7572:         use integer;
 7573:         $e=($a+$b);
 7574:         $f=($c+$d);
 7575:         if ($_64bit) {
 7576:             $e=(($e<<32)>>32);
 7577:             $f=(($f<<32)>>32);
 7578:         }
 7579:     }
 7580:     if (wantarray) {
 7581: 	return ($e,$f);
 7582:     } else {
 7583: 	my $g;
 7584: 	{
 7585: 	    use integer;
 7586: 	    $g=($e+$f);
 7587: 	    if ($_64bit) {
 7588: 		$g=(($g<<32)>>32);
 7589: 	    }
 7590: 	}
 7591: 	return $g;
 7592:     }
 7593: }
 7594: 
 7595: sub latest_rnd_algorithm_id {
 7596:     return '64bit5';
 7597: }
 7598: 
 7599: sub get_rand_alg {
 7600:     my ($courseid)=@_;
 7601:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7602:     if ($courseid) {
 7603: 	return $env{"course.$courseid.rndseed"};
 7604:     }
 7605:     return &latest_rnd_algorithm_id();
 7606: }
 7607: 
 7608: sub validCODE {
 7609:     my ($CODE)=@_;
 7610:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7611:     return 0;
 7612: }
 7613: 
 7614: sub getCODE {
 7615:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7616:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7617: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7618: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7619: 	return $Apache::lonhomework::history{'resource.CODE'};
 7620:     }
 7621:     return undef;
 7622: }
 7623: 
 7624: sub rndseed {
 7625:     my ($symb,$courseid,$domain,$username)=@_;
 7626:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7627:     if (!defined($symb)) {
 7628: 	unless ($symb=$wsymb) { return time; }
 7629:     }
 7630:     if (!$courseid) { $courseid=$wcourseid; }
 7631:     if (!$domain) { $domain=$wdomain; }
 7632:     if (!$username) { $username=$wusername }
 7633:     my $which=&get_rand_alg();
 7634: 
 7635:     if (defined(&getCODE())) {
 7636: 	if ($which eq '64bit5') {
 7637: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7638: 	} elsif ($which eq '64bit4') {
 7639: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7640: 	} else {
 7641: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7642: 	}
 7643:     } elsif ($which eq '64bit5') {
 7644: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7645:     } elsif ($which eq '64bit4') {
 7646: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7647:     } elsif ($which eq '64bit3') {
 7648: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7649:     } elsif ($which eq '64bit2') {
 7650: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7651:     } elsif ($which eq '64bit') {
 7652: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7653:     }
 7654:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7655: }
 7656: 
 7657: sub rndseed_32bit {
 7658:     my ($symb,$courseid,$domain,$username)=@_;
 7659:     {
 7660: 	use integer;
 7661: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7662: 	my $symbseed=numval($symb) << 22;
 7663: 	my $namechck=unpack("%32C*",$username) << 17;
 7664: 	my $nameseed=numval($username) << 12;
 7665: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7666: 	my $courseseed=unpack("%32C*",$courseid);
 7667: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7668: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7669: 	#&logthis("rndseed :$num:$symb");
 7670: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7671: 	return $num;
 7672:     }
 7673: }
 7674: 
 7675: sub rndseed_64bit {
 7676:     my ($symb,$courseid,$domain,$username)=@_;
 7677:     {
 7678: 	use integer;
 7679: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7680: 	my $symbseed=numval($symb) << 10;
 7681: 	my $namechck=unpack("%32S*",$username);
 7682: 	
 7683: 	my $nameseed=numval($username) << 21;
 7684: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7685: 	my $courseseed=unpack("%32S*",$courseid);
 7686: 	
 7687: 	my $num1=$symbchck+$symbseed+$namechck;
 7688: 	my $num2=$nameseed+$domainseed+$courseseed;
 7689: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7690: 	#&logthis("rndseed :$num:$symb");
 7691: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7692: 	return "$num1,$num2";
 7693:     }
 7694: }
 7695: 
 7696: sub rndseed_64bit2 {
 7697:     my ($symb,$courseid,$domain,$username)=@_;
 7698:     {
 7699: 	use integer;
 7700: 	# strings need to be an even # of cahracters long, it it is odd the
 7701:         # last characters gets thrown away
 7702: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7703: 	my $symbseed=numval($symb) << 10;
 7704: 	my $namechck=unpack("%32S*",$username.' ');
 7705: 	
 7706: 	my $nameseed=numval($username) << 21;
 7707: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7708: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7709: 	
 7710: 	my $num1=$symbchck+$symbseed+$namechck;
 7711: 	my $num2=$nameseed+$domainseed+$courseseed;
 7712: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7713: 	#&logthis("rndseed :$num:$symb");
 7714: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7715: 	return "$num1,$num2";
 7716:     }
 7717: }
 7718: 
 7719: sub rndseed_64bit3 {
 7720:     my ($symb,$courseid,$domain,$username)=@_;
 7721:     {
 7722: 	use integer;
 7723: 	# strings need to be an even # of cahracters long, it it is odd the
 7724:         # last characters gets thrown away
 7725: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7726: 	my $symbseed=numval2($symb) << 10;
 7727: 	my $namechck=unpack("%32S*",$username.' ');
 7728: 	
 7729: 	my $nameseed=numval2($username) << 21;
 7730: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7731: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7732: 	
 7733: 	my $num1=$symbchck+$symbseed+$namechck;
 7734: 	my $num2=$nameseed+$domainseed+$courseseed;
 7735: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7736: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7737: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7738: 	
 7739: 	return "$num1:$num2";
 7740:     }
 7741: }
 7742: 
 7743: sub rndseed_64bit4 {
 7744:     my ($symb,$courseid,$domain,$username)=@_;
 7745:     {
 7746: 	use integer;
 7747: 	# strings need to be an even # of cahracters long, it it is odd the
 7748:         # last characters gets thrown away
 7749: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7750: 	my $symbseed=numval3($symb) << 10;
 7751: 	my $namechck=unpack("%32S*",$username.' ');
 7752: 	
 7753: 	my $nameseed=numval3($username) << 21;
 7754: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7755: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7756: 	
 7757: 	my $num1=$symbchck+$symbseed+$namechck;
 7758: 	my $num2=$nameseed+$domainseed+$courseseed;
 7759: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7760: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7761: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7762: 	
 7763: 	return "$num1:$num2";
 7764:     }
 7765: }
 7766: 
 7767: sub rndseed_64bit5 {
 7768:     my ($symb,$courseid,$domain,$username)=@_;
 7769:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7770:     return "$num1:$num2";
 7771: }
 7772: 
 7773: sub rndseed_CODE_64bit {
 7774:     my ($symb,$courseid,$domain,$username)=@_;
 7775:     {
 7776: 	use integer;
 7777: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7778: 	my $symbseed=numval2($symb);
 7779: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7780: 	my $CODEseed=numval(&getCODE());
 7781: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7782: 	my $num1=$symbseed+$CODEchck;
 7783: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7784: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7785: 	#&logthis("rndseed :$num1:$num2:$symb");
 7786: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7787: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7788: 	return "$num1:$num2";
 7789:     }
 7790: }
 7791: 
 7792: sub rndseed_CODE_64bit4 {
 7793:     my ($symb,$courseid,$domain,$username)=@_;
 7794:     {
 7795: 	use integer;
 7796: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7797: 	my $symbseed=numval3($symb);
 7798: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7799: 	my $CODEseed=numval3(&getCODE());
 7800: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7801: 	my $num1=$symbseed+$CODEchck;
 7802: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7803: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7804: 	#&logthis("rndseed :$num1:$num2:$symb");
 7805: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7806: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7807: 	return "$num1:$num2";
 7808:     }
 7809: }
 7810: 
 7811: sub rndseed_CODE_64bit5 {
 7812:     my ($symb,$courseid,$domain,$username)=@_;
 7813:     my $code = &getCODE();
 7814:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7815:     return "$num1:$num2";
 7816: }
 7817: 
 7818: sub setup_random_from_rndseed {
 7819:     my ($rndseed)=@_;
 7820:     if ($rndseed =~/([,:])/) {
 7821: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7822: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7823:     } else {
 7824: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7825:     }
 7826: }
 7827: 
 7828: sub latest_receipt_algorithm_id {
 7829:     return 'receipt3';
 7830: }
 7831: 
 7832: sub recunique {
 7833:     my $fucourseid=shift;
 7834:     my $unique;
 7835:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7836: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7837: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7838:     } else {
 7839: 	$unique=$perlvar{'lonReceipt'};
 7840:     }
 7841:     return unpack("%32C*",$unique);
 7842: }
 7843: 
 7844: sub recprefix {
 7845:     my $fucourseid=shift;
 7846:     my $prefix;
 7847:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7848: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7849: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7850:     } else {
 7851: 	$prefix=$perlvar{'lonHostID'};
 7852:     }
 7853:     return unpack("%32C*",$prefix);
 7854: }
 7855: 
 7856: sub ireceipt {
 7857:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7858: 
 7859:     my $return =&recprefix($fucourseid).'-';
 7860: 
 7861:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7862: 	$env{'request.state'} eq 'construct') {
 7863: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7864: 	return $return;
 7865:     }
 7866: 
 7867:     my $cuname=unpack("%32C*",$funame);
 7868:     my $cudom=unpack("%32C*",$fudom);
 7869:     my $cucourseid=unpack("%32C*",$fucourseid);
 7870:     my $cusymb=unpack("%32C*",$fusymb);
 7871:     my $cunique=&recunique($fucourseid);
 7872:     my $cpart=unpack("%32S*",$part);
 7873:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7874: 
 7875: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7876: 			       
 7877: 	$return.= ($cunique%$cuname+
 7878: 		   $cunique%$cudom+
 7879: 		   $cusymb%$cuname+
 7880: 		   $cusymb%$cudom+
 7881: 		   $cucourseid%$cuname+
 7882: 		   $cucourseid%$cudom+
 7883: 		   $cpart%$cuname+
 7884: 		   $cpart%$cudom);
 7885:     } else {
 7886: 	$return.= ($cunique%$cuname+
 7887: 		   $cunique%$cudom+
 7888: 		   $cusymb%$cuname+
 7889: 		   $cusymb%$cudom+
 7890: 		   $cucourseid%$cuname+
 7891: 		   $cucourseid%$cudom);
 7892:     }
 7893:     return $return;
 7894: }
 7895: 
 7896: sub receipt {
 7897:     my ($part)=@_;
 7898:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7899:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7900: }
 7901: 
 7902: sub whichuser {
 7903:     my ($passedsymb)=@_;
 7904:     my ($symb,$courseid,$domain,$name,$publicuser);
 7905:     if (defined($env{'form.grade_symb'})) {
 7906: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7907: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7908: 	if (!$allowed &&
 7909: 	    exists($env{'request.course.sec'}) &&
 7910: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7911: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7912: 			      '/'.$env{'request.course.sec'});
 7913: 	}
 7914: 	if ($allowed) {
 7915: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7916: 	    $courseid=$tmp_courseid;
 7917: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7918: 	    ($name)=&get_env_multiple('form.grade_username');
 7919: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7920: 	}
 7921:     }
 7922:     if (!$passedsymb) {
 7923: 	$symb=&symbread();
 7924:     } else {
 7925: 	$symb=$passedsymb;
 7926:     }
 7927:     $courseid=$env{'request.course.id'};
 7928:     $domain=$env{'user.domain'};
 7929:     $name=$env{'user.name'};
 7930:     if ($name eq 'public' && $domain eq 'public') {
 7931: 	if (!defined($env{'form.username'})) {
 7932: 	    $env{'form.username'}.=time.rand(10000000);
 7933: 	}
 7934: 	$name.=$env{'form.username'};
 7935:     }
 7936:     return ($symb,$courseid,$domain,$name,$publicuser);
 7937: 
 7938: }
 7939: 
 7940: # ------------------------------------------------------------ Serves up a file
 7941: # returns either the contents of the file or 
 7942: # -1 if the file doesn't exist
 7943: #
 7944: # if the target is a file that was uploaded via DOCS, 
 7945: # a check will be made to see if a current copy exists on the local server,
 7946: # if it does this will be served, otherwise a copy will be retrieved from
 7947: # the home server for the course and stored in /home/httpd/html/userfiles on
 7948: # the local server.   
 7949: 
 7950: sub getfile {
 7951:     my ($file) = @_;
 7952:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7953:     &repcopy($file);
 7954:     return &readfile($file);
 7955: }
 7956: 
 7957: sub repcopy_userfile {
 7958:     my ($file)=@_;
 7959:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7960:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7961:     my ($cdom,$cnum,$filename) = 
 7962: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7963:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7964:     if (-e "$file") {
 7965: # we already have a local copy, check it out
 7966: 	my @fileinfo = stat($file);
 7967: 	my $rtncode;
 7968: 	my $info;
 7969: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7970: 	if ($lwpresp ne 'ok') {
 7971: # there is no such file anymore, even though we had a local copy
 7972: 	    if ($rtncode eq '404') {
 7973: 		unlink($file);
 7974: 	    }
 7975: 	    return -1;
 7976: 	}
 7977: 	if ($info < $fileinfo[9]) {
 7978: # nice, the file we have is up-to-date, just say okay
 7979: 	    return 'ok';
 7980: 	} else {
 7981: # the file is outdated, get rid of it
 7982: 	    unlink($file);
 7983: 	}
 7984:     }
 7985: # one way or the other, at this point, we don't have the file
 7986: # construct the correct path for the file
 7987:     my @parts = ($cdom,$cnum); 
 7988:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7989: 	push @parts, split(/\//,$1);
 7990:     }
 7991:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7992:     foreach my $part (@parts) {
 7993: 	$path .= '/'.$part;
 7994: 	if (!-e $path) {
 7995: 	    mkdir($path,0770);
 7996: 	}
 7997:     }
 7998: # now the path exists for sure
 7999: # get a user agent
 8000:     my $ua=new LWP::UserAgent;
 8001:     my $transferfile=$file.'.in.transfer';
 8002: # FIXME: this should flock
 8003:     if (-e $transferfile) { return 'ok'; }
 8004:     my $request;
 8005:     $uri=~s/^\///;
 8006:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 8007:     my $response=$ua->request($request,$transferfile);
 8008: # did it work?
 8009:     if ($response->is_error()) {
 8010: 	unlink($transferfile);
 8011: 	&logthis("Userfile repcopy failed for $uri");
 8012: 	return -1;
 8013:     }
 8014: # worked, rename the transfer file
 8015:     rename($transferfile,$file);
 8016:     return 'ok';
 8017: }
 8018: 
 8019: sub tokenwrapper {
 8020:     my $uri=shift;
 8021:     $uri=~s|^http\://([^/]+)||;
 8022:     $uri=~s|^/||;
 8023:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8024:     my $token=$1;
 8025:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8026:     if ($udom && $uname && $file) {
 8027: 	$file=~s|(\?\.*)*$||;
 8028:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8029:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 8030:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8031:                                '&tokenissued='.$perlvar{'lonHostID'};
 8032:     } else {
 8033:         return '/adm/notfound.html';
 8034:     }
 8035: }
 8036: 
 8037: # call with reqtype HEAD: get last modification time
 8038: # call with reqtype GET: get the file contents
 8039: # Do not call this with reqtype GET for large files! It loads everything into memory
 8040: #
 8041: sub getuploaded {
 8042:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8043:     $uri=~s/^\///;
 8044:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8045:     my $ua=new LWP::UserAgent;
 8046:     my $request=new HTTP::Request($reqtype,$uri);
 8047:     my $response=$ua->request($request);
 8048:     $$rtncode = $response->code;
 8049:     if (! $response->is_success()) {
 8050: 	return 'failed';
 8051:     }      
 8052:     if ($reqtype eq 'HEAD') {
 8053: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8054:     } elsif ($reqtype eq 'GET') {
 8055: 	$$info = $response->content;
 8056:     }
 8057:     return 'ok';
 8058: }
 8059: 
 8060: sub readfile {
 8061:     my $file = shift;
 8062:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8063:     my $fh;
 8064:     open($fh,"<$file");
 8065:     my $a='';
 8066:     while (my $line = <$fh>) { $a .= $line; }
 8067:     return $a;
 8068: }
 8069: 
 8070: sub filelocation {
 8071:     my ($dir,$file) = @_;
 8072:     my $location;
 8073:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8074: 
 8075:     if ($file =~ m-^/adm/-) {
 8076: 	$file=~s-^/adm/wrapper/-/-;
 8077: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8078:     }
 8079: 
 8080:     if ($file=~m:^/~:) { # is a contruction space reference
 8081:         $location = $file;
 8082:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8083:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8084: 	# is a correct contruction space reference
 8085:         $location = $file;
 8086:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8087:         my ($udom,$uname,$filename)=
 8088:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8089:         my $home=&homeserver($uname,$udom);
 8090:         my $is_me=0;
 8091:         my @ids=&current_machine_ids();
 8092:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8093:         if ($is_me) {
 8094:   	    $location=&propath($udom,$uname).
 8095:   	      '/userfiles/'.$filename;
 8096:         } else {
 8097:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8098:   	      $udom.'/'.$uname.'/'.$filename;
 8099:         }
 8100:     } elsif ($file =~ m-^/adm/-) {
 8101: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8102:     } else {
 8103:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8104:         $file=~s:^/res/:/:;
 8105:         if ( !( $file =~ m:^/:) ) {
 8106:             $location = $dir. '/'.$file;
 8107:         } else {
 8108:             $location = '/home/httpd/html/res'.$file;
 8109:         }
 8110:     }
 8111:     $location=~s://+:/:g; # remove duplicate /
 8112:     while ($location=~m{/\.\./}) {
 8113: 	if ($location =~ m{/[^/]+/\.\./}) {
 8114: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8115: 	} else {
 8116: 	    $location=~ s{/\.\./}{/}g;
 8117: 	}
 8118:     } #remove dir/..
 8119:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8120:     return $location;
 8121: }
 8122: 
 8123: sub hreflocation {
 8124:     my ($dir,$file)=@_;
 8125:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8126: 	$file=filelocation($dir,$file);
 8127:     } elsif ($file=~m-^/adm/-) {
 8128: 	$file=~s-^/adm/wrapper/-/-;
 8129: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8130:     }
 8131:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8132: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8133:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8134: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8135:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8136: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8137: 	    -/uploaded/$1/$2/-x;
 8138:     }
 8139:     if ($file=~ m{^/userfiles/}) {
 8140: 	$file =~ s{^/userfiles/}{/uploaded/};
 8141:     }
 8142:     return $file;
 8143: }
 8144: 
 8145: sub current_machine_domains {
 8146:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8147: }
 8148: 
 8149: sub machine_domains {
 8150:     my ($hostname) = @_;
 8151:     my @domains;
 8152:     my %hostname = &all_hostnames();
 8153:     while( my($id, $name) = each(%hostname)) {
 8154: #	&logthis("-$id-$name-$hostname-");
 8155: 	if ($hostname eq $name) {
 8156: 	    push(@domains,&host_domain($id));
 8157: 	}
 8158:     }
 8159:     return @domains;
 8160: }
 8161: 
 8162: sub current_machine_ids {
 8163:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8164: }
 8165: 
 8166: sub machine_ids {
 8167:     my ($hostname) = @_;
 8168:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8169:     my @ids;
 8170:     my %name_to_host = &all_names();
 8171:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8172: 	return @{ $name_to_host{$hostname} };
 8173:     }
 8174:     return;
 8175: }
 8176: 
 8177: sub additional_machine_domains {
 8178:     my @domains;
 8179:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8180:     while( my $line = <$fh>) {
 8181:         $line =~ s/\s//g;
 8182:         push(@domains,$line);
 8183:     }
 8184:     return @domains;
 8185: }
 8186: 
 8187: sub default_login_domain {
 8188:     my $domain = $perlvar{'lonDefDomain'};
 8189:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8190:     foreach my $posdom (&current_machine_domains(),
 8191:                         &additional_machine_domains()) {
 8192:         if (lc($posdom) eq lc($testdomain)) {
 8193:             $domain=$posdom;
 8194:             last;
 8195:         }
 8196:     }
 8197:     return $domain;
 8198: }
 8199: 
 8200: # ------------------------------------------------------------- Declutters URLs
 8201: 
 8202: sub declutter {
 8203:     my $thisfn=shift;
 8204:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8205:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8206:     $thisfn=~s/^\///;
 8207:     $thisfn=~s|^adm/wrapper/||;
 8208:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8209:     $thisfn=~s/^res\///;
 8210:     $thisfn=~s/\?.+$//;
 8211:     return $thisfn;
 8212: }
 8213: 
 8214: # ------------------------------------------------------------- Clutter up URLs
 8215: 
 8216: sub clutter {
 8217:     my $thisfn='/'.&declutter(shift);
 8218:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8219: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8220:        $thisfn='/res'.$thisfn; 
 8221:     }
 8222:     if ($thisfn !~m|/adm|) {
 8223: 	if ($thisfn =~ m|/ext/|) {
 8224: 	    $thisfn='/adm/wrapper'.$thisfn;
 8225: 	} else {
 8226: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8227: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8228: 	    if ($embstyle eq 'ssi'
 8229: 		|| ($embstyle eq 'hdn')
 8230: 		|| ($embstyle eq 'rat')
 8231: 		|| ($embstyle eq 'prv')
 8232: 		|| ($embstyle eq 'ign')) {
 8233: 		#do nothing with these
 8234: 	    } elsif (($embstyle eq 'img') 
 8235: 		|| ($embstyle eq 'emb')
 8236: 		|| ($embstyle eq 'wrp')) {
 8237: 		$thisfn='/adm/wrapper'.$thisfn;
 8238: 	    } elsif ($embstyle eq 'unk'
 8239: 		     && $thisfn!~/\.(sequence|page)$/) {
 8240: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8241: 	    } else {
 8242: #		&logthis("Got a blank emb style");
 8243: 	    }
 8244: 	}
 8245:     }
 8246:     return $thisfn;
 8247: }
 8248: 
 8249: sub clutter_with_no_wrapper {
 8250:     my $uri = &clutter(shift);
 8251:     if ($uri =~ m-^/adm/-) {
 8252: 	$uri =~ s-^/adm/wrapper/-/-;
 8253: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8254:     }
 8255:     return $uri;
 8256: }
 8257: 
 8258: sub freeze_escape {
 8259:     my ($value)=@_;
 8260:     if (ref($value)) {
 8261: 	$value=&nfreeze($value);
 8262: 	return '__FROZEN__'.&escape($value);
 8263:     }
 8264:     return &escape($value);
 8265: }
 8266: 
 8267: 
 8268: sub thaw_unescape {
 8269:     my ($value)=@_;
 8270:     if ($value =~ /^__FROZEN__/) {
 8271: 	substr($value,0,10,undef);
 8272: 	$value=&unescape($value);
 8273: 	return &thaw($value);
 8274:     }
 8275:     return &unescape($value);
 8276: }
 8277: 
 8278: sub correct_line_ends {
 8279:     my ($result)=@_;
 8280:     $$result =~s/\r\n/\n/mg;
 8281:     $$result =~s/\r/\n/mg;
 8282: }
 8283: # ================================================================ Main Program
 8284: 
 8285: sub goodbye {
 8286:    &logthis("Starting Shut down");
 8287: #not converted to using infrastruture and probably shouldn't be
 8288:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8289: #converted
 8290: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8291:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8292: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8293: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8294: #1.1 only
 8295: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8296: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8297: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8298: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8299:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8300:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8301:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8302:    &flushcourselogs();
 8303:    &logthis("Shutting down");
 8304: }
 8305: 
 8306: sub get_dns {
 8307:     my ($url,$func,$ignore_cache) = @_;
 8308:     if (!$ignore_cache) {
 8309: 	my ($content,$cached)=
 8310: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8311: 	if ($cached) {
 8312: 	    &$func($content);
 8313: 	    return;
 8314: 	}
 8315:     }
 8316: 
 8317:     my %alldns;
 8318:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8319:     foreach my $dns (<$config>) {
 8320: 	next if ($dns !~ /^\^(\S*)/x);
 8321: 	$alldns{$1} = 1;
 8322:     }
 8323:     while (%alldns) {
 8324: 	my ($dns) = keys(%alldns);
 8325: 	delete($alldns{$dns});
 8326: 	my $ua=new LWP::UserAgent;
 8327: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8328: 	my $response=$ua->request($request);
 8329: 	next if ($response->is_error());
 8330: 	my @content = split("\n",$response->content);
 8331: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8332: 	&$func(\@content);
 8333: 	return;
 8334:     }
 8335:     close($config);
 8336:     my $which = (split('/',$url))[3];
 8337:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8338:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8339:     my @content = <$config>;
 8340:     &$func(\@content);
 8341:     return;
 8342: }
 8343: # ------------------------------------------------------------ Read domain file
 8344: {
 8345:     my $loaded;
 8346:     my %domain;
 8347: 
 8348:     sub parse_domain_tab {
 8349: 	my ($lines) = @_;
 8350: 	foreach my $line (@$lines) {
 8351: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8352: 
 8353: 	    chomp($line);
 8354: 	    my ($name,@elements) = split(/:/,$line,9);
 8355: 	    my %this_domain;
 8356: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8357: 			       'lang_def', 'city', 'longi', 'lati',
 8358: 			       'primary') {
 8359: 		$this_domain{$field} = shift(@elements);
 8360: 	    }
 8361: 	    $domain{$name} = \%this_domain;
 8362: 	}
 8363:     }
 8364: 
 8365:     sub reset_domain_info {
 8366: 	undef($loaded);
 8367: 	undef(%domain);
 8368:     }
 8369: 
 8370:     sub load_domain_tab {
 8371: 	my ($ignore_cache) = @_;
 8372: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8373: 	my $fh;
 8374: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8375: 	    my @lines = <$fh>;
 8376: 	    &parse_domain_tab(\@lines);
 8377: 	}
 8378: 	close($fh);
 8379: 	$loaded = 1;
 8380:     }
 8381: 
 8382:     sub domain {
 8383: 	&load_domain_tab() if (!$loaded);
 8384: 
 8385: 	my ($name,$what) = @_;
 8386: 	return if ( !exists($domain{$name}) );
 8387: 
 8388: 	if (!$what) {
 8389: 	    return $domain{$name}{'description'};
 8390: 	}
 8391: 	return $domain{$name}{$what};
 8392:     }
 8393: }
 8394: 
 8395: 
 8396: # ------------------------------------------------------------- Read hosts file
 8397: {
 8398:     my %hostname;
 8399:     my %hostdom;
 8400:     my %libserv;
 8401:     my $loaded;
 8402:     my %name_to_host;
 8403: 
 8404:     sub parse_hosts_tab {
 8405: 	my ($file) = @_;
 8406: 	foreach my $configline (@$file) {
 8407: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8408: 	    next if ($configline =~ /^\^/);
 8409: 	    chomp($configline);
 8410: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8411: 	    $name=~s/\s//g;
 8412: 	    if ($id && $domain && $role && $name) {
 8413: 		$hostname{$id}=$name;
 8414: 		push(@{$name_to_host{$name}}, $id);
 8415: 		$hostdom{$id}=$domain;
 8416: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8417: 	    }
 8418: 	}
 8419:     }
 8420:     
 8421:     sub reset_hosts_info {
 8422: 	&purge_remembered();
 8423: 	&reset_domain_info();
 8424: 	&reset_hosts_ip_info();
 8425: 	undef(%name_to_host);
 8426: 	undef(%hostname);
 8427: 	undef(%hostdom);
 8428: 	undef(%libserv);
 8429: 	undef($loaded);
 8430:     }
 8431: 
 8432:     sub load_hosts_tab {
 8433: 	my ($ignore_cache) = @_;
 8434: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8435: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8436: 	my @config = <$config>;
 8437: 	&parse_hosts_tab(\@config);
 8438: 	close($config);
 8439: 	$loaded=1;
 8440:     }
 8441: 
 8442:     sub hostname {
 8443: 	&load_hosts_tab() if (!$loaded);
 8444: 
 8445: 	my ($lonid) = @_;
 8446: 	return $hostname{$lonid};
 8447:     }
 8448: 
 8449:     sub all_hostnames {
 8450: 	&load_hosts_tab() if (!$loaded);
 8451: 
 8452: 	return %hostname;
 8453:     }
 8454: 
 8455:     sub all_names {
 8456: 	&load_hosts_tab() if (!$loaded);
 8457: 
 8458: 	return %name_to_host;
 8459:     }
 8460: 
 8461:     sub is_library {
 8462: 	&load_hosts_tab() if (!$loaded);
 8463: 
 8464: 	return exists($libserv{$_[0]});
 8465:     }
 8466: 
 8467:     sub all_library {
 8468: 	&load_hosts_tab() if (!$loaded);
 8469: 
 8470: 	return %libserv;
 8471:     }
 8472: 
 8473:     sub get_servers {
 8474: 	&load_hosts_tab() if (!$loaded);
 8475: 
 8476: 	my ($domain,$type) = @_;
 8477: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8478: 	                                          : %hostname;
 8479: 	my %result;
 8480: 	if (ref($domain) eq 'ARRAY') {
 8481: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8482: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8483: 		    $result{$host} = $hostname;
 8484: 		}
 8485: 	    }
 8486: 	} else {
 8487: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8488: 		if ($hostdom{$host} eq $domain) {
 8489: 		    $result{$host} = $hostname;
 8490: 		}
 8491: 	    }
 8492: 	}
 8493: 	return %result;
 8494:     }
 8495: 
 8496:     sub host_domain {
 8497: 	&load_hosts_tab() if (!$loaded);
 8498: 
 8499: 	my ($lonid) = @_;
 8500: 	return $hostdom{$lonid};
 8501:     }
 8502: 
 8503:     sub all_domains {
 8504: 	&load_hosts_tab() if (!$loaded);
 8505: 
 8506: 	my %seen;
 8507: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8508: 	return @uniq;
 8509:     }
 8510: }
 8511: 
 8512: { 
 8513:     my %iphost;
 8514:     my %name_to_ip;
 8515:     my %lonid_to_ip;
 8516: 
 8517:     sub get_hosts_from_ip {
 8518: 	my ($ip) = @_;
 8519: 	my %iphosts = &get_iphost();
 8520: 	if (ref($iphosts{$ip})) {
 8521: 	    return @{$iphosts{$ip}};
 8522: 	}
 8523: 	return;
 8524:     }
 8525:     
 8526:     sub reset_hosts_ip_info {
 8527: 	undef(%iphost);
 8528: 	undef(%name_to_ip);
 8529: 	undef(%lonid_to_ip);
 8530:     }
 8531: 
 8532:     sub get_host_ip {
 8533: 	my ($lonid) = @_;
 8534: 	if (exists($lonid_to_ip{$lonid})) {
 8535: 	    return $lonid_to_ip{$lonid};
 8536: 	}
 8537: 	my $name=&hostname($lonid);
 8538:    	my $ip = gethostbyname($name);
 8539: 	return if (!$ip || length($ip) ne 4);
 8540: 	$ip=inet_ntoa($ip);
 8541: 	$name_to_ip{$name}   = $ip;
 8542: 	$lonid_to_ip{$lonid} = $ip;
 8543: 	return $ip;
 8544:     }
 8545:     
 8546:     sub get_iphost {
 8547: 	my ($ignore_cache) = @_;
 8548: 
 8549: 	if (!$ignore_cache) {
 8550: 	    if (%iphost) {
 8551: 		return %iphost;
 8552: 	    }
 8553: 	    my ($ip_info,$cached)=
 8554: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8555: 	    if ($cached) {
 8556: 		%iphost      = %{$ip_info->[0]};
 8557: 		%name_to_ip  = %{$ip_info->[1]};
 8558: 		%lonid_to_ip = %{$ip_info->[2]};
 8559: 		return %iphost;
 8560: 	    }
 8561: 	}
 8562: 
 8563: 	# get yesterday's info for fallback
 8564: 	my %old_name_to_ip;
 8565: 	my ($ip_info,$cached)=
 8566: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8567: 	if ($cached) {
 8568: 	    %old_name_to_ip = %{$ip_info->[1]};
 8569: 	}
 8570: 
 8571: 	my %name_to_host = &all_names();
 8572: 	foreach my $name (keys(%name_to_host)) {
 8573: 	    my $ip;
 8574: 	    if (!exists($name_to_ip{$name})) {
 8575: 		$ip = gethostbyname($name);
 8576: 		if (!$ip || length($ip) ne 4) {
 8577: 		    if (defined($old_name_to_ip{$name})) {
 8578: 			$ip = $old_name_to_ip{$name};
 8579: 			&logthis("Can't find $name defaulting to old $ip");
 8580: 		    } else {
 8581: 			&logthis("Name $name no IP found");
 8582: 			next;
 8583: 		    }
 8584: 		} else {
 8585: 		    $ip=inet_ntoa($ip);
 8586: 		}
 8587: 		$name_to_ip{$name} = $ip;
 8588: 	    } else {
 8589: 		$ip = $name_to_ip{$name};
 8590: 	    }
 8591: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8592: 		$lonid_to_ip{$id} = $ip;
 8593: 	    }
 8594: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8595: 	}
 8596: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8597: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8598: 				      48*60*60);
 8599: 
 8600: 	return %iphost;
 8601:     }
 8602: }
 8603: 
 8604: BEGIN {
 8605: 
 8606: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8607:     unless ($readit) {
 8608: {
 8609:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8610:     %perlvar = (%perlvar,%{$configvars});
 8611: }
 8612: 
 8613: 
 8614: # ------------------------------------------------------ Read spare server file
 8615: {
 8616:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8617: 
 8618:     while (my $configline=<$config>) {
 8619:        chomp($configline);
 8620:        if ($configline) {
 8621: 	   my ($host,$type) = split(':',$configline,2);
 8622: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8623: 	   push(@{ $spareid{$type} }, $host);
 8624:        }
 8625:     }
 8626:     close($config);
 8627: }
 8628: # ------------------------------------------------------------ Read permissions
 8629: {
 8630:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8631: 
 8632:     while (my $configline=<$config>) {
 8633: 	chomp($configline);
 8634: 	if ($configline) {
 8635: 	    my ($role,$perm)=split(/ /,$configline);
 8636: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8637: 	}
 8638:     }
 8639:     close($config);
 8640: }
 8641: 
 8642: # -------------------------------------------- Read plain texts for permissions
 8643: {
 8644:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8645: 
 8646:     while (my $configline=<$config>) {
 8647: 	chomp($configline);
 8648: 	if ($configline) {
 8649: 	    my ($short,@plain)=split(/:/,$configline);
 8650:             %{$prp{$short}} = ();
 8651: 	    if (@plain > 0) {
 8652:                 $prp{$short}{'std'} = $plain[0];
 8653:                 for (my $i=1; $i<@plain; $i++) {
 8654:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8655:                 }
 8656:             }
 8657: 	}
 8658:     }
 8659:     close($config);
 8660: }
 8661: 
 8662: # ---------------------------------------------------------- Read package table
 8663: {
 8664:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8665: 
 8666:     while (my $configline=<$config>) {
 8667: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8668: 	chomp($configline);
 8669: 	my ($short,$plain)=split(/:/,$configline);
 8670: 	my ($pack,$name)=split(/\&/,$short);
 8671: 	if ($plain ne '') {
 8672: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8673: 	    $packagetab{$short}=$plain; 
 8674: 	}
 8675:     }
 8676:     close($config);
 8677: }
 8678: 
 8679: # ------------- set up temporary directory
 8680: {
 8681:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8682: 
 8683: }
 8684: 
 8685: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8686: 				'compress_threshold'=> 20_000,
 8687:  			        });
 8688: 
 8689: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8690: $dumpcount=0;
 8691: 
 8692: &logtouch();
 8693: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8694: $readit=1;
 8695:     {
 8696: 	use integer;
 8697: 	my $test=(2**32)+1;
 8698: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8699: 	&logthis(" Detected 64bit platform ($_64bit)");
 8700:     }
 8701: }
 8702: }
 8703: 
 8704: 1;
 8705: __END__
 8706: 
 8707: =pod
 8708: 
 8709: =head1 NAME
 8710: 
 8711: Apache::lonnet - Subroutines to ask questions about things in the network.
 8712: 
 8713: =head1 SYNOPSIS
 8714: 
 8715: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8716: 
 8717:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8718: 
 8719: Common parameters:
 8720: 
 8721: =over 4
 8722: 
 8723: =item *
 8724: 
 8725: $uname : an internal username (if $cname expecting a course Id specifically)
 8726: 
 8727: =item *
 8728: 
 8729: $udom : a domain (if $cdom expecting a course's domain specifically)
 8730: 
 8731: =item *
 8732: 
 8733: $symb : a resource instance identifier
 8734: 
 8735: =item *
 8736: 
 8737: $namespace : the name of a .db file that contains the data needed or
 8738: being set.
 8739: 
 8740: =back
 8741: 
 8742: =head1 OVERVIEW
 8743: 
 8744: lonnet provides subroutines which interact with the
 8745: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8746: about classes, users, and resources.
 8747: 
 8748: For many of these objects you can also use this to store data about
 8749: them or modify them in various ways.
 8750: 
 8751: =head2 Symbs
 8752: 
 8753: To identify a specific instance of a resource, LON-CAPA uses symbols
 8754: or "symbs"X<symb>. These identifiers are built from the URL of the
 8755: map, the resource number of the resource in the map, and the URL of
 8756: the resource itself. The latter is somewhat redundant, but might help
 8757: if maps change.
 8758: 
 8759: An example is
 8760: 
 8761:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8762: 
 8763: The respective map entry is
 8764: 
 8765:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8766:   title="Problem 2">
 8767:  </resource>
 8768: 
 8769: Symbs are used by the random number generator, as well as to store and
 8770: restore data specific to a certain instance of for example a problem.
 8771: 
 8772: =head2 Storing And Retrieving Data
 8773: 
 8774: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8775: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8776: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8777: is is the non-critical message twin of cstore. These functions are for
 8778: handlers to store a perl hash to a user's permanent data space in an
 8779: easy manner, and to retrieve it again on another call. It is expected
 8780: that a handler would use this once at the beginning to retrieve data,
 8781: and then again once at the end to send only the new data back.
 8782: 
 8783: The data is stored in the user's data directory on the user's
 8784: homeserver under the ID of the course.
 8785: 
 8786: The hash that is returned by restore will have all of the previous
 8787: value for all of the elements of the hash.
 8788: 
 8789: Example:
 8790: 
 8791:  #creating a hash
 8792:  my %hash;
 8793:  $hash{'foo'}='bar';
 8794: 
 8795:  #storing it
 8796:  &Apache::lonnet::cstore(\%hash);
 8797: 
 8798:  #changing a value
 8799:  $hash{'foo'}='notbar';
 8800: 
 8801:  #adding a new value
 8802:  $hash{'bar'}='foo';
 8803:  &Apache::lonnet::cstore(\%hash);
 8804: 
 8805:  #retrieving the hash
 8806:  my %history=&Apache::lonnet::restore();
 8807: 
 8808:  #print the hash
 8809:  foreach my $key (sort(keys(%history))) {
 8810:    print("\%history{$key} = $history{$key}");
 8811:  }
 8812: 
 8813: Will print out:
 8814: 
 8815:  %history{1:foo} = bar
 8816:  %history{1:keys} = foo:timestamp
 8817:  %history{1:timestamp} = 990455579
 8818:  %history{2:bar} = foo
 8819:  %history{2:foo} = notbar
 8820:  %history{2:keys} = foo:bar:timestamp
 8821:  %history{2:timestamp} = 990455580
 8822:  %history{bar} = foo
 8823:  %history{foo} = notbar
 8824:  %history{timestamp} = 990455580
 8825:  %history{version} = 2
 8826: 
 8827: Note that the special hash entries C<keys>, C<version> and
 8828: C<timestamp> were added to the hash. C<version> will be equal to the
 8829: total number of versions of the data that have been stored. The
 8830: C<timestamp> attribute will be the UNIX time the hash was
 8831: stored. C<keys> is available in every historical section to list which
 8832: keys were added or changed at a specific historical revision of a
 8833: hash.
 8834: 
 8835: B<Warning>: do not store the hash that restore returns directly. This
 8836: will cause a mess since it will restore the historical keys as if the
 8837: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8838: 
 8839: Calling convention:
 8840: 
 8841:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8842:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8843: 
 8844: For more detailed information, see lonnet specific documentation.
 8845: 
 8846: =head1 RETURN MESSAGES
 8847: 
 8848: =over 4
 8849: 
 8850: =item * B<con_lost>: unable to contact remote host
 8851: 
 8852: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8853: when the connection is brought back up
 8854: 
 8855: =item * B<con_failed>: unable to contact remote host and unable to save message
 8856: for later delivery
 8857: 
 8858: =item * B<error:>: an error a occured, a description of the error follows the :
 8859: 
 8860: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8861: that was requested
 8862: 
 8863: =back
 8864: 
 8865: =head1 PUBLIC SUBROUTINES
 8866: 
 8867: =head2 Session Environment Functions
 8868: 
 8869: =over 4
 8870: 
 8871: =item * 
 8872: X<appenv()>
 8873: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 8874: the user envirnoment file, and will be restored for each access this
 8875: user makes during this session, also modifies the %env for the current
 8876: process. Optional rolesarrayref - if defined contains a reference to an array
 8877: of roles which are exempt from the restriction on modifying user.role entries 
 8878: in the user's environment.db and in %env.    
 8879: 
 8880: =item *
 8881: X<delenv()>
 8882: B<delenv($regexp)>: removes all items from the session
 8883: environment file that matches the regular expression in $regexp. The
 8884: values are also delted from the current processes %env.
 8885: 
 8886: =item * get_env_multiple($name) 
 8887: 
 8888: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8889: values may be defined and end up as an array ref.
 8890: 
 8891: returns an array of values
 8892: 
 8893: =back
 8894: 
 8895: =head2 User Information
 8896: 
 8897: =over 4
 8898: 
 8899: =item *
 8900: X<queryauthenticate()>
 8901: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8902: authentication scheme
 8903: 
 8904: =item *
 8905: X<authenticate()>
 8906: B<authenticate($uname,$upass,$udom)>: try to
 8907: authenticate user from domain's lib servers (first use the current
 8908: one). C<$upass> should be the users password.
 8909: 
 8910: =item *
 8911: X<homeserver()>
 8912: B<homeserver($uname,$udom)>: find the server which has
 8913: the user's directory and files (there must be only one), this caches
 8914: the answer, and also caches if there is a borken connection.
 8915: 
 8916: =item *
 8917: X<idget()>
 8918: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8919: (IDs are a unique resource in a domain, there must be only 1 ID per
 8920: username, and only 1 username per ID in a specific domain) (returns
 8921: hash: id=>name,id=>name)
 8922: 
 8923: =item *
 8924: X<idrget()>
 8925: B<idrget($udom,@unames)>: find the IDs behind a list of
 8926: usernames (returns hash: name=>id,name=>id)
 8927: 
 8928: =item *
 8929: X<idput()>
 8930: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8931: 
 8932: =item *
 8933: X<rolesinit()>
 8934: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8935: 
 8936: =item *
 8937: X<getsection()>
 8938: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8939: course $cname, return section name/number or '' for "not in course"
 8940: and '-1' for "no section"
 8941: 
 8942: =item *
 8943: X<userenvironment()>
 8944: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8945: passed in @what from the requested user's environment, returns a hash
 8946: 
 8947: =item * 
 8948: X<userlog_query()>
 8949: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8950: activity.log file. %filters defines filters applied when parsing the
 8951: log file. These can be start or end timestamps, or the type of action
 8952: - log to look for Login or Logout events, check for Checkin or
 8953: Checkout, role for role selection. The response is in the form
 8954: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8955: escaped strings of the action recorded in the activity.log file.
 8956: 
 8957: =back
 8958: 
 8959: =head2 User Roles
 8960: 
 8961: =over 4
 8962: 
 8963: =item *
 8964: 
 8965: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8966:  F: full access
 8967:  U,I,K: authentication modes (cxx only)
 8968:  '': forbidden
 8969:  1: user needs to choose course
 8970:  2: browse allowed
 8971:  A: passphrase authentication needed
 8972: 
 8973: =item *
 8974: 
 8975: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8976: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8977: and course level
 8978: 
 8979: =item *
 8980: 
 8981: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8982: explanation of a user role term
 8983: 
 8984: =item *
 8985: 
 8986: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8987: All arguments are optional. Returns a hash of a roles, either for
 8988: co-author/assistant author roles for a user's Construction Space
 8989: (default), or if $context is 'userroles', roles for the user himself,
 8990: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8991: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8992: For each key, value is set to colon-separated start and end times for
 8993: the role.  If no username and domain are specified, will default to
 8994: current user/domain. Types, roles, and roledoms are references to arrays
 8995: of role statuses (active, future or previous), roles 
 8996: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8997: to restrict the list of roles reported. If no array ref is 
 8998: provided for types, will default to return only active roles.
 8999: 
 9000: =back
 9001: 
 9002: =head2 User Modification
 9003: 
 9004: =over 4
 9005: 
 9006: =item *
 9007: 
 9008: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 9009: user for the level given by URL.  Optional start and end dates (leave empty
 9010: string or zero for "no date")
 9011: 
 9012: =item *
 9013: 
 9014: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9015: change a users, password, possible return values are: ok,
 9016: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9017: refused
 9018: 
 9019: =item *
 9020: 
 9021: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9022: 
 9023: =item *
 9024: 
 9025: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 9026: modify user
 9027: 
 9028: =item *
 9029: 
 9030: modifystudent
 9031: 
 9032: modify a students enrollment and identification information.
 9033: The course id is resolved based on the current users environment.  
 9034: This means the envoking user must be a course coordinator or otherwise
 9035: associated with a course.
 9036: 
 9037: This call is essentially a wrapper for lonnet::modifyuser and
 9038: lonnet::modify_student_enrollment
 9039: 
 9040: Inputs: 
 9041: 
 9042: =over 4
 9043: 
 9044: =item B<$udom> Students loncapa domain
 9045: 
 9046: =item B<$uname> Students loncapa login name
 9047: 
 9048: =item B<$uid> Students id/student number
 9049: 
 9050: =item B<$umode> Students authentication mode
 9051: 
 9052: =item B<$upass> Students password
 9053: 
 9054: =item B<$first> Students first name
 9055: 
 9056: =item B<$middle> Students middle name
 9057: 
 9058: =item B<$last> Students last name
 9059: 
 9060: =item B<$gene> Students generation
 9061: 
 9062: =item B<$usec> Students section in course
 9063: 
 9064: =item B<$end> Unix time of the roles expiration
 9065: 
 9066: =item B<$start> Unix time of the roles start date
 9067: 
 9068: =item B<$forceid> If defined, allow $uid to be changed
 9069: 
 9070: =item B<$desiredhome> server to use as home server for student
 9071: 
 9072: =back
 9073: 
 9074: =item *
 9075: 
 9076: modify_student_enrollment
 9077: 
 9078: Change a students enrollment status in a class.  The environment variable
 9079: 'role.request.course' must be defined for this function to proceed.
 9080: 
 9081: Inputs:
 9082: 
 9083: =over 4
 9084: 
 9085: =item $udom, students domain
 9086: 
 9087: =item $uname, students name
 9088: 
 9089: =item $uid, students user id
 9090: 
 9091: =item $first, students first name
 9092: 
 9093: =item $middle
 9094: 
 9095: =item $last
 9096: 
 9097: =item $gene
 9098: 
 9099: =item $usec
 9100: 
 9101: =item $end
 9102: 
 9103: =item $start
 9104: 
 9105: =back
 9106: 
 9107: 
 9108: =item *
 9109: 
 9110: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9111: custom role; give a custom role to a user for the level given by URL.  Specify
 9112: name and domain of role author, and role name
 9113: 
 9114: =item *
 9115: 
 9116: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9117: 
 9118: =item *
 9119: 
 9120: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9121: 
 9122: =back
 9123: 
 9124: =head2 Course Infomation
 9125: 
 9126: =over 4
 9127: 
 9128: =item *
 9129: 
 9130: coursedescription($courseid) : returns a hash of information about the
 9131: specified course id, including all environment settings for the
 9132: course, the description of the course will be in the hash under the
 9133: key 'description'
 9134: 
 9135: =item *
 9136: 
 9137: resdata($name,$domain,$type,@which) : request for current parameter
 9138: setting for a specific $type, where $type is either 'course' or 'user',
 9139: @what should be a list of parameters to ask about. This routine caches
 9140: answers for 5 minutes.
 9141: 
 9142: =item *
 9143: 
 9144: get_courseresdata($courseid, $domain) : dump the entire course resource
 9145: data base, returning a hash that is keyed by the resource name and has
 9146: values that are the resource value.  I believe that the timestamps and
 9147: versions are also returned.
 9148: 
 9149: 
 9150: =back
 9151: 
 9152: =head2 Course Modification
 9153: 
 9154: =over 4
 9155: 
 9156: =item *
 9157: 
 9158: writecoursepref($courseid,%prefs) : write preferences (environment
 9159: database) for a course
 9160: 
 9161: =item *
 9162: 
 9163: createcourse($udom,$description,$url) : make/modify course
 9164: 
 9165: =back
 9166: 
 9167: =head2 Resource Subroutines
 9168: 
 9169: =over 4
 9170: 
 9171: =item *
 9172: 
 9173: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9174: 
 9175: =item *
 9176: 
 9177: repcopy($filename) : subscribes to the requested file, and attempts to
 9178: replicate from the owning library server, Might return
 9179: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9180: 'bad_request', also attempts to grab the metadata for the
 9181: resource. Expects the local filesystem pathname
 9182: (/home/httpd/html/res/....)
 9183: 
 9184: =back
 9185: 
 9186: =head2 Resource Information
 9187: 
 9188: =over 4
 9189: 
 9190: =item *
 9191: 
 9192: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9193: a vairety of different possible values, $varname should be a request
 9194: string, and the other parameters can be used to specify who and what
 9195: one is asking about.
 9196: 
 9197: Possible values for $varname are environment.lastname (or other item
 9198: from the envirnment hash), user.name (or someother aspect about the
 9199: user), resource.0.maxtries (or some other part and parameter of a
 9200: resource)
 9201: 
 9202: =item *
 9203: 
 9204: directcondval($number) : get current value of a condition; reads from a state
 9205: string
 9206: 
 9207: =item *
 9208: 
 9209: condval($condidx) : value of condition index based on state
 9210: 
 9211: =item *
 9212: 
 9213: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9214: resource's metadata, $what should be either a specific key, or either
 9215: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9216: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9217: 
 9218: this function automatically caches all requests
 9219: 
 9220: =item *
 9221: 
 9222: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9223: network of library servers; returns file handle of where SQL and regex results
 9224: will be stored for query
 9225: 
 9226: =item *
 9227: 
 9228: symbread($filename) : return symbolic list entry (filename argument optional);
 9229: returns the data handle
 9230: 
 9231: =item *
 9232: 
 9233: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9234: a possible symb for the URL in $thisfn, and if is an encryypted
 9235: resource that the user accessed using /enc/ returns a 1 on success, 0
 9236: on failure, user must be in a course, as it assumes the existance of
 9237: the course initial hash, and uses $env('request.course.id'}
 9238: 
 9239: 
 9240: =item *
 9241: 
 9242: symbclean($symb) : removes versions numbers from a symb, returns the
 9243: cleaned symb
 9244: 
 9245: =item *
 9246: 
 9247: is_on_map($uri) : checks if the $uri is somewhere on the current
 9248: course map, user must be in a course for it to work.
 9249: 
 9250: =item *
 9251: 
 9252: numval($salt) : return random seed value (addend for rndseed)
 9253: 
 9254: =item *
 9255: 
 9256: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9257: a random seed, all arguments are optional, if they aren't sent it uses the
 9258: environment to derive them. Note: if symb isn't sent and it can't get one
 9259: from &symbread it will use the current time as its return value
 9260: 
 9261: =item *
 9262: 
 9263: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9264: unfakeable, receipt
 9265: 
 9266: =item *
 9267: 
 9268: receipt() : API to ireceipt working off of env values; given out to users
 9269: 
 9270: =item *
 9271: 
 9272: countacc($url) : count the number of accesses to a given URL
 9273: 
 9274: =item *
 9275: 
 9276: 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
 9277: 
 9278: =item *
 9279: 
 9280: 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)
 9281: 
 9282: =item *
 9283: 
 9284: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9285: 
 9286: =item *
 9287: 
 9288: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9289: forcing spreadsheet to reevaluate the resource scores next time.
 9290: 
 9291: =back
 9292: 
 9293: =head2 Storing/Retreiving Data
 9294: 
 9295: =over 4
 9296: 
 9297: =item *
 9298: 
 9299: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9300: for this url; hashref needs to be given and should be a \%hashname; the
 9301: remaining args aren't required and if they aren't passed or are '' they will
 9302: be derived from the env
 9303: 
 9304: =item *
 9305: 
 9306: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9307: uses critical subroutine
 9308: 
 9309: =item *
 9310: 
 9311: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9312: all args are optional
 9313: 
 9314: =item *
 9315: 
 9316: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9317: dumps the complete (or key matching regexp) namespace into a hash
 9318: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9319: normally &store()ed into
 9320: 
 9321: $range should be either an integer '100' (give me the first 100
 9322:                                            matching records)
 9323:               or be  two integers sperated by a - with no spaces
 9324:                  '30-50' (give me the 30th through the 50th matching
 9325:                           records)
 9326: 
 9327: 
 9328: =item *
 9329: 
 9330: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9331: replaces a &store() version of data with a replacement set of data
 9332: for a particular resource in a namespace passed in the $storehash hash 
 9333: reference
 9334: 
 9335: =item *
 9336: 
 9337: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9338: works very similar to store/cstore, but all data is stored in a
 9339: temporary location and can be reset using tmpreset, $storehash should
 9340: be a hash reference, returns nothing on success
 9341: 
 9342: =item *
 9343: 
 9344: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9345: similar to restore, but all data is stored in a temporary location and
 9346: can be reset using tmpreset. Returns a hash of values on success,
 9347: error string otherwise.
 9348: 
 9349: =item *
 9350: 
 9351: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9352: deltes all keys for $symb form the temporary storage hash.
 9353: 
 9354: =item *
 9355: 
 9356: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9357: reference filled in from namesp ($udom and $uname are optional)
 9358: 
 9359: =item *
 9360: 
 9361: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9362: namesp ($udom and $uname are optional)
 9363: 
 9364: =item *
 9365: 
 9366: dump($namespace,$udom,$uname,$regexp,$range) : 
 9367: dumps the complete (or key matching regexp) namespace into a hash
 9368: ($udom, $uname, $regexp, $range are optional)
 9369: 
 9370: $range should be either an integer '100' (give me the first 100
 9371:                                            matching records)
 9372:               or be  two integers sperated by a - with no spaces
 9373:                  '30-50' (give me the 30th through the 50th matching
 9374:                           records)
 9375: =item *
 9376: 
 9377: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9378: $store can be a scalar, an array reference, or if the amount to be 
 9379: incremented is > 1, a hash reference.
 9380: 
 9381: ($udom and $uname are optional)
 9382: 
 9383: =item *
 9384: 
 9385: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9386: ($udom and $uname are optional)
 9387: 
 9388: =item *
 9389: 
 9390: cput($namespace,$storehash,$udom,$uname) : critical put
 9391: ($udom and $uname are optional)
 9392: 
 9393: =item *
 9394: 
 9395: newput($namespace,$storehash,$udom,$uname) :
 9396: 
 9397: Attempts to store the items in the $storehash, but only if they don't
 9398: currently exist, if this succeeds you can be certain that you have 
 9399: successfully created a new key value pair in the $namespace db.
 9400: 
 9401: 
 9402: Args:
 9403:  $namespace: name of database to store values to
 9404:  $storehash: hashref to store to the db
 9405:  $udom: (optional) domain of user containing the db
 9406:  $uname: (optional) name of user caontaining the db
 9407: 
 9408: Returns:
 9409:  'ok' -> succeeded in storing all keys of $storehash
 9410:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9411:                         least <key> already existed in the db (other
 9412:                         requested keys may also already exist)
 9413:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9414:  'con_lost' -> unable to contact request server
 9415:  'refused' -> action was not allowed by remote machine
 9416: 
 9417: 
 9418: =item *
 9419: 
 9420: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9421: reference filled in from namesp (encrypts the return communication)
 9422: ($udom and $uname are optional)
 9423: 
 9424: =item *
 9425: 
 9426: log($udom,$name,$home,$message) : write to permanent log for user; use
 9427: critical subroutine
 9428: 
 9429: =item *
 9430: 
 9431: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9432: array reference filled in from namespace found in domain level on either
 9433: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9434: 
 9435: =item *
 9436: 
 9437: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9438: domain level either on specified domain server ($uhome) or primary domain 
 9439: server ($udom and $uhome are optional)
 9440: 
 9441: =item * 
 9442: 
 9443: get_domain_defaults($target_domain) : returns hash with defaults for
 9444: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9445: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9446: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9447: Values are retrieved from cache (if current), or from domain's configuration.db
 9448: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9449: or lonTabs/domain.tab. 
 9450: 
 9451: %domdefaults = &get_auth_defaults($target_domain);
 9452: 
 9453: =back
 9454: 
 9455: =head2 Network Status Functions
 9456: 
 9457: =over 4
 9458: 
 9459: =item *
 9460: 
 9461: dirlist($uri) : return directory list based on URI
 9462: 
 9463: =item *
 9464: 
 9465: spareserver() : find server with least workload from spare.tab
 9466: 
 9467: =back
 9468: 
 9469: =head2 Apache Request
 9470: 
 9471: =over 4
 9472: 
 9473: =item *
 9474: 
 9475: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9476: localhost, posts hash
 9477: 
 9478: =back
 9479: 
 9480: =head2 Data to String to Data
 9481: 
 9482: =over 4
 9483: 
 9484: =item *
 9485: 
 9486: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9487: and '&' separators, supports elements that are arrayrefs and hashrefs
 9488: 
 9489: =item *
 9490: 
 9491: hashref2str($hashref) : convert a hashref into a string complete with
 9492: escaping and '=' and '&' separators, supports elements that are
 9493: arrayrefs and hashrefs
 9494: 
 9495: =item *
 9496: 
 9497: arrayref2str($arrayref) : convert an arrayref into a string complete
 9498: with escaping and '&' separators, supports elements that are arrayrefs
 9499: and hashrefs
 9500: 
 9501: =item *
 9502: 
 9503: str2hash($string) : convert string to hash using unescaping and
 9504: splitting on '=' and '&', supports elements that are arrayrefs and
 9505: hashrefs
 9506: 
 9507: =item *
 9508: 
 9509: str2array($string) : convert string to hash using unescaping and
 9510: splitting on '&', supports elements that are arrayrefs and hashrefs
 9511: 
 9512: =back
 9513: 
 9514: =head2 Logging Routines
 9515: 
 9516: =over 4
 9517: 
 9518: These routines allow one to make log messages in the lonnet.log and
 9519: lonnet.perm logfiles.
 9520: 
 9521: =item *
 9522: 
 9523: logtouch() : make sure the logfile, lonnet.log, exists
 9524: 
 9525: =item *
 9526: 
 9527: logthis() : append message to the normal lonnet.log file, it gets
 9528: preiodically rolled over and deleted.
 9529: 
 9530: =item *
 9531: 
 9532: logperm() : append a permanent message to lonnet.perm.log, this log
 9533: file never gets deleted by any automated portion of the system, only
 9534: messages of critical importance should go in here.
 9535: 
 9536: =back
 9537: 
 9538: =head2 General File Helper Routines
 9539: 
 9540: =over 4
 9541: 
 9542: =item *
 9543: 
 9544: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9545: (a) files in /uploaded
 9546:   (i) If a local copy of the file exists - 
 9547:       compares modification date of local copy with last-modified date for 
 9548:       definitive version stored on home server for course. If local copy is 
 9549:       stale, requests a new version from the home server and stores it. 
 9550:       If the original has been removed from the home server, then local copy 
 9551:       is unlinked.
 9552:   (ii) If local copy does not exist -
 9553:       requests the file from the home server and stores it. 
 9554:   
 9555:   If $caller is 'uploadrep':  
 9556:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9557:     for request for files originally uploaded via DOCS. 
 9558:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9559:   
 9560:   Otherwise:
 9561:      This indicates a call from the content generation phase of the request.
 9562:      -  returns the entire contents of the file or -1.
 9563:      
 9564: (b) files in /res
 9565:    - returns the entire contents of a file or -1; 
 9566:    it properly subscribes to and replicates the file if neccessary.
 9567: 
 9568: 
 9569: =item *
 9570: 
 9571: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9572:                   reference
 9573: 
 9574: returns either a stat() list of data about the file or an empty list
 9575: if the file doesn't exist or couldn't find out about it (connection
 9576: problems or user unknown)
 9577: 
 9578: =item *
 9579: 
 9580: filelocation($dir,$file) : returns file system location of a file
 9581: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9582: directory that relative $file lookups are to looked in ($dir of /a/dir
 9583: and a file of ../bob will become /a/bob)
 9584: 
 9585: =item *
 9586: 
 9587: hreflocation($dir,$file) : returns file system location or a URL; same as
 9588: filelocation except for hrefs
 9589: 
 9590: =item *
 9591: 
 9592: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9593: 
 9594: =back
 9595: 
 9596: =head2 Usererfile file routines (/uploaded*)
 9597: 
 9598: =over 4
 9599: 
 9600: =item *
 9601: 
 9602: userfileupload(): main rotine for putting a file in a user or course's
 9603:                   filespace, arguments are,
 9604: 
 9605:  formname - required - this is the name of the element in $env where the
 9606:            filename, and the contents of the file to create/modifed exist
 9607:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9608:            contents of the file is located in $env{'form.'.$formname}
 9609:  coursedoc - if true, store the file in the course of the active role
 9610:              of the current user
 9611:  subdir - required - subdirectory to put the file in under ../userfiles/
 9612:          if undefined, it will be placed in "unknown"
 9613: 
 9614:  (This routine calls clean_filename() to remove any dangerous
 9615:  characters from the filename, and then calls finuserfileupload() to
 9616:  complete the transaction)
 9617: 
 9618:  returns either the url of the uploaded file (/uploaded/....) if successful
 9619:  and /adm/notfound.html if unsuccessful
 9620: 
 9621: =item *
 9622: 
 9623: clean_filename(): routine for cleaing a filename up for storage in
 9624:                  userfile space, argument is:
 9625: 
 9626:  filename - proposed filename
 9627: 
 9628: returns: the new clean filename
 9629: 
 9630: =item *
 9631: 
 9632: finishuserfileupload(): routine that creaes and sends the file to
 9633: userspace, probably shouldn't be called directly
 9634: 
 9635:   docuname: username or courseid of destination for the file
 9636:   docudom: domain of user/course of destination for the file
 9637:   formname: same as for userfileupload()
 9638:   fname: filename (inculding subdirectories) for the file
 9639: 
 9640:  returns either the url of the uploaded file (/uploaded/....) if successful
 9641:  and /adm/notfound.html if unsuccessful
 9642: 
 9643: =item *
 9644: 
 9645: renameuserfile(): renames an existing userfile to a new name
 9646: 
 9647:   Args:
 9648:    docuname: username or courseid of destination for the file
 9649:    docudom: domain of user/course of destination for the file
 9650:    old: current file name (including any subdirs under userfiles)
 9651:    new: desired file name (including any subdirs under userfiles)
 9652: 
 9653: =item *
 9654: 
 9655: mkdiruserfile(): creates a directory is a userfiles dir
 9656: 
 9657:   Args:
 9658:    docuname: username or courseid of destination for the file
 9659:    docudom: domain of user/course of destination for the file
 9660:    dir: dir to create (including any subdirs under userfiles)
 9661: 
 9662: =item *
 9663: 
 9664: removeuserfile(): removes a file that exists in userfiles
 9665: 
 9666:   Args:
 9667:    docuname: username or courseid of destination for the file
 9668:    docudom: domain of user/course of destination for the file
 9669:    fname: filname to delete (including any subdirs under userfiles)
 9670: 
 9671: =item *
 9672: 
 9673: removeuploadedurl(): convience function for removeuserfile()
 9674: 
 9675:   Args:
 9676:    url:  a full /uploaded/... url to delete
 9677: 
 9678: =item * 
 9679: 
 9680: get_portfile_permissions():
 9681:   Args:
 9682:     domain: domain of user or course contain the portfolio files
 9683:     user: name of user or num of course contain the portfolio files
 9684:   Returns:
 9685:     hashref of a dump of the proper file_permissions.db
 9686:    
 9687: 
 9688: =item * 
 9689: 
 9690: get_access_controls():
 9691: 
 9692: Args:
 9693:   current_permissions: the hash ref returned from get_portfile_permissions()
 9694:   group: (optional) the group you want the files associated with
 9695:   file: (optional) the file you want access info on
 9696: 
 9697: Returns:
 9698:     a hash (keys are file names) of hashes containing
 9699:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9700:         values are XML containing access control settings (see below) 
 9701: 
 9702: Internal notes:
 9703: 
 9704:  access controls are stored in file_permissions.db as key=value pairs.
 9705:     key -> path to file/file_name\0uniqueID:scope_end_start
 9706:         where scope -> public,guest,course,group,domains or users.
 9707:               end -> UNIX time for end of access (0 -> no end date)
 9708:               start -> UNIX time for start of access
 9709: 
 9710:     value -> XML description of access control
 9711:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9712:             <start></start>
 9713:             <end></end>
 9714: 
 9715:             <password></password>  for scope type = guest
 9716: 
 9717:             <domain></domain>     for scope type = course or group
 9718:             <number></number>
 9719:             <roles id="">
 9720:              <role></role>
 9721:              <access></access>
 9722:              <section></section>
 9723:              <group></group>
 9724:             </roles>
 9725: 
 9726:             <dom></dom>         for scope type = domains
 9727: 
 9728:             <users>             for scope type = users
 9729:              <user>
 9730:               <uname></uname>
 9731:               <udom></udom>
 9732:              </user>
 9733:             </users>
 9734:            </scope> 
 9735:               
 9736:  Access data is also aggregated for each file in an additional key=value pair:
 9737:  key -> path to file/file_name\0accesscontrol 
 9738:  value -> reference to hash
 9739:           hash contains key = value pairs
 9740:           where key = uniqueID:scope_end_start
 9741:                 value = UNIX time record was last updated
 9742: 
 9743:           Used to improve speed of look-ups of access controls for each file.  
 9744:  
 9745:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9746: 
 9747: modify_access_controls():
 9748: 
 9749: Modifies access controls for a portfolio file
 9750: Args
 9751: 1. file name
 9752: 2. reference to hash of required changes,
 9753: 3. domain
 9754: 4. username
 9755:   where domain,username are the domain of the portfolio owner 
 9756:   (either a user or a course) 
 9757: 
 9758: Returns:
 9759: 1. result of additions or updates ('ok' or 'error', with error message). 
 9760: 2. result of deletions ('ok' or 'error', with error message).
 9761: 3. reference to hash of any new or updated access controls.
 9762: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9763:    key = integer (inbound ID)
 9764:    value = uniqueID  
 9765: 
 9766: =back
 9767: 
 9768: =head2 HTTP Helper Routines
 9769: 
 9770: =over 4
 9771: 
 9772: =item *
 9773: 
 9774: escape() : unpack non-word characters into CGI-compatible hex codes
 9775: 
 9776: =item *
 9777: 
 9778: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9779: 
 9780: =back
 9781: 
 9782: =head1 PRIVATE SUBROUTINES
 9783: 
 9784: =head2 Underlying communication routines (Shouldn't call)
 9785: 
 9786: =over 4
 9787: 
 9788: =item *
 9789: 
 9790: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9791: 
 9792: =item *
 9793: 
 9794: reply() : uses subreply to send a message to remote machine, logs all failures
 9795: 
 9796: =item *
 9797: 
 9798: critical() : passes a critical message to another server; if cannot
 9799: get through then place message in connection buffer directory and
 9800: returns con_delayed, if incapable of saving message, returns
 9801: con_failed
 9802: 
 9803: =item *
 9804: 
 9805: reconlonc() : tries to reconnect lonc client processes.
 9806: 
 9807: =back
 9808: 
 9809: =head2 Resource Access Logging
 9810: 
 9811: =over 4
 9812: 
 9813: =item *
 9814: 
 9815: flushcourselogs() : flush (save) buffer logs and access logs
 9816: 
 9817: =item *
 9818: 
 9819: courselog($what) : save message for course in hash
 9820: 
 9821: =item *
 9822: 
 9823: courseacclog($what) : save message for course using &courselog().  Perform
 9824: special processing for specific resource types (problems, exams, quizzes, etc).
 9825: 
 9826: =item *
 9827: 
 9828: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9829: as a PerlChildExitHandler
 9830: 
 9831: =back
 9832: 
 9833: =head2 Other
 9834: 
 9835: =over 4
 9836: 
 9837: =item *
 9838: 
 9839: symblist($mapname,%newhash) : update symbolic storage links
 9840: 
 9841: =back
 9842: 
 9843: =cut
 9844: 

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