File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.780: download - view: text, annotated - select for diffs
Fri Sep 15 07:55:05 2006 UTC (17 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- some more speedups, transferring env could happen in multiple places now (Access or Authz phase, no need to do it twice)

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.780 2006/09/15 07:55:05 albertel 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::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: use lib '/home/httpd/lib/perl';
   56: use LONCAPA;
   57: use LONCAPA::Configuration;
   58: 
   59: my $readit;
   60: my $max_connection_retries = 10;     # Or some such value.
   61: 
   62: require Exporter;
   63: 
   64: our @ISA = qw (Exporter);
   65: our @EXPORT = qw(%env);
   66: 
   67: =pod
   68: 
   69: =head1 Package Variables
   70: 
   71: These are largely undocumented, so if you decipher one please note it here.
   72: 
   73: =over 4
   74: 
   75: =item $processmarker
   76: 
   77: Contains the time this process was started and this servers host id.
   78: 
   79: =item $dumpcount
   80: 
   81: Counts the number of times a message log flush has been attempted (regardless
   82: of success) by this process.  Used as part of the filename when messages are
   83: delayed.
   84: 
   85: =back
   86: 
   87: =cut
   88: 
   89: 
   90: # --------------------------------------------------------------------- Logging
   91: {
   92:     my $logid;
   93:     sub instructor_log {
   94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   95: 	$logid++;
   96: 	my $id=time().'00000'.$$.'00000'.$logid;
   97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   98: 				    { $id => {
   99: 					'exe_uname' => $env{'user.name'},
  100: 					'exe_udom'  => $env{'user.domain'},
  101: 					'exe_time'  => time(),
  102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  103: 					'delflag'   => $delflag,
  104: 					'logentry'  => $storehash,
  105: 					'uname'     => $uname,
  106: 					'udom'      => $udom,
  107: 				    }
  108: 				  },
  109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  111: 				    );
  112:     }
  113: }
  114: 
  115: sub logtouch {
  116:     my $execdir=$perlvar{'lonDaemons'};
  117:     unless (-e "$execdir/logs/lonnet.log") {	
  118: 	open(my $fh,">>$execdir/logs/lonnet.log");
  119: 	close $fh;
  120:     }
  121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  123: }
  124: 
  125: sub logthis {
  126:     my $message=shift;
  127:     my $execdir=$perlvar{'lonDaemons'};
  128:     my $now=time;
  129:     my $local=localtime($now);
  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  131: 	print $fh "$local ($$): $message\n";
  132: 	close($fh);
  133:     }
  134:     return 1;
  135: }
  136: 
  137: sub logperm {
  138:     my $message=shift;
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     my $now=time;
  141:     my $local=localtime($now);
  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  143: 	print $fh "$now:$message:$local\n";
  144: 	close($fh);
  145:     }
  146:     return 1;
  147: }
  148: 
  149: # -------------------------------------------------- Non-critical communication
  150: sub subreply {
  151:     my ($cmd,$server)=@_;
  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
  153:     #
  154:     #  With loncnew process trimming, there's a timing hole between lonc server
  155:     #  process exit and the master server picking up the listen on the AF_UNIX
  156:     #  socket.  In that time interval, a lock file will exist:
  157: 
  158:     my $lockfile=$peerfile.".lock";
  159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  160: 	sleep(1);
  161:     }
  162:     # At this point, either a loncnew parent is listening or an old lonc
  163:     # or loncnew child is listening so we can connect or everything's dead.
  164:     #
  165:     #   We'll give the connection a few tries before abandoning it.  If
  166:     #   connection is not possible, we'll con_lost back to the client.
  167:     #   
  168:     my $client;
  169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  171: 				      Type    => SOCK_STREAM,
  172: 				      Timeout => 10);
  173: 	if($client) {
  174: 	    last;		# Connected!
  175: 	}
  176: 	sleep(1);		# Try again later if failed connection.
  177:     }
  178:     my $answer;
  179:     if ($client) {
  180: 	print $client "sethost:$server:$cmd\n";
  181: 	$answer=<$client>;
  182: 	if (!$answer) { $answer="con_lost"; }
  183: 	chomp($answer);
  184:     } else {
  185: 	$answer = 'con_lost';	# Failed connection.
  186:     }
  187:     return $answer;
  188: }
  189: 
  190: sub reply {
  191:     my ($cmd,$server)=@_;
  192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  193:     my $answer=subreply($cmd,$server);
  194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  195:        &logthis("<font color=\"blue\">WARNING:".
  196:                 " $cmd to $server returned $answer</font>");
  197:     }
  198:     return $answer;
  199: }
  200: 
  201: # ----------------------------------------------------------- Send USR1 to lonc
  202: 
  203: sub reconlonc {
  204:     my $peerfile=shift;
  205:     &logthis("Trying to reconnect for $peerfile");
  206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  207:     if (open(my $fh,"<$loncfile")) {
  208: 	my $loncpid=<$fh>;
  209:         chomp($loncpid);
  210:         if (kill 0 => $loncpid) {
  211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  212:             kill USR1 => $loncpid;
  213:             sleep 1;
  214:             if (-e "$peerfile") { return; }
  215:             &logthis("$peerfile still not there, give it another try");
  216:             sleep 5;
  217:             if (-e "$peerfile") { return; }
  218:             &logthis(
  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
  220:         } else {
  221: 	    &logthis(
  222:                "<font color=\"blue\">WARNING:".
  223:                " lonc at pid $loncpid not responding, giving up</font>");
  224:         }
  225:     } else {
  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  227:     }
  228: }
  229: 
  230: # ------------------------------------------------------ Critical communication
  231: 
  232: sub critical {
  233:     my ($cmd,$server)=@_;
  234:     unless ($hostname{$server}) {
  235:         &logthis("<font color=\"blue\">WARNING:".
  236:                " Critical message to unknown server ($server)</font>");
  237:         return 'no_such_host';
  238:     }
  239:     my $answer=reply($cmd,$server);
  240:     if ($answer eq 'con_lost') {
  241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  242: 	my $answer=reply($cmd,$server);
  243:         if ($answer eq 'con_lost') {
  244:             my $now=time;
  245:             my $middlename=$cmd;
  246:             $middlename=substr($middlename,0,16);
  247:             $middlename=~s/\W//g;
  248:             my $dfilename=
  249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  250:             $dumpcount++;
  251:             {
  252: 		my $dfh;
  253: 		if (open($dfh,">$dfilename")) {
  254: 		    print $dfh "$cmd\n"; 
  255: 		    close($dfh);
  256: 		}
  257:             }
  258:             sleep 2;
  259:             my $wcmd='';
  260:             {
  261: 		my $dfh;
  262: 		if (open($dfh,"<$dfilename")) {
  263: 		    $wcmd=<$dfh>; 
  264: 		    close($dfh);
  265: 		}
  266:             }
  267:             chomp($wcmd);
  268:             if ($wcmd eq $cmd) {
  269: 		&logthis("<font color=\"blue\">WARNING: ".
  270:                          "Connection buffer $dfilename: $cmd</font>");
  271:                 &logperm("D:$server:$cmd");
  272: 	        return 'con_delayed';
  273:             } else {
  274:                 &logthis("<font color=\"red\">CRITICAL:"
  275:                         ." Critical connection failed: $server $cmd</font>");
  276:                 &logperm("F:$server:$cmd");
  277:                 return 'con_failed';
  278:             }
  279:         }
  280:     }
  281:     return $answer;
  282: }
  283: 
  284: # ------------------------------------------- check if return value is an error
  285: 
  286: sub error {
  287:     my ($result) = @_;
  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  289: 	if ($2 == 2) { return undef; }
  290: 	return $1;
  291:     }
  292:     return undef;
  293: }
  294: 
  295: # ------------------------------------------- Transfer profile into environment
  296: my $env_loaded;
  297: sub transfer_profile_to_env {
  298:     if ($env_loaded) { return; } 
  299: 
  300:     my ($lonidsdir,$handle)=@_;
  301:     if (!defined($lonidsdir)) {
  302: 	$lonidsdir = $perlvar{'lonIDsDir'};
  303:     }
  304:     if (!defined($handle)) {
  305:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  306:     }
  307: 
  308:     my @profile;
  309:     {
  310: 	open(my $idf,"$lonidsdir/$handle.id");
  311: 	flock($idf,LOCK_SH);
  312: 	@profile=<$idf>;
  313: 	close($idf);
  314:     }
  315:     my $envi;
  316:     my %Remove;
  317:     for ($envi=0;$envi<=$#profile;$envi++) {
  318: 	chomp($profile[$envi]);
  319: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
  320: 	$envname=&unescape($envname);
  321: 	$envvalue=&unescape($envvalue);
  322: 	$env{$envname} = $envvalue;
  323:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  324:             if ($time < time-300) {
  325:                 $Remove{$key}++;
  326:             }
  327:         }
  328:     }
  329:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  330:     $env_loaded=1;
  331:     foreach my $expired_key (keys(%Remove)) {
  332:         &delenv($expired_key);
  333:     }
  334: }
  335: 
  336: # ---------------------------------------------------------- Append Environment
  337: 
  338: sub appenv {
  339:     my %newenv=@_;
  340:     foreach my $key (keys(%newenv)) {
  341: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  342:             &logthis("<font color=\"blue\">WARNING: ".
  343:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  344:                 .'</font>');
  345: 	    delete($newenv{$key});
  346:         } else {
  347:             $env{$key}=$newenv{$key};
  348:         }
  349:     }
  350:     foreach my $key (keys(%newenv)) {
  351: 	my $value = &escape($newenv{$key});
  352: 	delete($newenv{$key});
  353: 	$newenv{&escape($key)}=$value;
  354:     }
  355: 
  356:     my $lockfh;
  357:     unless (open($lockfh,"$env{'user.environment'}")) {
  358: 	return 'error: '.$!;
  359:     }
  360:     unless (flock($lockfh,LOCK_EX)) {
  361:          &logthis("<font color=\"blue\">WARNING: ".
  362:                   'Could not obtain exclusive lock in appenv: '.$!);
  363:          close($lockfh);
  364:          return 'error: '.$!;
  365:     }
  366: 
  367:     my @oldenv;
  368:     {
  369: 	my $fh;
  370: 	unless (open($fh,"$env{'user.environment'}")) {
  371: 	    return 'error: '.$!;
  372: 	}
  373: 	@oldenv=<$fh>;
  374: 	close($fh);
  375:     }
  376:     for (my $i=0; $i<=$#oldenv; $i++) {
  377:         chomp($oldenv[$i]);
  378:         if ($oldenv[$i] ne '') {
  379: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
  380: 	    unless (defined($newenv{$name})) {
  381: 		$newenv{$name}=$value;
  382: 	    }
  383:         }
  384:     }
  385:     {
  386: 	my $fh;
  387: 	unless (open($fh,">$env{'user.environment'}")) {
  388: 	    return 'error';
  389: 	}
  390: 	my $newname;
  391: 	foreach $newname (keys %newenv) {
  392: 	    print $fh $newname.'='.$newenv{$newname}."\n";
  393: 	}
  394: 	close($fh);
  395:     }
  396: 	
  397:     close($lockfh);
  398:     return 'ok';
  399: }
  400: # ----------------------------------------------------- Delete from Environment
  401: 
  402: sub delenv {
  403:     my $delthis=shift;
  404:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  405:         &logthis("<font color=\"blue\">WARNING: ".
  406:                 "Attempt to delete from environment ".$delthis);
  407:         return 'error';
  408:     }
  409:     my @oldenv;
  410:     {
  411: 	my $fh;
  412: 	unless (open($fh,"$env{'user.environment'}")) {
  413: 	    return 'error';
  414: 	}
  415: 	unless (flock($fh,LOCK_SH)) {
  416: 	    &logthis("<font color=\"blue\">WARNING: ".
  417: 		     'Could not obtain shared lock in delenv: '.$!);
  418: 	    close($fh);
  419: 	    return 'error: '.$!;
  420: 	}
  421: 	@oldenv=<$fh>;
  422: 	close($fh);
  423:     }
  424:     {
  425: 	my $fh;
  426: 	unless (open($fh,">$env{'user.environment'}")) {
  427: 	    return 'error';
  428: 	}
  429: 	unless (flock($fh,LOCK_EX)) {
  430: 	    &logthis("<font color=\"blue\">WARNING: ".
  431: 		     'Could not obtain exclusive lock in delenv: '.$!);
  432: 	    close($fh);
  433: 	    return 'error: '.$!;
  434: 	}
  435: 	foreach my $cur_key (@oldenv) {
  436: 	    my $unescaped_cur_key = &unescape($cur_key);
  437: 	    if ($unescaped_cur_key=~/^$delthis/) { 
  438:                 my ($key) = split('=',$cur_key,2);
  439: 		$key = &unescape($key);
  440:                 delete($env{$key});
  441:             } else {
  442:                 print $fh $cur_key; 
  443:             }
  444: 	}
  445: 	close($fh);
  446:     }
  447:     return 'ok';
  448: }
  449: 
  450: # ------------------------------------------ Find out current server userload
  451: # there is a copy in lond
  452: sub userload {
  453:     my $numusers=0;
  454:     {
  455: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  456: 	my $filename;
  457: 	my $curtime=time;
  458: 	while ($filename=readdir(LONIDS)) {
  459: 	    if ($filename eq '.' || $filename eq '..') {next;}
  460: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  461: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  462: 	}
  463: 	closedir(LONIDS);
  464:     }
  465:     my $userloadpercent=0;
  466:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  467:     if ($maxuserload) {
  468: 	$userloadpercent=100*$numusers/$maxuserload;
  469:     }
  470:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  471:     return $userloadpercent;
  472: }
  473: 
  474: # ------------------------------------------ Fight off request when overloaded
  475: 
  476: sub overloaderror {
  477:     my ($r,$checkserver)=@_;
  478:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  479:     my $loadavg;
  480:     if ($checkserver eq $perlvar{'lonHostID'}) {
  481:        open(my $loadfile,'/proc/loadavg');
  482:        $loadavg=<$loadfile>;
  483:        $loadavg =~ s/\s.*//g;
  484:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  485:        close($loadfile);
  486:     } else {
  487:        $loadavg=&reply('load',$checkserver);
  488:     }
  489:     my $overload=$loadavg-100;
  490:     if ($overload>0) {
  491: 	$r->err_headers_out->{'Retry-After'}=$overload;
  492:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  493:         return 413;
  494:     }    
  495:     return '';
  496: }
  497: 
  498: # ------------------------------ Find server with least workload from spare.tab
  499: 
  500: sub spareserver {
  501:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  502:     my $tryserver;
  503:     my $spareserver='';
  504:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  505:     my $lowestserver=$loadpercent > $userloadpercent?
  506: 	             $loadpercent :  $userloadpercent;
  507:     foreach $tryserver (keys(%spareid)) {
  508: 	my $loadans=&reply('load',$tryserver);
  509: 	my $userloadans=&reply('userload',$tryserver);
  510: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  511: 	    next; #didn't get a number from the server
  512: 	}
  513: 	my $answer;
  514: 	if ($loadans =~ /\d/) {
  515: 	    if ($userloadans =~ /\d/) {
  516: 		#both are numbers, pick the bigger one
  517: 		$answer=$loadans > $userloadans?
  518: 		    $loadans :  $userloadans;
  519: 	    } else {
  520: 		$answer = $loadans;
  521: 	    }
  522: 	} else {
  523: 	    $answer = $userloadans;
  524: 	}
  525: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  526: 	    if ($want_server_name) {
  527: 		$spareserver=$tryserver;
  528: 	    } else {
  529: 		$spareserver="http://$hostname{$tryserver}";
  530: 	    }
  531: 	    $lowestserver=$answer;
  532: 	}
  533:     }
  534:     return $spareserver;
  535: }
  536: 
  537: # --------------------------------------------- Try to change a user's password
  538: 
  539: sub changepass {
  540:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  541:     $currentpass = &escape($currentpass);
  542:     $newpass     = &escape($newpass);
  543:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  544: 		       $server);
  545:     if (! $answer) {
  546: 	&logthis("No reply on password change request to $server ".
  547: 		 "by $uname in domain $udom.");
  548:     } elsif ($answer =~ "^ok") {
  549:         &logthis("$uname in $udom successfully changed their password ".
  550: 		 "on $server.");
  551:     } elsif ($answer =~ "^pwchange_failure") {
  552: 	&logthis("$uname in $udom was unable to change their password ".
  553: 		 "on $server.  The action was blocked by either lcpasswd ".
  554: 		 "or pwchange");
  555:     } elsif ($answer =~ "^non_authorized") {
  556:         &logthis("$uname in $udom did not get their password correct when ".
  557: 		 "attempting to change it on $server.");
  558:     } elsif ($answer =~ "^auth_mode_error") {
  559:         &logthis("$uname in $udom attempted to change their password despite ".
  560: 		 "not being locally or internally authenticated on $server.");
  561:     } elsif ($answer =~ "^unknown_user") {
  562:         &logthis("$uname in $udom attempted to change their password ".
  563: 		 "on $server but were unable to because $server is not ".
  564: 		 "their home server.");
  565:     } elsif ($answer =~ "^refused") {
  566: 	&logthis("$server refused to change $uname in $udom password because ".
  567: 		 "it was sent an unencrypted request to change the password.");
  568:     }
  569:     return $answer;
  570: }
  571: 
  572: # ----------------------- Try to determine user's current authentication scheme
  573: 
  574: sub queryauthenticate {
  575:     my ($uname,$udom)=@_;
  576:     my $uhome=&homeserver($uname,$udom);
  577:     if (!$uhome) {
  578: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  579: 	return 'no_host';
  580:     }
  581:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  582:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  583: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  584:     }
  585:     return $answer;
  586: }
  587: 
  588: # --------- Try to authenticate user from domain's lib servers (first this one)
  589: 
  590: sub authenticate {
  591:     my ($uname,$upass,$udom)=@_;
  592:     $upass=escape($upass);
  593:     $uname=~s/\W//g;
  594:     my $uhome=&homeserver($uname,$udom);
  595:     if (!$uhome) {
  596: 	&logthis("User $uname at $udom is unknown in authenticate");
  597: 	return 'no_host';
  598:     }
  599:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  600:     if ($answer eq 'authorized') {
  601: 	&logthis("User $uname at $udom authorized by $uhome"); 
  602: 	return $uhome; 
  603:     }
  604:     if ($answer eq 'non_authorized') {
  605: 	&logthis("User $uname at $udom rejected by $uhome");
  606: 	return 'no_host'; 
  607:     }
  608:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  609:     return 'no_host';
  610: }
  611: 
  612: # ---------------------- Find the homebase for a user from domain's lib servers
  613: 
  614: my %homecache;
  615: sub homeserver {
  616:     my ($uname,$udom,$ignoreBadCache)=@_;
  617:     my $index="$uname:$udom";
  618: 
  619:     if (exists($homecache{$index})) { return $homecache{$index}; }
  620:     my $tryserver;
  621:     foreach $tryserver (keys %libserv) {
  622:         next if ($ignoreBadCache ne 'true' && 
  623: 		 exists($badServerCache{$tryserver}));
  624: 	if ($hostdom{$tryserver} eq $udom) {
  625:            my $answer=reply("home:$udom:$uname",$tryserver);
  626:            if ($answer eq 'found') { 
  627: 	       return $homecache{$index}=$tryserver;
  628:            } elsif ($answer eq 'no_host') {
  629: 	       $badServerCache{$tryserver}=1;
  630:            }
  631:        }
  632:     }    
  633:     return 'no_host';
  634: }
  635: 
  636: # ------------------------------------- Find the usernames behind a list of IDs
  637: 
  638: sub idget {
  639:     my ($udom,@ids)=@_;
  640:     my %returnhash=();
  641:     
  642:     my $tryserver;
  643:     foreach $tryserver (keys %libserv) {
  644:        if ($hostdom{$tryserver} eq $udom) {
  645: 	  my $idlist=join('&',@ids);
  646:           $idlist=~tr/A-Z/a-z/; 
  647: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  648:           my @answer=();
  649:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  650: 	      @answer=split(/\&/,$reply);
  651:           }                    ;
  652:           my $i;
  653:           for ($i=0;$i<=$#ids;$i++) {
  654:               if ($answer[$i]) {
  655: 		  $returnhash{$ids[$i]}=$answer[$i];
  656:               } 
  657:           }
  658:        }
  659:     }    
  660:     return %returnhash;
  661: }
  662: 
  663: # ------------------------------------- Find the IDs behind a list of usernames
  664: 
  665: sub idrget {
  666:     my ($udom,@unames)=@_;
  667:     my %returnhash=();
  668:     foreach (@unames) {
  669:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  670:     }
  671:     return %returnhash;
  672: }
  673: 
  674: # ------------------------------- Store away a list of names and associated IDs
  675: 
  676: sub idput {
  677:     my ($udom,%ids)=@_;
  678:     my %servers=();
  679:     foreach (keys %ids) {
  680: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  681:         my $uhom=&homeserver($_,$udom);
  682:         if ($uhom ne 'no_host') {
  683:             my $id=&escape($ids{$_});
  684:             $id=~tr/A-Z/a-z/;
  685:             my $unam=&escape($_);
  686: 	    if ($servers{$uhom}) {
  687: 		$servers{$uhom}.='&'.$id.'='.$unam;
  688:             } else {
  689:                 $servers{$uhom}=$id.'='.$unam;
  690:             }
  691:         }
  692:     }
  693:     foreach (keys %servers) {
  694:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  695:     }
  696: }
  697: 
  698: # --------------------------------------------------- Assign a key to a student
  699: 
  700: sub assign_access_key {
  701: #
  702: # a valid key looks like uname:udom#comments
  703: # comments are being appended
  704: #
  705:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  706:     $kdom=
  707:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  708:     $knum=
  709:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  710:     $cdom=
  711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  712:     $cnum=
  713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  714:     $udom=$env{'user.name'} unless (defined($udom));
  715:     $uname=$env{'user.domain'} unless (defined($uname));
  716:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  717:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  718:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  719:                                                   # assigned to this person
  720:                                                   # - this should not happen,
  721:                                                   # unless something went wrong
  722:                                                   # the first time around
  723: # ready to assign
  724:         $logentry=$1.'; '.$logentry;
  725:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  726:                                                  $kdom,$knum) eq 'ok') {
  727: # key now belongs to user
  728: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  729:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  730:                 &appenv('environment.'.$envkey => $ckey);
  731:                 return 'ok';
  732:             } else {
  733:                 return 
  734:   'error: Count not permanently assign key, will need to be re-entered later.';
  735: 	    }
  736:         } else {
  737:             return 'error: Could not assign key, try again later.';
  738:         }
  739:     } elsif (!$existing{$ckey}) {
  740: # the key does not exist
  741: 	return 'error: The key does not exist';
  742:     } else {
  743: # the key is somebody else's
  744: 	return 'error: The key is already in use';
  745:     }
  746: }
  747: 
  748: # ------------------------------------------ put an additional comment on a key
  749: 
  750: sub comment_access_key {
  751: #
  752: # a valid key looks like uname:udom#comments
  753: # comments are being appended
  754: #
  755:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  756:     $cdom=
  757:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  758:     $cnum=
  759:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  760:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  761:     if ($existing{$ckey}) {
  762:         $existing{$ckey}.='; '.$logentry;
  763: # ready to assign
  764:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  765:                                                  $cdom,$cnum) eq 'ok') {
  766: 	    return 'ok';
  767:         } else {
  768: 	    return 'error: Count not store comment.';
  769:         }
  770:     } else {
  771: # the key does not exist
  772: 	return 'error: The key does not exist';
  773:     }
  774: }
  775: 
  776: # ------------------------------------------------------ Generate a set of keys
  777: 
  778: sub generate_access_keys {
  779:     my ($number,$cdom,$cnum,$logentry)=@_;
  780:     $cdom=
  781:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  782:     $cnum=
  783:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  784:     unless (&allowed('mky',$cdom)) { return 0; }
  785:     unless (($cdom) && ($cnum)) { return 0; }
  786:     if ($number>10000) { return 0; }
  787:     sleep(2); # make sure don't get same seed twice
  788:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  789:     my $total=0;
  790:     for (my $i=1;$i<=$number;$i++) {
  791:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  792:                   sprintf("%lx",int(100000*rand)).'-'.
  793:                   sprintf("%lx",int(100000*rand));
  794:        $newkey=~s/1/g/g; # folks mix up 1 and l
  795:        $newkey=~s/0/h/g; # and also 0 and O
  796:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  797:        if ($existing{$newkey}) {
  798:            $i--;
  799:        } else {
  800: 	  if (&put('accesskeys',
  801:               { $newkey => '# generated '.localtime().
  802:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  803:                            '; '.$logentry },
  804: 		   $cdom,$cnum) eq 'ok') {
  805:               $total++;
  806: 	  }
  807:        }
  808:     }
  809:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  810:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  811:     return $total;
  812: }
  813: 
  814: # ------------------------------------------------------- Validate an accesskey
  815: 
  816: sub validate_access_key {
  817:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  818:     $cdom=
  819:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  820:     $cnum=
  821:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  822:     $udom=$env{'user.domain'} unless (defined($udom));
  823:     $uname=$env{'user.name'} unless (defined($uname));
  824:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  825:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  826: }
  827: 
  828: # ------------------------------------- Find the section of student in a course
  829: sub devalidate_getsection_cache {
  830:     my ($udom,$unam,$courseid)=@_;
  831:     $courseid=~s/\_/\//g;
  832:     $courseid=~s/^(\w)/\/$1/;
  833:     my $hashid="$udom:$unam:$courseid";
  834:     &devalidate_cache_new('getsection',$hashid);
  835: }
  836: 
  837: sub getsection {
  838:     my ($udom,$unam,$courseid)=@_;
  839:     my $cachetime=1800;
  840:     $courseid=~s/\_/\//g;
  841:     $courseid=~s/^(\w)/\/$1/;
  842: 
  843:     my $hashid="$udom:$unam:$courseid";
  844:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  845:     if (defined($cached)) { return $result; }
  846: 
  847:     my %Pending; 
  848:     my %Expired;
  849:     #
  850:     # Each role can either have not started yet (pending), be active, 
  851:     #    or have expired.
  852:     #
  853:     # If there is an active role, we are done.
  854:     #
  855:     # If there is more than one role which has not started yet, 
  856:     #     choose the one which will start sooner
  857:     # If there is one role which has not started yet, return it.
  858:     #
  859:     # If there is more than one expired role, choose the one which ended last.
  860:     # If there is a role which has expired, return it.
  861:     #
  862:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  863:                         &homeserver($unam,$udom)))) {
  864:         my ($key,$value)=split(/\=/,$_);
  865:         $key=&unescape($key);
  866:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  867:         my $section=$1;
  868:         if ($key eq $courseid.'_st') { $section=''; }
  869:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  870:         my $now=time;
  871:         if (defined($end) && $end && ($now > $end)) {
  872:             $Expired{$end}=$section;
  873:             next;
  874:         }
  875:         if (defined($start) && $start && ($now < $start)) {
  876:             $Pending{$start}=$section;
  877:             next;
  878:         }
  879:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  880:     }
  881:     #
  882:     # Presumedly there will be few matching roles from the above
  883:     # loop and the sorting time will be negligible.
  884:     if (scalar(keys(%Pending))) {
  885:         my ($time) = sort {$a <=> $b} keys(%Pending);
  886:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  887:     } 
  888:     if (scalar(keys(%Expired))) {
  889:         my @sorted = sort {$a <=> $b} keys(%Expired);
  890:         my $time = pop(@sorted);
  891:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  892:     }
  893:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  894: }
  895: 
  896: sub save_cache {
  897:     &purge_remembered();
  898:     #&Apache::loncommon::validate_page();
  899:     undef(%env);
  900:     undef($env_loaded);
  901: }
  902: 
  903: my $to_remember=-1;
  904: my %remembered;
  905: my %accessed;
  906: my $kicks=0;
  907: my $hits=0;
  908: sub devalidate_cache_new {
  909:     my ($name,$id,$debug) = @_;
  910:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  911:     $id=&escape($name.':'.$id);
  912:     $memcache->delete($id);
  913:     delete($remembered{$id});
  914:     delete($accessed{$id});
  915: }
  916: 
  917: sub is_cached_new {
  918:     my ($name,$id,$debug) = @_;
  919:     $id=&escape($name.':'.$id);
  920:     if (exists($remembered{$id})) {
  921: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  922: 	$accessed{$id}=[&gettimeofday()];
  923: 	$hits++;
  924: 	return ($remembered{$id},1);
  925:     }
  926:     my $value = $memcache->get($id);
  927:     if (!(defined($value))) {
  928: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  929: 	return (undef,undef);
  930:     }
  931:     if ($value eq '__undef__') {
  932: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  933: 	$value=undef;
  934:     }
  935:     &make_room($id,$value,$debug);
  936:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  937:     return ($value,1);
  938: }
  939: 
  940: sub do_cache_new {
  941:     my ($name,$id,$value,$time,$debug) = @_;
  942:     $id=&escape($name.':'.$id);
  943:     my $setvalue=$value;
  944:     if (!defined($setvalue)) {
  945: 	$setvalue='__undef__';
  946:     }
  947:     if (!defined($time) ) {
  948: 	$time=600;
  949:     }
  950:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  951:     $memcache->set($id,$setvalue,$time);
  952:     # need to make a copy of $value
  953:     #&make_room($id,$value,$debug);
  954:     return $value;
  955: }
  956: 
  957: sub make_room {
  958:     my ($id,$value,$debug)=@_;
  959:     $remembered{$id}=$value;
  960:     if ($to_remember<0) { return; }
  961:     $accessed{$id}=[&gettimeofday()];
  962:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  963:     my $to_kick;
  964:     my $max_time=0;
  965:     foreach my $other (keys(%accessed)) {
  966: 	if (&tv_interval($accessed{$other}) > $max_time) {
  967: 	    $to_kick=$other;
  968: 	    $max_time=&tv_interval($accessed{$other});
  969: 	}
  970:     }
  971:     delete($remembered{$to_kick});
  972:     delete($accessed{$to_kick});
  973:     $kicks++;
  974:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  975:     return;
  976: }
  977: 
  978: sub purge_remembered {
  979:     #&logthis("Tossing ".scalar(keys(%remembered)));
  980:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  981:     undef(%remembered);
  982:     undef(%accessed);
  983: }
  984: # ------------------------------------- Read an entry from a user's environment
  985: 
  986: sub userenvironment {
  987:     my ($udom,$unam,@what)=@_;
  988:     my %returnhash=();
  989:     my @answer=split(/\&/,
  990:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  991:                       &homeserver($unam,$udom)));
  992:     my $i;
  993:     for ($i=0;$i<=$#what;$i++) {
  994: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  995:     }
  996:     return %returnhash;
  997: }
  998: 
  999: # ---------------------------------------------------------- Get a studentphoto
 1000: sub studentphoto {
 1001:     my ($udom,$unam,$ext) = @_;
 1002:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1003:     if (defined($env{'request.course.id'})) {
 1004:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1005:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1006:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1007:             } else {
 1008:                 my ($result,$perm_reqd)=
 1009: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1010:                 if ($result eq 'ok') {
 1011:                     if (!($perm_reqd eq 'yes')) {
 1012:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1013:                     }
 1014:                 }
 1015:             }
 1016:         }
 1017:     } else {
 1018:         my ($result,$perm_reqd) = 
 1019: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1020:         if ($result eq 'ok') {
 1021:             if (!($perm_reqd eq 'yes')) {
 1022:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1023:             }
 1024:         }
 1025:     }
 1026:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1027: }
 1028: 
 1029: sub retrievestudentphoto {
 1030:     my ($udom,$unam,$ext,$type) = @_;
 1031:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1032:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1033:     if ($ret eq 'ok') {
 1034:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1035:         if ($type eq 'thumbnail') {
 1036:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1037:         }
 1038:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1039:         return $tokenurl;
 1040:     } else {
 1041:         if ($type eq 'thumbnail') {
 1042:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1043:         } else { 
 1044:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1045:         }
 1046:     }
 1047: }
 1048: 
 1049: # -------------------------------------------------------------------- New chat
 1050: 
 1051: sub chatsend {
 1052:     my ($newentry,$anon,$group)=@_;
 1053:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1054:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1055:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1056:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1057: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1058: 		   &escape($newentry)).':'.$group,$chome);
 1059: }
 1060: 
 1061: # ------------------------------------------ Find current version of a resource
 1062: 
 1063: sub getversion {
 1064:     my $fname=&clutter(shift);
 1065:     unless ($fname=~/^\/res\//) { return -1; }
 1066:     return &currentversion(&filelocation('',$fname));
 1067: }
 1068: 
 1069: sub currentversion {
 1070:     my $fname=shift;
 1071:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1072:     if (defined($cached)) { return $result; }
 1073:     my $author=$fname;
 1074:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1075:     my ($udom,$uname)=split(/\//,$author);
 1076:     my $home=homeserver($uname,$udom);
 1077:     if ($home eq 'no_host') { 
 1078:         return -1; 
 1079:     }
 1080:     my $answer=reply("currentversion:$fname",$home);
 1081:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1082: 	return -1;
 1083:     }
 1084:     return &do_cache_new('resversion',$fname,$answer,600);
 1085: }
 1086: 
 1087: # ----------------------------- Subscribe to a resource, return URL if possible
 1088: 
 1089: sub subscribe {
 1090:     my $fname=shift;
 1091:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1092:     $fname=~s/[\n\r]//g;
 1093:     my $author=$fname;
 1094:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1095:     my ($udom,$uname)=split(/\//,$author);
 1096:     my $home=homeserver($uname,$udom);
 1097:     if ($home eq 'no_host') {
 1098:         return 'not_found';
 1099:     }
 1100:     my $answer=reply("sub:$fname",$home);
 1101:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1102: 	$answer.=' by '.$home;
 1103:     }
 1104:     return $answer;
 1105: }
 1106:     
 1107: # -------------------------------------------------------------- Replicate file
 1108: 
 1109: sub repcopy {
 1110:     my $filename=shift;
 1111:     $filename=~s/\/+/\//g;
 1112:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1113:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1114:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1115: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1116: 	return &repcopy_userfile($filename);
 1117:     }
 1118:     $filename=~s/[\n\r]//g;
 1119:     my $transname="$filename.in.transfer";
 1120:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1121:     my $remoteurl=subscribe($filename);
 1122:     if ($remoteurl =~ /^con_lost by/) {
 1123: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1124:            return 'unavailable';
 1125:     } elsif ($remoteurl eq 'not_found') {
 1126: 	   #&logthis("Subscribe returned not_found: $filename");
 1127: 	   return 'not_found';
 1128:     } elsif ($remoteurl =~ /^rejected by/) {
 1129: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1130:            return 'forbidden';
 1131:     } elsif ($remoteurl eq 'directory') {
 1132:            return 'ok';
 1133:     } else {
 1134:         my $author=$filename;
 1135:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1136:         my ($udom,$uname)=split(/\//,$author);
 1137:         my $home=homeserver($uname,$udom);
 1138:         unless ($home eq $perlvar{'lonHostID'}) {
 1139:            my @parts=split(/\//,$filename);
 1140:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1141:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1142:                &logthis("Malconfiguration for replication: $filename");
 1143: 	       return 'bad_request';
 1144:            }
 1145:            my $count;
 1146:            for ($count=5;$count<$#parts;$count++) {
 1147:                $path.="/$parts[$count]";
 1148:                if ((-e $path)!=1) {
 1149: 		   mkdir($path,0777);
 1150:                }
 1151:            }
 1152:            my $ua=new LWP::UserAgent;
 1153:            my $request=new HTTP::Request('GET',"$remoteurl");
 1154:            my $response=$ua->request($request,$transname);
 1155:            if ($response->is_error()) {
 1156: 	       unlink($transname);
 1157:                my $message=$response->status_line;
 1158:                &logthis("<font color=\"blue\">WARNING:"
 1159:                        ." LWP get: $message: $filename</font>");
 1160:                return 'unavailable';
 1161:            } else {
 1162: 	       if ($remoteurl!~/\.meta$/) {
 1163:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1164:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1165:                   if ($mresponse->is_error()) {
 1166: 		      unlink($filename.'.meta');
 1167:                       &logthis(
 1168:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1169:                   }
 1170: 	       }
 1171:                rename($transname,$filename);
 1172:                return 'ok';
 1173:            }
 1174:        }
 1175:     }
 1176: }
 1177: 
 1178: # ------------------------------------------------ Get server side include body
 1179: sub ssi_body {
 1180:     my ($filelink,%form)=@_;
 1181:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1182:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1183:     }
 1184:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1185:                                      &ssi($filelink,%form));
 1186:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1187:     $output=~s/^.*?\<body[^\>]*\>//si;
 1188:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1189:     return $output;
 1190: }
 1191: 
 1192: # --------------------------------------------------------- Server Side Include
 1193: 
 1194: sub ssi {
 1195: 
 1196:     my ($fn,%form)=@_;
 1197: 
 1198:     my $ua=new LWP::UserAgent;
 1199:     
 1200:     my $request;
 1201: 
 1202:     $form{'no_update_last_known'}=1;
 1203: 
 1204:     if (%form) {
 1205:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1206:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1207:     } else {
 1208:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1209:     }
 1210: 
 1211:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1212:     my $response=$ua->request($request);
 1213: 
 1214:     return $response->content;
 1215: }
 1216: 
 1217: sub externalssi {
 1218:     my ($url)=@_;
 1219:     my $ua=new LWP::UserAgent;
 1220:     my $request=new HTTP::Request('GET',$url);
 1221:     my $response=$ua->request($request);
 1222:     return $response->content;
 1223: }
 1224: 
 1225: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1226: 
 1227: sub allowuploaded {
 1228:     my ($srcurl,$url)=@_;
 1229:     $url=&clutter(&declutter($url));
 1230:     my $dir=$url;
 1231:     $dir=~s/\/[^\/]+$//;
 1232:     my %httpref=();
 1233:     my $httpurl=&hreflocation('',$url);
 1234:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1235:     &Apache::lonnet::appenv(%httpref);
 1236: }
 1237: 
 1238: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1239: # input: action, courseID, current domain, intended
 1240: #        path to file, source of file, instruction to parse file for objects,
 1241: #        ref to hash for embedded objects,
 1242: #        ref to hash for codebase of java objects.
 1243: #
 1244: # output: url to file (if action was uploaddoc), 
 1245: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1246: #
 1247: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1248: # course.
 1249: #
 1250: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1251: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1252: #          course's home server.
 1253: #
 1254: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1255: #          be copied from $source (current location) to 
 1256: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1257: #         and will then be copied to
 1258: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1259: #         course's home server.
 1260: #
 1261: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1262: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1263: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1264: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1265: #         in course's home server.
 1266: #
 1267: 
 1268: sub process_coursefile {
 1269:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1270:     my $fetchresult;
 1271:     my $home=&homeserver($docuname,$docudom);
 1272:     if ($action eq 'propagate') {
 1273:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1274: 			     $home);
 1275:     } else {
 1276:         my $fpath = '';
 1277:         my $fname = $file;
 1278:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1279:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1280:         my $filepath = &build_filepath($fpath);
 1281:         if ($action eq 'copy') {
 1282:             if ($source eq '') {
 1283:                 $fetchresult = 'no source file';
 1284:                 return $fetchresult;
 1285:             } else {
 1286:                 my $destination = $filepath.'/'.$fname;
 1287:                 rename($source,$destination);
 1288:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1289:                                  $home);
 1290:             }
 1291:         } elsif ($action eq 'uploaddoc') {
 1292:             open(my $fh,'>'.$filepath.'/'.$fname);
 1293:             print $fh $env{'form.'.$source};
 1294:             close($fh);
 1295:             if ($parser eq 'parse') {
 1296:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1297:                 unless ($parse_result eq 'ok') {
 1298:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1299:                 }
 1300:             }
 1301:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1302:                                  $home);
 1303:             if ($fetchresult eq 'ok') {
 1304:                 return '/uploaded/'.$fpath.'/'.$fname;
 1305:             } else {
 1306:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1307:                         ' to host '.$home.': '.$fetchresult);
 1308:                 return '/adm/notfound.html';
 1309:             }
 1310:         }
 1311:     }
 1312:     unless ( $fetchresult eq 'ok') {
 1313:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1314:              ' to host '.$home.': '.$fetchresult);
 1315:     }
 1316:     return $fetchresult;
 1317: }
 1318: 
 1319: sub build_filepath {
 1320:     my ($fpath) = @_;
 1321:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1322:     unless ($fpath eq '') {
 1323:         my @parts=split('/',$fpath);
 1324:         foreach my $part (@parts) {
 1325:             $filepath.= '/'.$part;
 1326:             if ((-e $filepath)!=1) {
 1327:                 mkdir($filepath,0777);
 1328:             }
 1329:         }
 1330:     }
 1331:     return $filepath;
 1332: }
 1333: 
 1334: sub store_edited_file {
 1335:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1336:     my $file = $primary_url;
 1337:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1338:     my $fpath = '';
 1339:     my $fname = $file;
 1340:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1341:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1342:     my $filepath = &build_filepath($fpath);
 1343:     open(my $fh,'>'.$filepath.'/'.$fname);
 1344:     print $fh $content;
 1345:     close($fh);
 1346:     my $home=&homeserver($docuname,$docudom);
 1347:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1348: 			  $home);
 1349:     if ($$fetchresult eq 'ok') {
 1350:         return '/uploaded/'.$fpath.'/'.$fname;
 1351:     } else {
 1352:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1353: 		 ' to host '.$home.': '.$$fetchresult);
 1354:         return '/adm/notfound.html';
 1355:     }
 1356: }
 1357: 
 1358: sub clean_filename {
 1359:     my ($fname)=@_;
 1360: # Replace Windows backslashes by forward slashes
 1361:     $fname=~s/\\/\//g;
 1362: # Get rid of everything but the actual filename
 1363:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1364: # Replace spaces by underscores
 1365:     $fname=~s/\s+/\_/g;
 1366: # Replace all other weird characters by nothing
 1367:     $fname=~s/[^\w\.\-]//g;
 1368: # Replace all .\d. sequences with _\d. so they no longer look like version
 1369: # numbers
 1370:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1371:     return $fname;
 1372: }
 1373: 
 1374: # --------------- Take an uploaded file and put it into the userfiles directory
 1375: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1376: #                    the desired filenam is in $env{"form.$formname.filename"}
 1377: #        $coursedoc - if true up to the current course
 1378: #                     if false
 1379: #        $subdir - directory in userfile to store the file into
 1380: #        $parser, $allfiles, $codebase - unknown
 1381: #
 1382: # output: url of file in userspace, or error: <message> 
 1383: #             or /adm/notfound.html if failure to upload occurse
 1384: 
 1385: 
 1386: sub userfileupload {
 1387:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1388:     if (!defined($subdir)) { $subdir='unknown'; }
 1389:     my $fname=$env{'form.'.$formname.'.filename'};
 1390:     $fname=&clean_filename($fname);
 1391: # See if there is anything left
 1392:     unless ($fname) { return 'error: no uploaded file'; }
 1393:     chop($env{'form.'.$formname});
 1394:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1395:         my $now = time;
 1396:         my $filepath = 'tmp/helprequests/'.$now;
 1397:         my @parts=split(/\//,$filepath);
 1398:         my $fullpath = $perlvar{'lonDaemons'};
 1399:         for (my $i=0;$i<@parts;$i++) {
 1400:             $fullpath .= '/'.$parts[$i];
 1401:             if ((-e $fullpath)!=1) {
 1402:                 mkdir($fullpath,0777);
 1403:             }
 1404:         }
 1405:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1406:         print $fh $env{'form.'.$formname};
 1407:         close($fh);
 1408:         return $fullpath.'/'.$fname;
 1409:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1410:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1411:                        '_'.$env{'user.domain'}.'/pending';
 1412:         my @parts=split(/\//,$filepath);
 1413:         my $fullpath = $perlvar{'lonDaemons'};
 1414:         for (my $i=0;$i<@parts;$i++) {
 1415:             $fullpath .= '/'.$parts[$i];
 1416:             if ((-e $fullpath)!=1) {
 1417:                 mkdir($fullpath,0777);
 1418:             }
 1419:         }
 1420:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1421:         print $fh $env{'form.'.$formname};
 1422:         close($fh);
 1423:         return $fullpath.'/'.$fname;
 1424:     }
 1425:     
 1426: # Create the directory if not present
 1427:     $fname="$subdir/$fname";
 1428:     if ($coursedoc) {
 1429: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1430: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1431:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1432:             return &finishuserfileupload($docuname,$docudom,
 1433: 					 $formname,$fname,$parser,$allfiles,
 1434: 					 $codebase);
 1435:         } else {
 1436:             $fname=$env{'form.folder'}.'/'.$fname;
 1437:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1438: 				       $fname,$formname,$parser,
 1439: 				       $allfiles,$codebase);
 1440:         }
 1441:     } elsif (defined($destuname)) {
 1442:         my $docuname=$destuname;
 1443:         my $docudom=$destudom;
 1444: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1445: 				     $fname,$parser,$allfiles,$codebase);
 1446:         
 1447:     } else {
 1448:         my $docuname=$env{'user.name'};
 1449:         my $docudom=$env{'user.domain'};
 1450:         if (exists($env{'form.group'})) {
 1451:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1452:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1453:         }
 1454: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1455: 				     $fname,$parser,$allfiles,$codebase);
 1456:     }
 1457: }
 1458: 
 1459: sub finishuserfileupload {
 1460:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1461:     my $path=$docudom.'/'.$docuname.'/';
 1462:     my $filepath=$perlvar{'lonDocRoot'};
 1463:     my ($fnamepath,$file);
 1464:     $file=$fname;
 1465:     if ($fname=~m|/|) {
 1466:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1467: 	$path.=$fnamepath.'/';
 1468:     }
 1469:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1470:     my $count;
 1471:     for ($count=4;$count<=$#parts;$count++) {
 1472:         $filepath.="/$parts[$count]";
 1473:         if ((-e $filepath)!=1) {
 1474: 	    mkdir($filepath,0777);
 1475:         }
 1476:     }
 1477: # Save the file
 1478:     {
 1479: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1480: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1481: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1482: 	    return '/adm/notfound.html';
 1483: 	}
 1484: 	if (!print FH ($env{'form.'.$formname})) {
 1485: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1486: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1487: 	    return '/adm/notfound.html';
 1488: 	}
 1489: 	close(FH);
 1490:     }
 1491:     if ($parser eq 'parse') {
 1492:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1493: 						   $codebase);
 1494:         unless ($parse_result eq 'ok') {
 1495:             &logthis('Failed to parse '.$filepath.$file.
 1496: 		     ' for embedded media: '.$parse_result); 
 1497:         }
 1498:     }
 1499: # Notify homeserver to grep it
 1500: #
 1501:     my $docuhome=&homeserver($docuname,$docudom);
 1502:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1503:     if ($fetchresult eq 'ok') {
 1504: #
 1505: # Return the URL to it
 1506:         return '/uploaded/'.$path.$file;
 1507:     } else {
 1508:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1509: 		 ': '.$fetchresult);
 1510:         return '/adm/notfound.html';
 1511:     }    
 1512: }
 1513: 
 1514: sub extract_embedded_items {
 1515:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1516:     my @state = ();
 1517:     my %javafiles = (
 1518:                       codebase => '',
 1519:                       code => '',
 1520:                       archive => ''
 1521:                     );
 1522:     my %mediafiles = (
 1523:                       src => '',
 1524:                       movie => '',
 1525:                      );
 1526:     my $p;
 1527:     if ($content) {
 1528:         $p = HTML::LCParser->new($content);
 1529:     } else {
 1530:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1531:     }
 1532:     while (my $t=$p->get_token()) {
 1533: 	if ($t->[0] eq 'S') {
 1534: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1535: 	    push (@state, $tagname);
 1536:             if (lc($tagname) eq 'allow') {
 1537:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1538:             }
 1539: 	    if (lc($tagname) eq 'img') {
 1540: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1541: 	    }
 1542:             if (lc($tagname) eq 'script') {
 1543:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1544:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1545:                 } else {
 1546:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1547:                 }
 1548:             }
 1549:             if (lc($tagname) eq 'link') {
 1550:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1551:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1552:                 }
 1553:             }
 1554: 	    if (lc($tagname) eq 'object' ||
 1555: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1556: 		foreach my $item (keys(%javafiles)) {
 1557: 		    $javafiles{$item} = '';
 1558: 		}
 1559: 	    }
 1560: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1561: 		my $name = lc($attr->{'name'});
 1562: 		foreach my $item (keys(%javafiles)) {
 1563: 		    if ($name eq $item) {
 1564: 			$javafiles{$item} = $attr->{'value'};
 1565: 			last;
 1566: 		    }
 1567: 		}
 1568: 		foreach my $item (keys(%mediafiles)) {
 1569: 		    if ($name eq $item) {
 1570: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1571: 			last;
 1572: 		    }
 1573: 		}
 1574: 	    }
 1575: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1576: 		foreach my $item (keys(%javafiles)) {
 1577: 		    if ($attr->{$item}) {
 1578: 			$javafiles{$item} = $attr->{$item};
 1579: 			last;
 1580: 		    }
 1581: 		}
 1582: 		foreach my $item (keys(%mediafiles)) {
 1583: 		    if ($attr->{$item}) {
 1584: 			&add_filetype($allfiles,$attr->{$item},$item);
 1585: 			last;
 1586: 		    }
 1587: 		}
 1588: 	    }
 1589: 	} elsif ($t->[0] eq 'E') {
 1590: 	    my ($tagname) = ($t->[1]);
 1591: 	    if ($javafiles{'codebase'} ne '') {
 1592: 		$javafiles{'codebase'} .= '/';
 1593: 	    }  
 1594: 	    if (lc($tagname) eq 'applet' ||
 1595: 		lc($tagname) eq 'object' ||
 1596: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1597: 		) {
 1598: 		foreach my $item (keys(%javafiles)) {
 1599: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1600: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1601: 			&add_filetype($allfiles,$file,$item);
 1602: 		    }
 1603: 		}
 1604: 	    } 
 1605: 	    pop @state;
 1606: 	}
 1607:     }
 1608:     return 'ok';
 1609: }
 1610: 
 1611: sub add_filetype {
 1612:     my ($allfiles,$file,$type)=@_;
 1613:     if (exists($allfiles->{$file})) {
 1614: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1615: 	    push(@{$allfiles->{$file}}, &escape($type));
 1616: 	}
 1617:     } else {
 1618: 	@{$allfiles->{$file}} = (&escape($type));
 1619:     }
 1620: }
 1621: 
 1622: sub removeuploadedurl {
 1623:     my ($url)=@_;
 1624:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1625:     return &removeuserfile($uname,$udom,$fname);
 1626: }
 1627: 
 1628: sub removeuserfile {
 1629:     my ($docuname,$docudom,$fname)=@_;
 1630:     my $home=&homeserver($docuname,$docudom);
 1631:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1632: }
 1633: 
 1634: sub mkdiruserfile {
 1635:     my ($docuname,$docudom,$dir)=@_;
 1636:     my $home=&homeserver($docuname,$docudom);
 1637:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1638: }
 1639: 
 1640: sub renameuserfile {
 1641:     my ($docuname,$docudom,$old,$new)=@_;
 1642:     my $home=&homeserver($docuname,$docudom);
 1643:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1644: 		  &escape("$new"),$home);
 1645: }
 1646: 
 1647: # ------------------------------------------------------------------------- Log
 1648: 
 1649: sub log {
 1650:     my ($dom,$nam,$hom,$what)=@_;
 1651:     return critical("log:$dom:$nam:$what",$hom);
 1652: }
 1653: 
 1654: # ------------------------------------------------------------------ Course Log
 1655: #
 1656: # This routine flushes several buffers of non-mission-critical nature
 1657: #
 1658: 
 1659: sub flushcourselogs {
 1660:     &logthis('Flushing log buffers');
 1661: #
 1662: # course logs
 1663: # This is a log of all transactions in a course, which can be used
 1664: # for data mining purposes
 1665: #
 1666: # It also collects the courseid database, which lists last transaction
 1667: # times and course titles for all courseids
 1668: #
 1669:     my %courseidbuffer=();
 1670:     foreach (keys %courselogs) {
 1671:         my $crsid=$_;
 1672:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1673: 		          &escape($courselogs{$crsid}),
 1674: 		          $coursehombuf{$crsid}) eq 'ok') {
 1675: 	    delete $courselogs{$crsid};
 1676:         } else {
 1677:             &logthis('Failed to flush log buffer for '.$crsid);
 1678:             if (length($courselogs{$crsid})>40000) {
 1679:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1680:                         " exceeded maximum size, deleting.</font>");
 1681:                delete $courselogs{$crsid};
 1682:             }
 1683:         }
 1684:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1685:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1686: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1687:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1688:         } else {
 1689:            $courseidbuffer{$coursehombuf{$crsid}}=
 1690: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1691:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1692:         }
 1693:     }
 1694: #
 1695: # Write course id database (reverse lookup) to homeserver of courses 
 1696: # Is used in pickcourse
 1697: #
 1698:     foreach (keys %courseidbuffer) {
 1699:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1700:     }
 1701: #
 1702: # File accesses
 1703: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1704: #
 1705:     foreach my $entry (keys(%accesshash)) {
 1706:         if ($entry =~ /___count$/) {
 1707:             my ($dom,$name);
 1708:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1709:             if (! defined($dom) || $dom eq '' || 
 1710:                 ! defined($name) || $name eq '') {
 1711:                 my $cid = $env{'request.course.id'};
 1712:                 $dom  = $env{'request.'.$cid.'.domain'};
 1713:                 $name = $env{'request.'.$cid.'.num'};
 1714:             }
 1715:             my $value = $accesshash{$entry};
 1716:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1717:             my %temphash=($url => $value);
 1718:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1719:             if ($result eq 'ok') {
 1720:                 delete $accesshash{$entry};
 1721:             } elsif ($result eq 'unknown_cmd') {
 1722:                 # Target server has old code running on it.
 1723:                 my %temphash=($entry => $value);
 1724:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1725:                     delete $accesshash{$entry};
 1726:                 }
 1727:             }
 1728:         } else {
 1729:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1730:             my %temphash=($entry => $accesshash{$entry});
 1731:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1732:                 delete $accesshash{$entry};
 1733:             }
 1734:         }
 1735:     }
 1736: #
 1737: # Roles
 1738: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1739: #
 1740:     foreach (keys %userrolehash) {
 1741:         my $entry=$_;
 1742:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1743: 	    split(/\:/,$entry);
 1744:         if (&Apache::lonnet::put('nohist_userroles',
 1745:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1746:                 $rudom,$runame) eq 'ok') {
 1747: 	    delete $userrolehash{$entry};
 1748:         }
 1749:     }
 1750: #
 1751: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1752: #
 1753:     my %domrolebuffer = ();
 1754:     foreach my $entry (keys %domainrolehash) {
 1755:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1756:         if ($domrolebuffer{$rudom}) {
 1757:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1758:                       '='.&escape($domainrolehash{$entry});
 1759:         } else {
 1760:             $domrolebuffer{$rudom}.=&escape($entry).
 1761:                       '='.&escape($domainrolehash{$entry});
 1762:         }
 1763:         delete $domainrolehash{$entry};
 1764:     }
 1765:     foreach my $dom (keys(%domrolebuffer)) {
 1766:         foreach my $tryserver (keys %libserv) {
 1767:             if ($hostdom{$tryserver} eq $dom) {
 1768:                 unless (&reply('domroleput:'.$dom.':'.
 1769:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1770:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1771:                 }
 1772:             }
 1773:         }
 1774:     }
 1775:     $dumpcount++;
 1776: }
 1777: 
 1778: sub courselog {
 1779:     my $what=shift;
 1780:     $what=time.':'.$what;
 1781:     unless ($env{'request.course.id'}) { return ''; }
 1782:     $coursedombuf{$env{'request.course.id'}}=
 1783:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1784:     $coursenumbuf{$env{'request.course.id'}}=
 1785:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1786:     $coursehombuf{$env{'request.course.id'}}=
 1787:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1788:     $coursedescrbuf{$env{'request.course.id'}}=
 1789:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1790:     $courseinstcodebuf{$env{'request.course.id'}}=
 1791:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1792:     $courseownerbuf{$env{'request.course.id'}}=
 1793:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1794:     $coursetypebuf{$env{'request.course.id'}}=
 1795:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1796:     if (defined $courselogs{$env{'request.course.id'}}) {
 1797: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1798:     } else {
 1799: 	$courselogs{$env{'request.course.id'}}.=$what;
 1800:     }
 1801:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1802: 	&flushcourselogs();
 1803:     }
 1804: }
 1805: 
 1806: sub courseacclog {
 1807:     my $fnsymb=shift;
 1808:     unless ($env{'request.course.id'}) { return ''; }
 1809:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1810:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1811:         $what.=':POST';
 1812:         # FIXME: Probably ought to escape things....
 1813: 	foreach (keys %env) {
 1814:             if ($_=~/^form\.(.*)/) {
 1815: 		$what.=':'.$1.'='.$env{$_};
 1816:             }
 1817:         }
 1818:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1819:         # FIXME: We should not be depending on a form parameter that someone
 1820:         # editing lonsearchcat.pm might change in the future.
 1821:         if ($env{'form.phase'} eq 'course_search') {
 1822:             $what.= ':POST';
 1823:             # FIXME: Probably ought to escape things....
 1824:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1825:                                  'crsdiscuss') {
 1826:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1827:             }
 1828:         }
 1829:     }
 1830:     &courselog($what);
 1831: }
 1832: 
 1833: sub countacc {
 1834:     my $url=&declutter(shift);
 1835:     return if (! defined($url) || $url eq '');
 1836:     unless ($env{'request.course.id'}) { return ''; }
 1837:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1838:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1839:     $accesshash{$key}++;
 1840: }
 1841: 
 1842: sub linklog {
 1843:     my ($from,$to)=@_;
 1844:     $from=&declutter($from);
 1845:     $to=&declutter($to);
 1846:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1847:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1848: }
 1849:   
 1850: sub userrolelog {
 1851:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1852:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1853:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1854:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1855:         ($trole=~/^ta/)) {
 1856:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1857:        $userrolehash
 1858:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1859:                     =$tend.':'.$tstart;
 1860:     }
 1861:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1862:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1863:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1864:         ($trole=~/^sc/)) {
 1865:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1866:        $domainrolehash
 1867:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1868:                     = $tend.':'.$tstart;
 1869:     }
 1870: }
 1871: 
 1872: sub get_course_adv_roles {
 1873:     my $cid=shift;
 1874:     $cid=$env{'request.course.id'} unless (defined($cid));
 1875:     my %coursehash=&coursedescription($cid);
 1876:     my %nothide=();
 1877:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1878: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1879:     }
 1880:     my %returnhash=();
 1881:     my %dumphash=
 1882:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1883:     my $now=time;
 1884:     foreach (keys %dumphash) {
 1885: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1886:         if (($tstart) && ($tstart<0)) { next; }
 1887:         if (($tend) && ($tend<$now)) { next; }
 1888:         if (($tstart) && ($now<$tstart)) { next; }
 1889:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1890: 	if ($username eq '' || $domain eq '') { next; }
 1891: 	if ((&privileged($username,$domain)) && 
 1892: 	    (!$nothide{$username.':'.$domain})) { next; }
 1893: 	if ($role eq 'cr') { next; }
 1894:         my $key=&plaintext($role);
 1895:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1896:         if ($returnhash{$key}) {
 1897: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1898:         } else {
 1899:             $returnhash{$key}=$username.':'.$domain;
 1900:         }
 1901:      }
 1902:     return %returnhash;
 1903: }
 1904: 
 1905: sub get_my_roles {
 1906:     my ($uname,$udom)=@_;
 1907:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1908:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1909:     my %dumphash=
 1910:             &dump('nohist_userroles',$udom,$uname);
 1911:     my %returnhash=();
 1912:     my $now=time;
 1913:     foreach (keys %dumphash) {
 1914: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1915:         if (($tstart) && ($tstart<0)) { next; }
 1916:         if (($tend) && ($tend<$now)) { next; }
 1917:         if (($tstart) && ($now<$tstart)) { next; }
 1918:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1919: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1920:      }
 1921:     return %returnhash;
 1922: }
 1923: 
 1924: # ----------------------------------------------------- Frontpage Announcements
 1925: #
 1926: #
 1927: 
 1928: sub postannounce {
 1929:     my ($server,$text)=@_;
 1930:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1931:     unless ($text=~/\w/) { $text=''; }
 1932:     return &reply('setannounce:'.&escape($text),$server);
 1933: }
 1934: 
 1935: sub getannounce {
 1936: 
 1937:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1938: 	my $announcement='';
 1939: 	while (<$fh>) { $announcement .=$_; }
 1940: 	close($fh);
 1941: 	if ($announcement=~/\w/) { 
 1942: 	    return 
 1943:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1944:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1945: 	} else {
 1946: 	    return '';
 1947: 	}
 1948:     } else {
 1949: 	return '';
 1950:     }
 1951: }
 1952: 
 1953: # ---------------------------------------------------------- Course ID routines
 1954: # Deal with domain's nohist_courseid.db files
 1955: #
 1956: 
 1957: sub courseidput {
 1958:     my ($domain,$what,$coursehome)=@_;
 1959:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1960: }
 1961: 
 1962: sub courseiddump {
 1963:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
 1964:     my %returnhash=();
 1965:     unless ($domfilter) { $domfilter=''; }
 1966:     foreach my $tryserver (keys %libserv) {
 1967:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1968: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1969: 	        foreach (
 1970:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1971: 			       $sincefilter.':'.&escape($descfilter).':'.
 1972:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
 1973:                                $tryserver))) {
 1974: 		    my ($key,$value)=split(/\=/,$_);
 1975:                     if (($key) && ($value)) {
 1976: 		        $returnhash{&unescape($key)}=$value;
 1977:                     }
 1978:                 }
 1979:             }
 1980:         }
 1981:     }
 1982:     return %returnhash;
 1983: }
 1984: 
 1985: # ---------------------------------------------------------- DC e-mail
 1986: 
 1987: sub dcmailput {
 1988:     my ($domain,$msgid,$message,$server)=@_;
 1989:     my $status = &Apache::lonnet::critical(
 1990:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 1991:        &escape($message),$server);
 1992:     return $status;
 1993: }
 1994: 
 1995: sub dcmaildump {
 1996:     my ($dom,$startdate,$enddate,$senders) = @_;
 1997:     my %returnhash=();
 1998:     if (exists($domain_primary{$dom})) {
 1999:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2000:                                                          &escape($enddate).':';
 2001: 	my @esc_senders=map { &escape($_)} @$senders;
 2002: 	$cmd.=&escape(join('&',@esc_senders));
 2003: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2004:             my ($key,$value) = split(/\=/,$_);
 2005:             if (($key) && ($value)) {
 2006:                 $returnhash{&unescape($key)} = &unescape($value);
 2007:             }
 2008:         }
 2009:     }
 2010:     return %returnhash;
 2011: }
 2012: # ---------------------------------------------------------- Domain roles
 2013: 
 2014: sub get_domain_roles {
 2015:     my ($dom,$roles,$startdate,$enddate)=@_;
 2016:     if (undef($startdate) || $startdate eq '') {
 2017:         $startdate = '.';
 2018:     }
 2019:     if (undef($enddate) || $enddate eq '') {
 2020:         $enddate = '.';
 2021:     }
 2022:     my $rolelist = join(':',@{$roles});
 2023:     my %personnel = ();
 2024:     foreach my $tryserver (keys(%libserv)) {
 2025:         if ($hostdom{$tryserver} eq $dom) {
 2026:             %{$personnel{$tryserver}}=();
 2027:             foreach (
 2028:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2029:                    &escape($startdate).':'.&escape($enddate).':'.
 2030:                    &escape($rolelist), $tryserver))) {
 2031:                 my($key,$value) = split(/\=/,$_);
 2032:                 if (($key) && ($value)) {
 2033:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2034:                 }
 2035:             }
 2036:         }
 2037:     }
 2038:     return %personnel;
 2039: }
 2040: 
 2041: # ----------------------------------------------------------- Check out an item
 2042: 
 2043: sub get_first_access {
 2044:     my ($type,$argsymb)=@_;
 2045:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2046:     if ($argsymb) { $symb=$argsymb; }
 2047:     my ($map,$id,$res)=&decode_symb($symb);
 2048:     if ($type eq 'map') {
 2049: 	$res=&symbread($map);
 2050:     } else {
 2051: 	$res=$symb;
 2052:     }
 2053:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2054:     return $times{"$courseid\0$res"};
 2055: }
 2056: 
 2057: sub set_first_access {
 2058:     my ($type)=@_;
 2059:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2060:     my ($map,$id,$res)=&decode_symb($symb);
 2061:     if ($type eq 'map') {
 2062: 	$res=&symbread($map);
 2063:     } else {
 2064: 	$res=$symb;
 2065:     }
 2066:     my $firstaccess=&get_first_access($type,$symb);
 2067:     if (!$firstaccess) {
 2068: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2069:     }
 2070:     return 'already_set';
 2071: }
 2072: 
 2073: sub checkout {
 2074:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2075:     my $now=time;
 2076:     my $lonhost=$perlvar{'lonHostID'};
 2077:     my $infostr=&escape(
 2078:                  'CHECKOUTTOKEN&'.
 2079:                  $tuname.'&'.
 2080:                  $tudom.'&'.
 2081:                  $tcrsid.'&'.
 2082:                  $symb.'&'.
 2083: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2084:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2085:     if ($token=~/^error\:/) { 
 2086:         &logthis("<font color=\"blue\">WARNING: ".
 2087:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2088:                  "</font>");
 2089:         return ''; 
 2090:     }
 2091: 
 2092:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2093:     $token=~tr/a-z/A-Z/;
 2094: 
 2095:     my %infohash=('resource.0.outtoken' => $token,
 2096:                   'resource.0.checkouttime' => $now,
 2097:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2098: 
 2099:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2100:        return '';
 2101:     } else {
 2102:         &logthis("<font color=\"blue\">WARNING: ".
 2103:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2104:                  "</font>");
 2105:     }    
 2106: 
 2107:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2108:                          &escape('Checkout '.$infostr.' - '.
 2109:                                                  $token)) ne 'ok') {
 2110: 	return '';
 2111:     } else {
 2112:         &logthis("<font color=\"blue\">WARNING: ".
 2113:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2114:                  "</font>");
 2115:     }
 2116:     return $token;
 2117: }
 2118: 
 2119: # ------------------------------------------------------------ Check in an item
 2120: 
 2121: sub checkin {
 2122:     my $token=shift;
 2123:     my $now=time;
 2124:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2125:     $lonhost=~tr/A-Z/a-z/;
 2126:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2127:     $dtoken=~s/\W/\_/g;
 2128:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2129:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2130: 
 2131:     unless (($tuname) && ($tudom)) {
 2132:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2133:         return '';
 2134:     }
 2135:     
 2136:     unless (&allowed('mgr',$tcrsid)) {
 2137:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2138:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2139:         return '';
 2140:     }
 2141: 
 2142:     my %infohash=('resource.0.intoken' => $token,
 2143:                   'resource.0.checkintime' => $now,
 2144:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2145: 
 2146:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2147:        return '';
 2148:     }    
 2149: 
 2150:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2151:                          &escape('Checkin - '.$token)) ne 'ok') {
 2152: 	return '';
 2153:     }
 2154: 
 2155:     return ($symb,$tuname,$tudom,$tcrsid);    
 2156: }
 2157: 
 2158: # --------------------------------------------- Set Expire Date for Spreadsheet
 2159: 
 2160: sub expirespread {
 2161:     my ($uname,$udom,$stype,$usymb)=@_;
 2162:     my $cid=$env{'request.course.id'}; 
 2163:     if ($cid) {
 2164:        my $now=time;
 2165:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2166:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2167:                             $env{'course.'.$cid.'.num'}.
 2168: 	        	    ':nohist_expirationdates:'.
 2169:                             &escape($key).'='.$now,
 2170:                             $env{'course.'.$cid.'.home'})
 2171:     }
 2172:     return 'ok';
 2173: }
 2174: 
 2175: # ----------------------------------------------------- Devalidate Spreadsheets
 2176: 
 2177: sub devalidate {
 2178:     my ($symb,$uname,$udom)=@_;
 2179:     my $cid=$env{'request.course.id'}; 
 2180:     if ($cid) {
 2181:         # delete the stored spreadsheets for
 2182:         # - the student level sheet of this user in course's homespace
 2183:         # - the assessment level sheet for this resource 
 2184:         #   for this user in user's homespace
 2185: 	# - current conditional state info
 2186: 	my $key=$uname.':'.$udom.':';
 2187:         my $status=
 2188: 	    &del('nohist_calculatedsheets',
 2189: 		 [$key.'studentcalc:'],
 2190: 		 $env{'course.'.$cid.'.domain'},
 2191: 		 $env{'course.'.$cid.'.num'})
 2192: 		.' '.
 2193: 	    &del('nohist_calculatedsheets_'.$cid,
 2194: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2195:         unless ($status eq 'ok ok') {
 2196:            &logthis('Could not devalidate spreadsheet '.
 2197:                     $uname.' at '.$udom.' for '.
 2198: 		    $symb.': '.$status);
 2199:         }
 2200: 	&delenv('user.state.'.$cid);
 2201:     }
 2202: }
 2203: 
 2204: sub get_scalar {
 2205:     my ($string,$end) = @_;
 2206:     my $value;
 2207:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2208: 	$value = $1;
 2209:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2210: 	$value = $1;
 2211:     }
 2212:     return &unescape($value);
 2213: }
 2214: 
 2215: sub array2str {
 2216:   my (@array) = @_;
 2217:   my $result=&arrayref2str(\@array);
 2218:   $result=~s/^__ARRAY_REF__//;
 2219:   $result=~s/__END_ARRAY_REF__$//;
 2220:   return $result;
 2221: }
 2222: 
 2223: sub arrayref2str {
 2224:   my ($arrayref) = @_;
 2225:   my $result='__ARRAY_REF__';
 2226:   foreach my $elem (@$arrayref) {
 2227:     if(ref($elem) eq 'ARRAY') {
 2228:       $result.=&arrayref2str($elem).'&';
 2229:     } elsif(ref($elem) eq 'HASH') {
 2230:       $result.=&hashref2str($elem).'&';
 2231:     } elsif(ref($elem)) {
 2232:       #print("Got a ref of ".(ref($elem))." skipping.");
 2233:     } else {
 2234:       $result.=&escape($elem).'&';
 2235:     }
 2236:   }
 2237:   $result=~s/\&$//;
 2238:   $result .= '__END_ARRAY_REF__';
 2239:   return $result;
 2240: }
 2241: 
 2242: sub hash2str {
 2243:   my (%hash) = @_;
 2244:   my $result=&hashref2str(\%hash);
 2245:   $result=~s/^__HASH_REF__//;
 2246:   $result=~s/__END_HASH_REF__$//;
 2247:   return $result;
 2248: }
 2249: 
 2250: sub hashref2str {
 2251:   my ($hashref)=@_;
 2252:   my $result='__HASH_REF__';
 2253:   foreach (sort(keys(%$hashref))) {
 2254:     if (ref($_) eq 'ARRAY') {
 2255:       $result.=&arrayref2str($_).'=';
 2256:     } elsif (ref($_) eq 'HASH') {
 2257:       $result.=&hashref2str($_).'=';
 2258:     } elsif (ref($_)) {
 2259:       $result.='=';
 2260:       #print("Got a ref of ".(ref($_))." skipping.");
 2261:     } else {
 2262: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2263:     }
 2264: 
 2265:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2266:       $result.=&arrayref2str($hashref->{$_}).'&';
 2267:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2268:       $result.=&hashref2str($hashref->{$_}).'&';
 2269:     } elsif(ref($hashref->{$_})) {
 2270:        $result.='&';
 2271:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2272:     } else {
 2273:       $result.=&escape($hashref->{$_}).'&';
 2274:     }
 2275:   }
 2276:   $result=~s/\&$//;
 2277:   $result .= '__END_HASH_REF__';
 2278:   return $result;
 2279: }
 2280: 
 2281: sub str2hash {
 2282:     my ($string)=@_;
 2283:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2284:     return %$hash;
 2285: }
 2286: 
 2287: sub str2hashref {
 2288:   my ($string) = @_;
 2289: 
 2290:   my %hash;
 2291: 
 2292:   if($string !~ /^__HASH_REF__/) {
 2293:       if (! ($string eq '' || !defined($string))) {
 2294: 	  $hash{'error'}='Not hash reference';
 2295:       }
 2296:       return (\%hash, $string);
 2297:   }
 2298: 
 2299:   $string =~ s/^__HASH_REF__//;
 2300: 
 2301:   while($string !~ /^__END_HASH_REF__/) {
 2302:       #key
 2303:       my $key='';
 2304:       if($string =~ /^__HASH_REF__/) {
 2305:           ($key, $string)=&str2hashref($string);
 2306:           if(defined($key->{'error'})) {
 2307:               $hash{'error'}='Bad data';
 2308:               return (\%hash, $string);
 2309:           }
 2310:       } elsif($string =~ /^__ARRAY_REF__/) {
 2311:           ($key, $string)=&str2arrayref($string);
 2312:           if($key->[0] eq 'Array reference error') {
 2313:               $hash{'error'}='Bad data';
 2314:               return (\%hash, $string);
 2315:           }
 2316:       } else {
 2317:           $string =~ s/^(.*?)=//;
 2318: 	  $key=&unescape($1);
 2319:       }
 2320:       $string =~ s/^=//;
 2321: 
 2322:       #value
 2323:       my $value='';
 2324:       if($string =~ /^__HASH_REF__/) {
 2325:           ($value, $string)=&str2hashref($string);
 2326:           if(defined($value->{'error'})) {
 2327:               $hash{'error'}='Bad data';
 2328:               return (\%hash, $string);
 2329:           }
 2330:       } elsif($string =~ /^__ARRAY_REF__/) {
 2331:           ($value, $string)=&str2arrayref($string);
 2332:           if($value->[0] eq 'Array reference error') {
 2333:               $hash{'error'}='Bad data';
 2334:               return (\%hash, $string);
 2335:           }
 2336:       } else {
 2337: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2338:       }
 2339:       $string =~ s/^&//;
 2340: 
 2341:       $hash{$key}=$value;
 2342:   }
 2343: 
 2344:   $string =~ s/^__END_HASH_REF__//;
 2345: 
 2346:   return (\%hash, $string);
 2347: }
 2348: 
 2349: sub str2array {
 2350:     my ($string)=@_;
 2351:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2352:     return @$array;
 2353: }
 2354: 
 2355: sub str2arrayref {
 2356:   my ($string) = @_;
 2357:   my @array;
 2358: 
 2359:   if($string !~ /^__ARRAY_REF__/) {
 2360:       if (! ($string eq '' || !defined($string))) {
 2361: 	  $array[0]='Array reference error';
 2362:       }
 2363:       return (\@array, $string);
 2364:   }
 2365: 
 2366:   $string =~ s/^__ARRAY_REF__//;
 2367: 
 2368:   while($string !~ /^__END_ARRAY_REF__/) {
 2369:       my $value='';
 2370:       if($string =~ /^__HASH_REF__/) {
 2371:           ($value, $string)=&str2hashref($string);
 2372:           if(defined($value->{'error'})) {
 2373:               $array[0] ='Array reference error';
 2374:               return (\@array, $string);
 2375:           }
 2376:       } elsif($string =~ /^__ARRAY_REF__/) {
 2377:           ($value, $string)=&str2arrayref($string);
 2378:           if($value->[0] eq 'Array reference error') {
 2379:               $array[0] ='Array reference error';
 2380:               return (\@array, $string);
 2381:           }
 2382:       } else {
 2383: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2384:       }
 2385:       $string =~ s/^&//;
 2386: 
 2387:       push(@array, $value);
 2388:   }
 2389: 
 2390:   $string =~ s/^__END_ARRAY_REF__//;
 2391: 
 2392:   return (\@array, $string);
 2393: }
 2394: 
 2395: # -------------------------------------------------------------------Temp Store
 2396: 
 2397: sub tmpreset {
 2398:   my ($symb,$namespace,$domain,$stuname) = @_;
 2399:   if (!$symb) {
 2400:     $symb=&symbread();
 2401:     if (!$symb) { $symb= $env{'request.url'}; }
 2402:   }
 2403:   $symb=escape($symb);
 2404: 
 2405:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2406:   $namespace=~s/\//\_/g;
 2407:   $namespace=~s/\W//g;
 2408: 
 2409:   if (!$domain) { $domain=$env{'user.domain'}; }
 2410:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2411:   if ($domain eq 'public' && $stuname eq 'public') {
 2412:       $stuname=$ENV{'REMOTE_ADDR'};
 2413:   }
 2414:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2415:   my %hash;
 2416:   if (tie(%hash,'GDBM_File',
 2417: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2418: 	  &GDBM_WRCREAT(),0640)) {
 2419:     foreach my $key (keys %hash) {
 2420:       if ($key=~ /:$symb/) {
 2421: 	delete($hash{$key});
 2422:       }
 2423:     }
 2424:   }
 2425: }
 2426: 
 2427: sub tmpstore {
 2428:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2429: 
 2430:   if (!$symb) {
 2431:     $symb=&symbread();
 2432:     if (!$symb) { $symb= $env{'request.url'}; }
 2433:   }
 2434:   $symb=escape($symb);
 2435: 
 2436:   if (!$namespace) {
 2437:     # I don't think we would ever want to store this for a course.
 2438:     # it seems this will only be used if we don't have a course.
 2439:     #$namespace=$env{'request.course.id'};
 2440:     #if (!$namespace) {
 2441:       $namespace=$env{'request.state'};
 2442:     #}
 2443:   }
 2444:   $namespace=~s/\//\_/g;
 2445:   $namespace=~s/\W//g;
 2446:   if (!$domain) { $domain=$env{'user.domain'}; }
 2447:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2448:   if ($domain eq 'public' && $stuname eq 'public') {
 2449:       $stuname=$ENV{'REMOTE_ADDR'};
 2450:   }
 2451:   my $now=time;
 2452:   my %hash;
 2453:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2454:   if (tie(%hash,'GDBM_File',
 2455: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2456: 	  &GDBM_WRCREAT(),0640)) {
 2457:     $hash{"version:$symb"}++;
 2458:     my $version=$hash{"version:$symb"};
 2459:     my $allkeys=''; 
 2460:     foreach my $key (keys(%$storehash)) {
 2461:       $allkeys.=$key.':';
 2462:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2463:     }
 2464:     $hash{"$version:$symb:timestamp"}=$now;
 2465:     $allkeys.='timestamp';
 2466:     $hash{"$version:keys:$symb"}=$allkeys;
 2467:     if (untie(%hash)) {
 2468:       return 'ok';
 2469:     } else {
 2470:       return "error:$!";
 2471:     }
 2472:   } else {
 2473:     return "error:$!";
 2474:   }
 2475: }
 2476: 
 2477: # -----------------------------------------------------------------Temp Restore
 2478: 
 2479: sub tmprestore {
 2480:   my ($symb,$namespace,$domain,$stuname) = @_;
 2481: 
 2482:   if (!$symb) {
 2483:     $symb=&symbread();
 2484:     if (!$symb) { $symb= $env{'request.url'}; }
 2485:   }
 2486:   $symb=escape($symb);
 2487: 
 2488:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2489: 
 2490:   if (!$domain) { $domain=$env{'user.domain'}; }
 2491:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2492:   if ($domain eq 'public' && $stuname eq 'public') {
 2493:       $stuname=$ENV{'REMOTE_ADDR'};
 2494:   }
 2495:   my %returnhash;
 2496:   $namespace=~s/\//\_/g;
 2497:   $namespace=~s/\W//g;
 2498:   my %hash;
 2499:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2500:   if (tie(%hash,'GDBM_File',
 2501: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2502: 	  &GDBM_READER(),0640)) {
 2503:     my $version=$hash{"version:$symb"};
 2504:     $returnhash{'version'}=$version;
 2505:     my $scope;
 2506:     for ($scope=1;$scope<=$version;$scope++) {
 2507:       my $vkeys=$hash{"$scope:keys:$symb"};
 2508:       my @keys=split(/:/,$vkeys);
 2509:       my $key;
 2510:       $returnhash{"$scope:keys"}=$vkeys;
 2511:       foreach $key (@keys) {
 2512: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2513: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2514:       }
 2515:     }
 2516:     if (!(untie(%hash))) {
 2517:       return "error:$!";
 2518:     }
 2519:   } else {
 2520:     return "error:$!";
 2521:   }
 2522:   return %returnhash;
 2523: }
 2524: 
 2525: # ----------------------------------------------------------------------- Store
 2526: 
 2527: sub store {
 2528:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2529:     my $home='';
 2530: 
 2531:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2532: 
 2533:     $symb=&symbclean($symb);
 2534:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2535: 
 2536:     if (!$domain) { $domain=$env{'user.domain'}; }
 2537:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2538: 
 2539:     &devalidate($symb,$stuname,$domain);
 2540: 
 2541:     $symb=escape($symb);
 2542:     if (!$namespace) { 
 2543:        unless ($namespace=$env{'request.course.id'}) { 
 2544:           return ''; 
 2545:        } 
 2546:     }
 2547:     if (!$home) { $home=$env{'user.home'}; }
 2548: 
 2549:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2550:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2551: 
 2552:     my $namevalue='';
 2553:     foreach (keys %$storehash) {
 2554:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2555:     }
 2556:     $namevalue=~s/\&$//;
 2557:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2558:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2559: }
 2560: 
 2561: # -------------------------------------------------------------- Critical Store
 2562: 
 2563: sub cstore {
 2564:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2565:     my $home='';
 2566: 
 2567:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2568: 
 2569:     $symb=&symbclean($symb);
 2570:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2571: 
 2572:     if (!$domain) { $domain=$env{'user.domain'}; }
 2573:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2574: 
 2575:     &devalidate($symb,$stuname,$domain);
 2576: 
 2577:     $symb=escape($symb);
 2578:     if (!$namespace) { 
 2579:        unless ($namespace=$env{'request.course.id'}) { 
 2580:           return ''; 
 2581:        } 
 2582:     }
 2583:     if (!$home) { $home=$env{'user.home'}; }
 2584: 
 2585:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2586:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2587: 
 2588:     my $namevalue='';
 2589:     foreach (keys %$storehash) {
 2590:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2591:     }
 2592:     $namevalue=~s/\&$//;
 2593:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2594:     return critical
 2595:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2596: }
 2597: 
 2598: # --------------------------------------------------------------------- Restore
 2599: 
 2600: sub restore {
 2601:     my ($symb,$namespace,$domain,$stuname) = @_;
 2602:     my $home='';
 2603: 
 2604:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2605: 
 2606:     if (!$symb) {
 2607:       unless ($symb=escape(&symbread())) { return ''; }
 2608:     } else {
 2609:       $symb=&escape(&symbclean($symb));
 2610:     }
 2611:     if (!$namespace) { 
 2612:        unless ($namespace=$env{'request.course.id'}) { 
 2613:           return ''; 
 2614:        } 
 2615:     }
 2616:     if (!$domain) { $domain=$env{'user.domain'}; }
 2617:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2618:     if (!$home) { $home=$env{'user.home'}; }
 2619:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2620: 
 2621:     my %returnhash=();
 2622:     foreach (split(/\&/,$answer)) {
 2623: 	my ($name,$value)=split(/\=/,$_);
 2624:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2625:     }
 2626:     my $version;
 2627:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2628:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2629:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2630:        }
 2631:     }
 2632:     return %returnhash;
 2633: }
 2634: 
 2635: # ---------------------------------------------------------- Course Description
 2636: 
 2637: sub coursedescription {
 2638:     my ($courseid,$args)=@_;
 2639:     $courseid=~s/^\///;
 2640:     $courseid=~s/\_/\//g;
 2641:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2642:     my $chome=&homeserver($cnum,$cdomain);
 2643:     my $normalid=$cdomain.'_'.$cnum;
 2644:     # need to always cache even if we get errors otherwise we keep 
 2645:     # trying and trying and trying to get the course description.
 2646:     my %envhash=();
 2647:     my %returnhash=();
 2648:     
 2649:     my $expiretime=600;
 2650:     if ($env{'request.course.id'} eq $normalid) {
 2651: 	$expiretime=120;
 2652:     }
 2653: 
 2654:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2655:     if (!$args->{'freshen_cache'}
 2656: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2657: 	foreach my $key (keys(%env)) {
 2658: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2659: 	    my ($setting) = $1;
 2660: 	    $returnhash{$setting} = $env{$key};
 2661: 	}
 2662: 	return %returnhash;
 2663:     }
 2664: 
 2665:     # get the data agin
 2666:     if (!$args->{'one_time'}) {
 2667: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2668:     }
 2669:     if ($chome ne 'no_host') {
 2670:        %returnhash=&dump('environment',$cdomain,$cnum);
 2671:        if (!exists($returnhash{'con_lost'})) {
 2672:            $returnhash{'home'}= $chome;
 2673: 	   $returnhash{'domain'} = $cdomain;
 2674: 	   $returnhash{'num'} = $cnum;
 2675:            if (!defined($returnhash{'type'})) {
 2676:                $returnhash{'type'} = 'Course';
 2677:            }
 2678:            while (my ($name,$value) = each %returnhash) {
 2679:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2680:            }
 2681:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2682:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2683: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2684:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2685:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2686:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2687:        }
 2688:     }
 2689:     if (!$args->{'one_time'}) {
 2690: 	&appenv(%envhash);
 2691:     }
 2692:     return %returnhash;
 2693: }
 2694: 
 2695: # -------------------------------------------------See if a user is privileged
 2696: 
 2697: sub privileged {
 2698:     my ($username,$domain)=@_;
 2699:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2700: 			&homeserver($username,$domain));
 2701:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2702:     my $now=time;
 2703:     if ($rolesdump ne '') {
 2704:         foreach (split(/&/,$rolesdump)) {
 2705: 	    if ($_!~/^rolesdef_/) {
 2706: 		my ($area,$role)=split(/=/,$_);
 2707: 		$area=~s/\_\w\w$//;
 2708: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2709: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2710: 		    my $active=1;
 2711: 		    if ($tend) {
 2712: 			if ($tend<$now) { $active=0; }
 2713: 		    }
 2714: 		    if ($tstart) {
 2715: 			if ($tstart>$now) { $active=0; }
 2716: 		    }
 2717: 		    if ($active) { return 1; }
 2718: 		}
 2719: 	    }
 2720: 	}
 2721:     }
 2722:     return 0;
 2723: }
 2724: 
 2725: # -------------------------------------------------------- Get user privileges
 2726: 
 2727: sub rolesinit {
 2728:     my ($domain,$username,$authhost)=@_;
 2729:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2730:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2731:     my %allroles=();
 2732:     my %allgroups=();   
 2733:     my $now=time;
 2734:     my %userroles = ('user.login.time' => $now);
 2735:     my $group_privs;
 2736: 
 2737:     if ($rolesdump ne '') {
 2738:         foreach (split(/&/,$rolesdump)) {
 2739: 	  if ($_!~/^rolesdef_/) {
 2740:             my ($area,$role)=split(/=/,$_);
 2741: 	    $area=~s/\_\w\w$//;
 2742:             my ($trole,$tend,$tstart,$group_privs);
 2743: 	    if ($role=~/^cr/) { 
 2744: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2745: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2746: 		    ($tend,$tstart)=split('_',$trest);
 2747: 		} else {
 2748: 		    $trole=$role;
 2749: 		}
 2750:             } elsif ($role =~ m|^gr/|) {
 2751:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2752:                 ($trole,$group_privs) = split(/\//,$trole);
 2753:                 $group_privs = &unescape($group_privs);
 2754: 	    } else {
 2755: 		($trole,$tend,$tstart)=split(/_/,$role);
 2756: 	    }
 2757: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2758: 					 $username);
 2759: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2760:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2761:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2762:             if (($area ne '') && ($trole ne '')) {
 2763: 		my $spec=$trole.'.'.$area;
 2764: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2765: 		if ($trole =~ /^cr\//) {
 2766:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2767:                 } elsif ($trole eq 'gr') {
 2768:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2769: 		} else {
 2770:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2771: 		}
 2772:             }
 2773:           }
 2774:         }
 2775:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2776:         $userroles{'user.adv'}    = $adv;
 2777: 	$userroles{'user.author'} = $author;
 2778:         $env{'user.adv'}=$adv;
 2779:     }
 2780:     return \%userroles;  
 2781: }
 2782: 
 2783: sub set_arearole {
 2784:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2785: # log the associated role with the area
 2786:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2787:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2788: }
 2789: 
 2790: sub custom_roleprivs {
 2791:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2792:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2793:     my $homsvr=homeserver($rauthor,$rdomain);
 2794:     if ($hostname{$homsvr} ne '') {
 2795:         my ($rdummy,$roledef)=
 2796:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2797:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2798:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2799:             if (defined($syspriv)) {
 2800:                 $$allroles{'cm./'}.=':'.$syspriv;
 2801:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2802:             }
 2803:             if ($tdomain ne '') {
 2804:                 if (defined($dompriv)) {
 2805:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2806:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2807:                 }
 2808:                 if (($trest ne '') && (defined($coursepriv))) {
 2809:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2810:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2811:                 }
 2812:             }
 2813:         }
 2814:     }
 2815: }
 2816: 
 2817: sub group_roleprivs {
 2818:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2819:     my $access = 1;
 2820:     my $now = time;
 2821:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2822:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2823:     if ($access) {
 2824:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2825:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2826:     }
 2827: }
 2828: 
 2829: sub standard_roleprivs {
 2830:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2831:     if (defined($pr{$trole.':s'})) {
 2832:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2833:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2834:     }
 2835:     if ($tdomain ne '') {
 2836:         if (defined($pr{$trole.':d'})) {
 2837:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2838:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2839:         }
 2840:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2841:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2842:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2843:         }
 2844:     }
 2845: }
 2846: 
 2847: sub set_userprivs {
 2848:     my ($userroles,$allroles,$allgroups) = @_; 
 2849:     my $author=0;
 2850:     my $adv=0;
 2851:     my %grouproles = ();
 2852:     if (keys(%{$allgroups}) > 0) {
 2853:         foreach my $role (keys %{$allroles}) {
 2854:             my ($trole,$area,$sec,$extendedarea);
 2855:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
 2856:                 $trole = $1;
 2857:                 $area = $2;
 2858:                 $sec = $3;
 2859:                 $extendedarea = $area.$sec;
 2860:                 if (exists($$allgroups{$area})) {
 2861:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2862:                         my $spec = $trole.'.'.$extendedarea;
 2863:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2864:                                                 $$allgroups{$area}{$group};
 2865:                     }
 2866:                 }
 2867:             }
 2868:         }
 2869:     }
 2870:     foreach (keys(%grouproles)) {
 2871:         $$allroles{$_} = $grouproles{$_};
 2872:     }
 2873:     foreach (keys %{$allroles}) {
 2874:         my %thesepriv=();
 2875:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2876:         foreach (split(/:/,$$allroles{$_})) {
 2877:             if ($_ ne '') {
 2878:                 my ($privilege,$restrictions)=split(/&/,$_);
 2879:                 if ($restrictions eq '') {
 2880:                     $thesepriv{$privilege}='F';
 2881:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2882:                     $thesepriv{$privilege}.=$restrictions;
 2883:                 }
 2884:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2885:             }
 2886:         }
 2887:         my $thesestr='';
 2888:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2889:         $userroles->{'user.priv.'.$_} = $thesestr;
 2890:     }
 2891:     return ($author,$adv);
 2892: }
 2893: 
 2894: # --------------------------------------------------------------- get interface
 2895: 
 2896: sub get {
 2897:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2898:    my $items='';
 2899:    foreach (@$storearr) {
 2900:        $items.=escape($_).'&';
 2901:    }
 2902:    $items=~s/\&$//;
 2903:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2904:    if (!$uname) { $uname=$env{'user.name'}; }
 2905:    my $uhome=&homeserver($uname,$udomain);
 2906: 
 2907:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2908:    my @pairs=split(/\&/,$rep);
 2909:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2910:      return @pairs;
 2911:    }
 2912:    my %returnhash=();
 2913:    my $i=0;
 2914:    foreach (@$storearr) {
 2915:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2916:       $i++;
 2917:    }
 2918:    return %returnhash;
 2919: }
 2920: 
 2921: # --------------------------------------------------------------- del interface
 2922: 
 2923: sub del {
 2924:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2925:    my $items='';
 2926:    foreach (@$storearr) {
 2927:        $items.=escape($_).'&';
 2928:    }
 2929:    $items=~s/\&$//;
 2930:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2931:    if (!$uname) { $uname=$env{'user.name'}; }
 2932:    my $uhome=&homeserver($uname,$udomain);
 2933: 
 2934:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2935: }
 2936: 
 2937: # -------------------------------------------------------------- dump interface
 2938: 
 2939: sub dump {
 2940:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2941:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2942:     if (!$uname) { $uname=$env{'user.name'}; }
 2943:     my $uhome=&homeserver($uname,$udomain);
 2944:     if ($regexp) {
 2945: 	$regexp=&escape($regexp);
 2946:     } else {
 2947: 	$regexp='.';
 2948:     }
 2949:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2950:     my @pairs=split(/\&/,$rep);
 2951:     my %returnhash=();
 2952:     foreach my $item (@pairs) {
 2953: 	my ($key,$value)=split(/=/,$item,2);
 2954: 	$key = &unescape($key);
 2955: 	next if ($key =~ /^error: 2 /);
 2956: 	$returnhash{$key}=&thaw_unescape($value);
 2957:     }
 2958:     return %returnhash;
 2959: }
 2960: 
 2961: # --------------------------------------------------------- dumpstore interface
 2962: 
 2963: sub dumpstore {
 2964:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2965:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2966: }
 2967: 
 2968: # -------------------------------------------------------------- keys interface
 2969: 
 2970: sub getkeys {
 2971:    my ($namespace,$udomain,$uname)=@_;
 2972:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2973:    if (!$uname) { $uname=$env{'user.name'}; }
 2974:    my $uhome=&homeserver($uname,$udomain);
 2975:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2976:    my @keyarray=();
 2977:    foreach (split(/\&/,$rep)) {
 2978:       push (@keyarray,&unescape($_));
 2979:    }
 2980:    return @keyarray;
 2981: }
 2982: 
 2983: # --------------------------------------------------------------- currentdump
 2984: sub currentdump {
 2985:    my ($courseid,$sdom,$sname)=@_;
 2986:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2987:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2988:    $sname    = $env{'user.name'}         if (! defined($sname));
 2989:    my $uhome = &homeserver($sname,$sdom);
 2990:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2991:    return if ($rep =~ /^(error:|no_such_host)/);
 2992:    #
 2993:    my %returnhash=();
 2994:    #
 2995:    if ($rep eq "unknown_cmd") { 
 2996:        # an old lond will not know currentdump
 2997:        # Do a dump and make it look like a currentdump
 2998:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2999:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3000:        my %hash = @tmp;
 3001:        @tmp=();
 3002:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3003:    } else {
 3004:        my @pairs=split(/\&/,$rep);
 3005:        foreach (@pairs) {
 3006:            my ($key,$value)=split(/=/,$_);
 3007:            my ($symb,$param) = split(/:/,$key);
 3008:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3009:                                                         &thaw_unescape($value);
 3010:        }
 3011:    }
 3012:    return %returnhash;
 3013: }
 3014: 
 3015: sub convert_dump_to_currentdump{
 3016:     my %hash = %{shift()};
 3017:     my %returnhash;
 3018:     # Code ripped from lond, essentially.  The only difference
 3019:     # here is the unescaping done by lonnet::dump().  Conceivably
 3020:     # we might run in to problems with parameter names =~ /^v\./
 3021:     while (my ($key,$value) = each(%hash)) {
 3022:         my ($v,$symb,$param) = split(/:/,$key);
 3023:         next if ($v eq 'version' || $symb eq 'keys');
 3024:         next if (exists($returnhash{$symb}) &&
 3025:                  exists($returnhash{$symb}->{$param}) &&
 3026:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3027:         $returnhash{$symb}->{$param}=$value;
 3028:         $returnhash{$symb}->{'v.'.$param}=$v;
 3029:     }
 3030:     #
 3031:     # Remove all of the keys in the hashes which keep track of
 3032:     # the version of the parameter.
 3033:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3034:         # use a foreach because we are going to delete from the hash.
 3035:         foreach my $key (keys(%$param_hash)) {
 3036:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3037:         }
 3038:     }
 3039:     return \%returnhash;
 3040: }
 3041: 
 3042: # ------------------------------------------------------ critical inc interface
 3043: 
 3044: sub cinc {
 3045:     return &inc(@_,'critical');
 3046: }
 3047: 
 3048: # --------------------------------------------------------------- inc interface
 3049: 
 3050: sub inc {
 3051:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3052:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3053:     if (!$uname) { $uname=$env{'user.name'}; }
 3054:     my $uhome=&homeserver($uname,$udomain);
 3055:     my $items='';
 3056:     if (! ref($store)) {
 3057:         # got a single value, so use that instead
 3058:         $items = &escape($store).'=&';
 3059:     } elsif (ref($store) eq 'SCALAR') {
 3060:         $items = &escape($$store).'=&';        
 3061:     } elsif (ref($store) eq 'ARRAY') {
 3062:         $items = join('=&',map {&escape($_);} @{$store});
 3063:     } elsif (ref($store) eq 'HASH') {
 3064:         while (my($key,$value) = each(%{$store})) {
 3065:             $items.= &escape($key).'='.&escape($value).'&';
 3066:         }
 3067:     }
 3068:     $items=~s/\&$//;
 3069:     if ($critical) {
 3070: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3071:     } else {
 3072: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3073:     }
 3074: }
 3075: 
 3076: # --------------------------------------------------------------- put interface
 3077: 
 3078: sub put {
 3079:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3081:    if (!$uname) { $uname=$env{'user.name'}; }
 3082:    my $uhome=&homeserver($uname,$udomain);
 3083:    my $items='';
 3084:    foreach (keys %$storehash) {
 3085:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3086:    }
 3087:    $items=~s/\&$//;
 3088:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3089: }
 3090: 
 3091: # ------------------------------------------------------------ newput interface
 3092: 
 3093: sub newput {
 3094:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3096:    if (!$uname) { $uname=$env{'user.name'}; }
 3097:    my $uhome=&homeserver($uname,$udomain);
 3098:    my $items='';
 3099:    foreach my $key (keys(%$storehash)) {
 3100:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3101:    }
 3102:    $items=~s/\&$//;
 3103:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3104: }
 3105: 
 3106: # ---------------------------------------------------------  putstore interface
 3107: 
 3108: sub putstore {
 3109:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3110:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3111:    if (!$uname) { $uname=$env{'user.name'}; }
 3112:    my $uhome=&homeserver($uname,$udomain);
 3113:    my $items='';
 3114:    foreach my $key (keys(%$storehash)) {
 3115:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3116:    }
 3117:    $items=~s/\&$//;
 3118:    my $esc_symb=&escape($symb);
 3119:    my $esc_v=&escape($version);
 3120:    my $reply =
 3121:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3122: 	      $uhome);
 3123:    if ($reply eq 'unknown_cmd') {
 3124:        # gfall back to way things use to be done
 3125:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3126: 			    $uname);
 3127:    }
 3128:    return $reply;
 3129: }
 3130: 
 3131: sub old_putstore {
 3132:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3133:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3134:     if (!$uname) { $uname=$env{'user.name'}; }
 3135:     my $uhome=&homeserver($uname,$udomain);
 3136:     my %newstorehash;
 3137:     foreach (keys %$storehash) {
 3138: 	my $key = $version.':'.&escape($symb).':'.$_;
 3139: 	$newstorehash{$key} = $storehash->{$_};
 3140:     }
 3141:     my $items='';
 3142:     my %allitems = ();
 3143:     foreach (keys %newstorehash) {
 3144: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3145: 	    my $key = $1.':keys:'.$2;
 3146: 	    $allitems{$key} .= $3.':';
 3147: 	}
 3148: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3149:     }
 3150:     foreach (keys %allitems) {
 3151: 	$allitems{$_} =~ s/\:$//;
 3152: 	$items.= $_.'='.$allitems{$_}.'&';
 3153:     }
 3154:     $items=~s/\&$//;
 3155:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3156: }
 3157: 
 3158: # ------------------------------------------------------ critical put interface
 3159: 
 3160: sub cput {
 3161:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3163:    if (!$uname) { $uname=$env{'user.name'}; }
 3164:    my $uhome=&homeserver($uname,$udomain);
 3165:    my $items='';
 3166:    foreach (keys %$storehash) {
 3167:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3168:    }
 3169:    $items=~s/\&$//;
 3170:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3171: }
 3172: 
 3173: # -------------------------------------------------------------- eget interface
 3174: 
 3175: sub eget {
 3176:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3177:    my $items='';
 3178:    foreach (@$storearr) {
 3179:        $items.=escape($_).'&';
 3180:    }
 3181:    $items=~s/\&$//;
 3182:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3183:    if (!$uname) { $uname=$env{'user.name'}; }
 3184:    my $uhome=&homeserver($uname,$udomain);
 3185:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3186:    my @pairs=split(/\&/,$rep);
 3187:    my %returnhash=();
 3188:    my $i=0;
 3189:    foreach (@$storearr) {
 3190:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3191:       $i++;
 3192:    }
 3193:    return %returnhash;
 3194: }
 3195: 
 3196: # ------------------------------------------------------------ tmpput interface
 3197: sub tmpput {
 3198:     my ($storehash,$server)=@_;
 3199:     my $items='';
 3200:     foreach (keys(%$storehash)) {
 3201: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3202:     }
 3203:     $items=~s/\&$//;
 3204:     return &reply("tmpput:$items",$server);
 3205: }
 3206: 
 3207: # ------------------------------------------------------------ tmpget interface
 3208: sub tmpget {
 3209:     my ($token,$server)=@_;
 3210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3211:     my $rep=&reply("tmpget:$token",$server);
 3212:     my %returnhash;
 3213:     foreach my $item (split(/\&/,$rep)) {
 3214: 	my ($key,$value)=split(/=/,$item);
 3215: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3216:     }
 3217:     return %returnhash;
 3218: }
 3219: 
 3220: # ------------------------------------------------------------ tmpget interface
 3221: sub tmpdel {
 3222:     my ($token,$server)=@_;
 3223:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3224:     return &reply("tmpdel:$token",$server);
 3225: }
 3226: 
 3227: # -------------------------------------------------- portfolio access checking
 3228: 
 3229: sub portfolio_access {
 3230:     my ($requrl) = @_;
 3231:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3232:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3233:     if ($result eq 'ok') {
 3234:        return 'F';
 3235:     } elsif ($result =~ /^[^:]+:guest_/) {
 3236:        return 'A';
 3237:     }
 3238:     return '';
 3239: }
 3240: 
 3241: sub get_portfolio_access {
 3242:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3243: 
 3244:     if (!ref($access_hash)) {
 3245: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3246: 	my %access_controls = &get_access_controls($current_perms,$group,
 3247: 						   $file_name);
 3248: 	$access_hash = $access_controls{$file_name};
 3249:     }
 3250: 
 3251:     my ($public,$guest,@domains,@users,@courses,@groups);
 3252:     my $now = time;
 3253:     if (ref($access_hash) eq 'HASH') {
 3254:         foreach my $key (keys(%{$access_hash})) {
 3255:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3256:             if ($start > $now) {
 3257:                 next;
 3258:             }
 3259:             if ($end && $end<$now) {
 3260:                 next;
 3261:             }
 3262:             if ($scope eq 'public') {
 3263:                 $public = $key;
 3264:                 last;
 3265:             } elsif ($scope eq 'guest') {
 3266:                 $guest = $key;
 3267:             } elsif ($scope eq 'domains') {
 3268:                 push(@domains,$key);
 3269:             } elsif ($scope eq 'users') {
 3270:                 push(@users,$key);
 3271:             } elsif ($scope eq 'course') {
 3272:                 push(@courses,$key);
 3273:             } elsif ($scope eq 'group') {
 3274:                 push(@groups,$key);
 3275:             }
 3276:         }
 3277:         if ($public) {
 3278:             return 'ok';
 3279:         }
 3280:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3281:             if ($guest) {
 3282:                 return $guest;
 3283:             }
 3284:         } else {
 3285:             if (@domains > 0) {
 3286:                 foreach my $domkey (@domains) {
 3287:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3288:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3289:                             return 'ok';
 3290:                         }
 3291:                     }
 3292:                 }
 3293:             }
 3294:             if (@users > 0) {
 3295:                 foreach my $userkey (@users) {
 3296:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3297:                         return 'ok';
 3298:                     }
 3299:                 }
 3300:             }
 3301:             my %roleshash;
 3302:             my @courses_and_groups = @courses;
 3303:             push(@courses_and_groups,@groups); 
 3304:             if (@courses_and_groups > 0) {
 3305:                 my (%allgroups,%allroles); 
 3306:                 my ($start,$end,$role,$sec,$group);
 3307:                 foreach my $envkey (%env) {
 3308:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
 3309:                         my $cid = $2.'_'.$3; 
 3310:                         if ($1 eq 'gr') {
 3311:                             $group = $4;
 3312:                             $allgroups{$cid}{$group} = $env{$envkey};
 3313:                         } else {
 3314:                             if ($4 eq '') {
 3315:                                 $sec = 'none';
 3316:                             } else {
 3317:                                 $sec = $4;
 3318:                             }
 3319:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3320:                         }
 3321:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
 3322:                         my $cid = $2.'_'.$3;
 3323:                         if ($4 eq '') {
 3324:                             $sec = 'none';
 3325:                         } else {
 3326:                             $sec = $4;
 3327:                         }
 3328:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3329:                     }
 3330:                 }
 3331:                 if (keys(%allroles) == 0) {
 3332:                     return;
 3333:                 }
 3334:                 foreach my $key (@courses_and_groups) {
 3335:                     my %content = %{$$access_hash{$key}};
 3336:                     my $cnum = $content{'number'};
 3337:                     my $cdom = $content{'domain'};
 3338:                     my $cid = $cdom.'_'.$cnum;
 3339:                     if (!exists($allroles{$cid})) {
 3340:                         next;
 3341:                     }    
 3342:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3343:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3344:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3345:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3346:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3347:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3348:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3349:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3350:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3351:                                         if (grep/^all$/,@sections) {
 3352:                                             return 'ok';
 3353:                                         } else {
 3354:                                             if (grep/^$sec$/,@sections) {
 3355:                                                 return 'ok';
 3356:                                             }
 3357:                                         }
 3358:                                     }
 3359:                                 }
 3360:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3361:                                     if (grep/^none$/,@groups) {
 3362:                                         return 'ok';
 3363:                                     }
 3364:                                 } else {
 3365:                                     if (grep/^all$/,@groups) {
 3366:                                         return 'ok';
 3367:                                     } 
 3368:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3369:                                         if (grep/^$group$/,@groups) {
 3370:                                             return 'ok';
 3371:                                         }
 3372:                                     }
 3373:                                 } 
 3374:                             }
 3375:                         }
 3376:                     }
 3377:                 }
 3378:             }
 3379:             if ($guest) {
 3380:                 return $guest;
 3381:             }
 3382:         }
 3383:     }
 3384:     return;
 3385: }
 3386: 
 3387: sub course_group_datechecker {
 3388:     my ($dates,$now,$status) = @_;
 3389:     my ($start,$end) = split(/\./,$dates);
 3390:     if (!$start && !$end) {
 3391:         return 'ok';
 3392:     }
 3393:     if (grep/^active$/,@{$status}) {
 3394:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3395:             return 'ok';
 3396:         }
 3397:     }
 3398:     if (grep/^previous$/,@{$status}) {
 3399:         if ($end > $now ) {
 3400:             return 'ok';
 3401:         }
 3402:     }
 3403:     if (grep/^future$/,@{$status}) {
 3404:         if ($start > $now) {
 3405:             return 'ok';
 3406:         }
 3407:     }
 3408:     return; 
 3409: }
 3410: 
 3411: sub parse_portfolio_url {
 3412:     my ($url) = @_;
 3413: 
 3414:     my ($type,$udom,$unum,$group,$file_name);
 3415:     
 3416:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
 3417: 	$type = 1;
 3418:         $udom = $1;
 3419:         $unum = $2;
 3420:         $file_name = $3;
 3421:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
 3422: 	$type = 2;
 3423:         $udom = $1;
 3424:         $unum = $2;
 3425:         $group = $3;
 3426:         $file_name = $3.'/'.$4;
 3427:     }
 3428:     if (wantarray) {
 3429: 	return ($type,$udom,$unum,$file_name,$group);
 3430:     }
 3431:     return $type;
 3432: }
 3433: 
 3434: sub is_portfolio_url {
 3435:     my ($url) = @_;
 3436:     return scalar(&parse_portfolio_url($url));
 3437: }
 3438: 
 3439: # ---------------------------------------------- Custom access rule evaluation
 3440: 
 3441: sub customaccess {
 3442:     my ($priv,$uri)=@_;
 3443:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3444:     $urealm=~s/^\W//;
 3445:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3446:     my $access=0;
 3447:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3448: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3449:         if ($role) {
 3450: 	   if ($role ne $urole) { next; }
 3451:         }
 3452:         foreach (split(/\s*\,\s*/,$realm)) {
 3453:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3454:             if ($tdom) {
 3455: 		if ($tdom ne $udom) { next; }
 3456:             }
 3457:             if ($tcrs) {
 3458: 		if ($tcrs ne $ucrs) { next; }
 3459:             }
 3460:             if ($tsec) {
 3461: 		if ($tsec ne $usec) { next; }
 3462:             }
 3463:             $access=($effect eq 'allow');
 3464:             last;
 3465:         }
 3466: 	if ($realm eq '' && $role eq '') {
 3467:             $access=($effect eq 'allow');
 3468: 	}
 3469:     }
 3470:     return $access;
 3471: }
 3472: 
 3473: # ------------------------------------------------- Check for a user privilege
 3474: 
 3475: sub allowed {
 3476:     my ($priv,$uri,$symb)=@_;
 3477:     my $ver_orguri=$uri;
 3478:     $uri=&deversion($uri);
 3479:     my $orguri=$uri;
 3480:     $uri=&declutter($uri);
 3481:     
 3482:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3483: # Free bre access to adm and meta resources
 3484:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3485: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3486: 	&& ($priv eq 'bre')) {
 3487: 	return 'F';
 3488:     }
 3489: 
 3490: # Free bre access to user's own portfolio contents
 3491:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3492:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3493: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3494:         return 'F';
 3495:     }
 3496: 
 3497: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3498:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3499:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3500:         if (exists($env{'request.course.id'})) {
 3501:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3502:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3503:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3504:                 my $courseprivid=$env{'request.course.id'};
 3505:                 $courseprivid=~s/\_/\//;
 3506:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3507:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3508:                     return $1; 
 3509:                 } else {
 3510:                     if ($env{'request.course.sec'}) {
 3511:                         $courseprivid.='/'.$env{'request.course.sec'};
 3512:                     }
 3513:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3514:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3515:                         return $2;
 3516:                     }
 3517:                 }
 3518:             }
 3519:         }
 3520:     }
 3521: 
 3522: # Free bre to public access
 3523: 
 3524:     if ($priv eq 'bre') {
 3525:         my $copyright=&metadata($uri,'copyright');
 3526: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3527:            return 'F'; 
 3528:         }
 3529:         if ($copyright eq 'priv') {
 3530:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3531: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3532: 		return '';
 3533:             }
 3534:         }
 3535:         if ($copyright eq 'domain') {
 3536:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3537: 	    unless (($env{'user.domain'} eq $1) ||
 3538:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3539: 		return '';
 3540:             }
 3541:         }
 3542:         if ($env{'request.role'}=~ /li\.\//) {
 3543:             # Library role, so allow browsing of resources in this domain.
 3544:             return 'F';
 3545:         }
 3546:         if ($copyright eq 'custom') {
 3547: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3548:         }
 3549:     }
 3550:     # Domain coordinator is trying to create a course
 3551:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3552:         # uri is the requested domain in this case.
 3553:         # comparison to 'request.role.domain' shows if the user has selected
 3554:         # a role of dc for the domain in question.
 3555:         return 'F' if ($uri eq $env{'request.role.domain'});
 3556:     }
 3557: 
 3558:     my $thisallowed='';
 3559:     my $statecond=0;
 3560:     my $courseprivid='';
 3561: 
 3562: # Course
 3563: 
 3564:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3565:        $thisallowed.=$1;
 3566:     }
 3567: 
 3568: # Domain
 3569: 
 3570:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3571:        =~/\Q$priv\E\&([^\:]*)/) {
 3572:        $thisallowed.=$1;
 3573:     }
 3574: 
 3575: # Course: uri itself is a course
 3576:     my $courseuri=$uri;
 3577:     $courseuri=~s/\_(\d)/\/$1/;
 3578:     $courseuri=~s/^([^\/])/\/$1/;
 3579: 
 3580:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3581:        =~/\Q$priv\E\&([^\:]*)/) {
 3582:        $thisallowed.=$1;
 3583:     }
 3584: 
 3585: # URI is an uploaded document for this course, default permissions don't matter
 3586: # not allowing 'edit' access (editupload) to uploaded course docs
 3587:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3588: 	$thisallowed='';
 3589:         my ($match)=&is_on_map($uri);
 3590:         if ($match) {
 3591:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3592:                   =~/\Q$priv\E\&([^\:]*)/) {
 3593:                 $thisallowed.=$1;
 3594:             }
 3595:         } else {
 3596:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3597:             if ($refuri) {
 3598:                 if ($refuri =~ m|^/adm/|) {
 3599:                     $thisallowed='F';
 3600:                 } else {
 3601:                     $refuri=&declutter($refuri);
 3602:                     my ($match) = &is_on_map($refuri);
 3603:                     if ($match) {
 3604:                         $thisallowed='F';
 3605:                     }
 3606:                 }
 3607:             }
 3608:         }
 3609:     }
 3610: 
 3611:     if ($priv eq 'bre'
 3612: 	&& $thisallowed ne 'F' 
 3613: 	&& $thisallowed ne '2'
 3614: 	&& &is_portfolio_url($uri)) {
 3615: 	$thisallowed = &portfolio_access($uri);
 3616:     }
 3617:     
 3618: # Full access at system, domain or course-wide level? Exit.
 3619: 
 3620:     if ($thisallowed=~/F/) {
 3621: 	return 'F';
 3622:     }
 3623: 
 3624: # If this is generating or modifying users, exit with special codes
 3625: 
 3626:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3627: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3628: 	    my ($audom,$auname)=split('/',$uri);
 3629: # no author name given, so this just checks on the general right to make a co-author in this domain
 3630: 	    unless ($auname) { return $thisallowed; }
 3631: # an author name is given, so we are about to actually make a co-author for a certain account
 3632: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3633: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3634: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3635: 	}
 3636: 	return $thisallowed;
 3637:     }
 3638: #
 3639: # Gathered so far: system, domain and course wide privileges
 3640: #
 3641: # Course: See if uri or referer is an individual resource that is part of 
 3642: # the course
 3643: 
 3644:     if ($env{'request.course.id'}) {
 3645: 
 3646:        $courseprivid=$env{'request.course.id'};
 3647:        if ($env{'request.course.sec'}) {
 3648:           $courseprivid.='/'.$env{'request.course.sec'};
 3649:        }
 3650:        $courseprivid=~s/\_/\//;
 3651:        my $checkreferer=1;
 3652:        my ($match,$cond)=&is_on_map($uri);
 3653:        if ($match) {
 3654:            $statecond=$cond;
 3655:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3656:                =~/\Q$priv\E\&([^\:]*)/) {
 3657:                $thisallowed.=$1;
 3658:                $checkreferer=0;
 3659:            }
 3660:        }
 3661:        
 3662:        if ($checkreferer) {
 3663: 	  my $refuri=$env{'httpref.'.$orguri};
 3664:             unless ($refuri) {
 3665:                 foreach (keys %env) {
 3666: 		    if ($_=~/^httpref\..*\*/) {
 3667: 			my $pattern=$_;
 3668:                         $pattern=~s/^httpref\.\/res\///;
 3669:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3670:                         $pattern=~s/\//\\\//g;
 3671:                         if ($orguri=~/$pattern/) {
 3672: 			    $refuri=$env{$_};
 3673:                         }
 3674:                     }
 3675:                 }
 3676:             }
 3677: 
 3678:          if ($refuri) { 
 3679: 	  $refuri=&declutter($refuri);
 3680:           my ($match,$cond)=&is_on_map($refuri);
 3681:             if ($match) {
 3682:               my $refstatecond=$cond;
 3683:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3684:                   =~/\Q$priv\E\&([^\:]*)/) {
 3685:                   $thisallowed.=$1;
 3686:                   $uri=$refuri;
 3687:                   $statecond=$refstatecond;
 3688:               }
 3689:           }
 3690:         }
 3691:        }
 3692:    }
 3693: 
 3694: #
 3695: # Gathered now: all privileges that could apply, and condition number
 3696: # 
 3697: #
 3698: # Full or no access?
 3699: #
 3700: 
 3701:     if ($thisallowed=~/F/) {
 3702: 	return 'F';
 3703:     }
 3704: 
 3705:     unless ($thisallowed) {
 3706:         return '';
 3707:     }
 3708: 
 3709: # Restrictions exist, deal with them
 3710: #
 3711: #   C:according to course preferences
 3712: #   R:according to resource settings
 3713: #   L:unless locked
 3714: #   X:according to user session state
 3715: #
 3716: 
 3717: # Possibly locked functionality, check all courses
 3718: # Locks might take effect only after 10 minutes cache expiration for other
 3719: # courses, and 2 minutes for current course
 3720: 
 3721:     my $envkey;
 3722:     if ($thisallowed=~/L/) {
 3723:         foreach $envkey (keys %env) {
 3724:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3725:                my $courseid=$2;
 3726:                my $roleid=$1.'.'.$2;
 3727:                $courseid=~s/^\///;
 3728:                my $expiretime=600;
 3729:                if ($env{'request.role'} eq $roleid) {
 3730: 		  $expiretime=120;
 3731:                }
 3732: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3733:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3734:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3735: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3736:                }
 3737:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3738:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3739: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3740:                        &log($env{'user.domain'},$env{'user.name'},
 3741:                             $env{'user.home'},
 3742:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3743:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3744:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3745: 		       return '';
 3746:                    }
 3747:                }
 3748:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3749:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3750: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3751:                        &log($env{'user.domain'},$env{'user.name'},
 3752:                             $env{'user.home'},
 3753:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3754:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3755:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3756: 		       return '';
 3757:                    }
 3758:                }
 3759: 	   }
 3760:        }
 3761:     }
 3762:    
 3763: #
 3764: # Rest of the restrictions depend on selected course
 3765: #
 3766: 
 3767:     unless ($env{'request.course.id'}) {
 3768: 	if ($thisallowed eq 'A') {
 3769: 	    return 'A';
 3770: 	} else {
 3771: 	    return '1';
 3772: 	}
 3773:     }
 3774: 
 3775: #
 3776: # Now user is definitely in a course
 3777: #
 3778: 
 3779: 
 3780: # Course preferences
 3781: 
 3782:    if ($thisallowed=~/C/) {
 3783:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3784:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3785:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3786: 	   =~/\Q$rolecode\E/) {
 3787: 	   if ($priv ne 'pch') { 
 3788: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3789: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3790: 			$env{'request.course.id'});
 3791: 	   }
 3792:            return '';
 3793:        }
 3794: 
 3795:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3796: 	   =~/\Q$unamedom\E/) {
 3797: 	   if ($priv ne 'pch') { 
 3798: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3799: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3800: 			$env{'request.course.id'});
 3801: 	   }
 3802:            return '';
 3803:        }
 3804:    }
 3805: 
 3806: # Resource preferences
 3807: 
 3808:    if ($thisallowed=~/R/) {
 3809:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3810:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3811: 	   if ($priv ne 'pch') { 
 3812: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3813: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3814: 	   }
 3815: 	   return '';
 3816:        }
 3817:    }
 3818: 
 3819: # Restricted by state or randomout?
 3820: 
 3821:    if ($thisallowed=~/X/) {
 3822:       if ($env{'acc.randomout'}) {
 3823: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3824:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3825:             return ''; 
 3826:          }
 3827:       }
 3828:       if (&condval($statecond)) {
 3829: 	 return '2';
 3830:       } else {
 3831:          return '';
 3832:       }
 3833:    }
 3834: 
 3835:     if ($thisallowed eq 'A') {
 3836: 	return 'A';
 3837:     }
 3838:    return 'F';
 3839: }
 3840: 
 3841: sub split_uri_for_cond {
 3842:     my $uri=&deversion(&declutter(shift));
 3843:     my @uriparts=split(/\//,$uri);
 3844:     my $filename=pop(@uriparts);
 3845:     my $pathname=join('/',@uriparts);
 3846:     return ($pathname,$filename);
 3847: }
 3848: # --------------------------------------------------- Is a resource on the map?
 3849: 
 3850: sub is_on_map {
 3851:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3852:     #Trying to find the conditional for the file
 3853:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3854: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3855:     if ($match) {
 3856: 	return (1,$1);
 3857:     } else {
 3858: 	return (0,0);
 3859:     }
 3860: }
 3861: 
 3862: # --------------------------------------------------------- Get symb from alias
 3863: 
 3864: sub get_symb_from_alias {
 3865:     my $symb=shift;
 3866:     my ($map,$resid,$url)=&decode_symb($symb);
 3867: # Already is a symb
 3868:     if ($url) { return $symb; }
 3869: # Must be an alias
 3870:     my $aliassymb='';
 3871:     my %bighash;
 3872:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3873:                             &GDBM_READER(),0640)) {
 3874:         my $rid=$bighash{'mapalias_'.$symb};
 3875: 	if ($rid) {
 3876: 	    my ($mapid,$resid)=split(/\./,$rid);
 3877: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3878: 				    $resid,$bighash{'src_'.$rid});
 3879: 	}
 3880:         untie %bighash;
 3881:     }
 3882:     return $aliassymb;
 3883: }
 3884: 
 3885: # ----------------------------------------------------------------- Define Role
 3886: 
 3887: sub definerole {
 3888:   if (allowed('mcr','/')) {
 3889:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3890:     foreach (split(':',$sysrole)) {
 3891: 	my ($crole,$cqual)=split(/\&/,$_);
 3892:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3893:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3894: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3895:                return "refused:s:$crole&$cqual"; 
 3896:             }
 3897:         }
 3898:     }
 3899:     foreach (split(':',$domrole)) {
 3900: 	my ($crole,$cqual)=split(/\&/,$_);
 3901:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3902:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3903: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3904:                return "refused:d:$crole&$cqual"; 
 3905:             }
 3906:         }
 3907:     }
 3908:     foreach (split(':',$courole)) {
 3909: 	my ($crole,$cqual)=split(/\&/,$_);
 3910:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3911:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3912: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3913:                return "refused:c:$crole&$cqual"; 
 3914:             }
 3915:         }
 3916:     }
 3917:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3918:                 "$env{'user.domain'}:$env{'user.name'}:".
 3919: 	        "rolesdef_$rolename=".
 3920:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3921:     return reply($command,$env{'user.home'});
 3922:   } else {
 3923:     return 'refused';
 3924:   }
 3925: }
 3926: 
 3927: # ---------------- Make a metadata query against the network of library servers
 3928: 
 3929: sub metadata_query {
 3930:     my ($query,$custom,$customshow,$server_array)=@_;
 3931:     my %rhash;
 3932:     my @server_list = (defined($server_array) ? @$server_array
 3933:                                               : keys(%libserv) );
 3934:     for my $server (@server_list) {
 3935: 	unless ($custom or $customshow) {
 3936: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3937: 	    $rhash{$server}=$reply;
 3938: 	}
 3939: 	else {
 3940: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3941: 			     &escape($custom).':'.&escape($customshow),
 3942: 			     $server);
 3943: 	    $rhash{$server}=$reply;
 3944: 	}
 3945:     }
 3946:     return \%rhash;
 3947: }
 3948: 
 3949: # ----------------------------------------- Send log queries and wait for reply
 3950: 
 3951: sub log_query {
 3952:     my ($uname,$udom,$query,%filters)=@_;
 3953:     my $uhome=&homeserver($uname,$udom);
 3954:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3955:     my $uhost=$hostname{$uhome};
 3956:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3957:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3958:                        $uhome);
 3959:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3960:     return get_query_reply($queryid);
 3961: }
 3962: 
 3963: # ------- Request retrieval of institutional classlists for course(s)
 3964: 
 3965: sub fetch_enrollment_query {
 3966:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3967:     my $homeserver;
 3968:     my $maxtries = 1;
 3969:     if ($context eq 'automated') {
 3970:         $homeserver = $perlvar{'lonHostID'};
 3971:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3972:     } else {
 3973:         $homeserver = &homeserver($cnum,$dom);
 3974:     }
 3975:     my $host=$hostname{$homeserver};
 3976:     my $cmd = '';
 3977:     foreach (keys %{$affiliatesref}) {
 3978:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3979:     }
 3980:     $cmd =~ s/%%$//;
 3981:     $cmd = &escape($cmd);
 3982:     my $query = 'fetchenrollment';
 3983:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3984:     unless ($queryid=~/^\Q$host\E\_/) { 
 3985:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3986:         return 'error: '.$queryid;
 3987:     }
 3988:     my $reply = &get_query_reply($queryid);
 3989:     my $tries = 1;
 3990:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3991:         $reply = &get_query_reply($queryid);
 3992:         $tries ++;
 3993:     }
 3994:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3995:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3996:     } else {
 3997:         my @responses = split/:/,$reply;
 3998:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3999:             foreach (@responses) {
 4000:                 my ($key,$value) = split/=/,$_;
 4001:                 $$replyref{$key} = $value;
 4002:             }
 4003:         } else {
 4004:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4005:             foreach (@responses) {
 4006:                 my ($key,$value) = split/=/,$_;
 4007:                 $$replyref{$key} = $value;
 4008:                 if ($value > 0) {
 4009:                     foreach (@{$$affiliatesref{$key}}) {
 4010:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 4011:                         my $destname = $pathname.'/'.$filename;
 4012:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4013:                         if ($xml_classlist =~ /^error/) {
 4014:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4015:                         } else {
 4016:                             if ( open(FILE,">$destname") ) {
 4017:                                 print FILE &unescape($xml_classlist);
 4018:                                 close(FILE);
 4019:                             } else {
 4020:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4021:                             }
 4022:                         }
 4023:                     }
 4024:                 }
 4025:             }
 4026:         }
 4027:         return 'ok';
 4028:     }
 4029:     return 'error';
 4030: }
 4031: 
 4032: sub get_query_reply {
 4033:     my $queryid=shift;
 4034:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4035:     my $reply='';
 4036:     for (1..100) {
 4037: 	sleep 2;
 4038:         if (-e $replyfile.'.end') {
 4039: 	    if (open(my $fh,$replyfile)) {
 4040:                $reply.=<$fh>;
 4041:                close($fh);
 4042: 	   } else { return 'error: reply_file_error'; }
 4043:            return &unescape($reply);
 4044: 	}
 4045:     }
 4046:     return 'timeout:'.$queryid;
 4047: }
 4048: 
 4049: sub courselog_query {
 4050: #
 4051: # possible filters:
 4052: # url: url or symb
 4053: # username
 4054: # domain
 4055: # action: view, submit, grade
 4056: # start: timestamp
 4057: # end: timestamp
 4058: #
 4059:     my (%filters)=@_;
 4060:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4061:     if ($filters{'url'}) {
 4062: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4063:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4064:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4065:     }
 4066:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4067:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4068:     return &log_query($cname,$cdom,'courselog',%filters);
 4069: }
 4070: 
 4071: sub userlog_query {
 4072:     my ($uname,$udom,%filters)=@_;
 4073:     return &log_query($uname,$udom,'userlog',%filters);
 4074: }
 4075: 
 4076: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4077: 
 4078: sub auto_run {
 4079:     my ($cnum,$cdom) = @_;
 4080:     my $homeserver = &homeserver($cnum,$cdom);
 4081:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4082:     return $response;
 4083: }
 4084: 
 4085: sub auto_get_sections {
 4086:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4087:     my $homeserver = &homeserver($cnum,$cdom);
 4088:     my @secs = ();
 4089:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4090:     unless ($response eq 'refused') {
 4091:         @secs = split/:/,$response;
 4092:     }
 4093:     return @secs;
 4094: }
 4095: 
 4096: sub auto_new_course {
 4097:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4098:     my $homeserver = &homeserver($cnum,$cdom);
 4099:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4100:     return $response;
 4101: }
 4102: 
 4103: sub auto_validate_courseID {
 4104:     my ($cnum,$cdom,$inst_course_id) = @_;
 4105:     my $homeserver = &homeserver($cnum,$cdom);
 4106:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4107:     return $response;
 4108: }
 4109: 
 4110: sub auto_create_password {
 4111:     my ($cnum,$cdom,$authparam) = @_;
 4112:     my $homeserver = &homeserver($cnum,$cdom); 
 4113:     my $create_passwd = 0;
 4114:     my $authchk = '';
 4115:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4116:     if ($response eq 'refused') {
 4117:         $authchk = 'refused';
 4118:     } else {
 4119:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4120:     }
 4121:     return ($authparam,$create_passwd,$authchk);
 4122: }
 4123: 
 4124: sub auto_photo_permission {
 4125:     my ($cnum,$cdom,$students) = @_;
 4126:     my $homeserver = &homeserver($cnum,$cdom);
 4127:     my ($outcome,$perm_reqd,$conditions) = 
 4128: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4129:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4130: 	return (undef,undef);
 4131:     }
 4132:     return ($outcome,$perm_reqd,$conditions);
 4133: }
 4134: 
 4135: sub auto_checkphotos {
 4136:     my ($uname,$udom,$pid) = @_;
 4137:     my $homeserver = &homeserver($uname,$udom);
 4138:     my ($result,$resulttype);
 4139:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4140: 				   &escape($uname).':'.&escape($pid),
 4141: 				   $homeserver));
 4142:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4143: 	return (undef,undef);
 4144:     }
 4145:     if ($outcome) {
 4146:         ($result,$resulttype) = split(/:/,$outcome);
 4147:     } 
 4148:     return ($result,$resulttype);
 4149: }
 4150: 
 4151: sub auto_photochoice {
 4152:     my ($cnum,$cdom) = @_;
 4153:     my $homeserver = &homeserver($cnum,$cdom);
 4154:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4155: 						       &escape($cdom),
 4156: 						       $homeserver)));
 4157:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4158: 	return (undef,undef);
 4159:     }
 4160:     return ($update,$comment);
 4161: }
 4162: 
 4163: sub auto_photoupdate {
 4164:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4165:     my $homeserver = &homeserver($cnum,$dom);
 4166:     my $host=$hostname{$homeserver};
 4167:     my $cmd = '';
 4168:     my $maxtries = 1;
 4169:     foreach (keys %{$affiliatesref}) {
 4170:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 4171:     }
 4172:     $cmd =~ s/%%$//;
 4173:     $cmd = &escape($cmd);
 4174:     my $query = 'institutionalphotos';
 4175:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4176:     unless ($queryid=~/^\Q$host\E\_/) {
 4177:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4178:         return 'error: '.$queryid;
 4179:     }
 4180:     my $reply = &get_query_reply($queryid);
 4181:     my $tries = 1;
 4182:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4183:         $reply = &get_query_reply($queryid);
 4184:         $tries ++;
 4185:     }
 4186:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4187:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4188:     } else {
 4189:         my @responses = split(/:/,$reply);
 4190:         my $outcome = shift(@responses); 
 4191:         foreach my $item (@responses) {
 4192:             my ($key,$value) = split(/=/,$item);
 4193:             $$photo{$key} = $value;
 4194:         }
 4195:         return $outcome;
 4196:     }
 4197:     return 'error';
 4198: }
 4199: 
 4200: sub auto_instcode_format {
 4201:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 4202:     my $courses = '';
 4203:     my @homeservers;
 4204:     if ($caller eq 'global') {
 4205:         foreach my $tryserver (keys %libserv) {
 4206:             if ($hostdom{$tryserver} eq $codedom) {
 4207:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
 4208:                     push(@homeservers,$tryserver);
 4209:                 }
 4210:             }
 4211:         }
 4212:     } else {
 4213:         push(@homeservers,&homeserver($caller,$codedom));
 4214:     }
 4215:     foreach (keys %{$instcodes}) {
 4216:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 4217:     }
 4218:     chop($courses);
 4219:     my $ok_response = 0;
 4220:     my $response;
 4221:     while (@homeservers > 0 && $ok_response == 0) {
 4222:         my $server = shift(@homeservers); 
 4223:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4224:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4225:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4226:                                                             split/:/,$response;
 4227:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4228:             push(@{$codetitles},&str2array($codetitles_str));
 4229:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4230:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4231:             $ok_response = 1;
 4232:         }
 4233:     }
 4234:     if ($ok_response) {
 4235:         return 'ok';
 4236:     } else {
 4237:         return $response;
 4238:     }
 4239: }
 4240: 
 4241: sub auto_validate_class_sec {
 4242:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4243:     my $homeserver = &homeserver($cnum,$cdom);
 4244:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4245:                         &escape($owner).':'.$cdom,$homeserver);
 4246:     return $response;
 4247: }
 4248: 
 4249: # ------------------------------------------------------- Course Group routines
 4250: 
 4251: sub get_coursegroups {
 4252:     my ($cdom,$cnum,$group) = @_;
 4253:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4254: }
 4255: 
 4256: sub modify_coursegroup {
 4257:     my ($cdom,$cnum,$groupsettings) = @_;
 4258:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4259: }
 4260: 
 4261: sub modify_group_roles {
 4262:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4263:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4264:     my $role = 'gr/'.&escape($userprivs);
 4265:     my ($uname,$udom) = split(/:/,$user);
 4266:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4267:     if ($result eq 'ok') {
 4268:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4269:     }
 4270:     return $result;
 4271: }
 4272: 
 4273: sub modify_coursegroup_membership {
 4274:     my ($cdom,$cnum,$membership) = @_;
 4275:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4276:     return $result;
 4277: }
 4278: 
 4279: sub get_active_groups {
 4280:     my ($udom,$uname,$cdom,$cnum) = @_;
 4281:     my $now = time;
 4282:     my %groups = ();
 4283:     foreach my $key (keys(%env)) {
 4284:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4285:             my ($start,$end) = split(/\./,$env{$key});
 4286:             if (($end!=0) && ($end<$now)) { next; }
 4287:             if (($start!=0) && ($start>$now)) { next; }
 4288:             if ($1 eq $cdom && $2 eq $cnum) {
 4289:                 $groups{$3} = $env{$key} ;
 4290:             }
 4291:         }
 4292:     }
 4293:     return %groups;
 4294: }
 4295: 
 4296: sub get_group_membership {
 4297:     my ($cdom,$cnum,$group) = @_;
 4298:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4299: }
 4300: 
 4301: sub get_users_groups {
 4302:     my ($udom,$uname,$courseid) = @_;
 4303:     my @usersgroups;
 4304:     my $cachetime=1800;
 4305:     $courseid=~s/\_/\//g;
 4306:     $courseid=~s/^(\w)/\/$1/;
 4307: 
 4308:     my $hashid="$udom:$uname:$courseid";
 4309:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4310:     if (defined($cached)) {
 4311:         @usersgroups = split(/:/,$grouplist);
 4312:     } else {  
 4313:         $grouplist = '';
 4314:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4315:         my ($tmp) = keys(%roleshash);
 4316:         if ($tmp=~/^error:/) {
 4317:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4318:         } else {
 4319:             my $access_end = $env{'course.'.$courseid.
 4320:                                   '.default_enrollment_end_date'};
 4321:             my $now = time;
 4322:             foreach my $key (keys(%roleshash)) {
 4323:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4324:                     my $group = $1;
 4325:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4326:                         my $start = $2;
 4327:                         my $end = $1;
 4328:                         if ($start == -1) { next; } # deleted from group
 4329:                         if (($start!=0) && ($start>$now)) { next; }
 4330:                         if (($end!=0) && ($end<$now)) {
 4331:                             if ($access_end && $access_end < $now) {
 4332:                                 if ($access_end - $end < 86400) {
 4333:                                     push(@usersgroups,$group);
 4334:                                 }
 4335:                             }
 4336:                             next;
 4337:                         }
 4338:                         push(@usersgroups,$group);
 4339:                     }
 4340:                 }
 4341:             }
 4342:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4343:             $grouplist = join(':',@usersgroups);
 4344:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4345:         }
 4346:     }
 4347:     return @usersgroups;
 4348: }
 4349: 
 4350: sub devalidate_getgroups_cache {
 4351:     my ($udom,$uname,$cdom,$cnum)=@_;
 4352:     my $courseid = $cdom.'_'.$cnum;
 4353:     $courseid=~s/\_/\//g;
 4354:     $courseid=~s/^(\w)/\/$1/;
 4355:     my $hashid="$udom:$uname:$courseid";
 4356:     &devalidate_cache_new('getgroups',$hashid);
 4357: }
 4358: 
 4359: # ------------------------------------------------------------------ Plain Text
 4360: 
 4361: sub plaintext {
 4362:     my ($short,$type,$cid) = @_;
 4363:     if ($short =~ /^cr/) {
 4364: 	return (split('/',$short))[-1];
 4365:     }
 4366:     if (!defined($cid)) {
 4367:         $cid = $env{'request.course.id'};
 4368:     }
 4369:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4370:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4371:                                           '.plaintext'});
 4372:     }
 4373:     my %rolenames = (
 4374:                       Course => 'std',
 4375:                       Group => 'alt1',
 4376:                     );
 4377:     if (defined($type) && 
 4378:          defined($rolenames{$type}) && 
 4379:          defined($prp{$short}{$rolenames{$type}})) {
 4380:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4381:     } else {
 4382:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4383:     }
 4384: }
 4385: 
 4386: # ----------------------------------------------------------------- Assign Role
 4387: 
 4388: sub assignrole {
 4389:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4390:     my $mrole;
 4391:     if ($role =~ /^cr\//) {
 4392:         my $cwosec=$url;
 4393:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4394: 	unless (&allowed('ccr',$cwosec)) {
 4395:            &logthis('Refused custom assignrole: '.
 4396:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4397: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4398:            return 'refused'; 
 4399:         }
 4400:         $mrole='cr';
 4401:     } elsif ($role =~ /^gr\//) {
 4402:         my $cwogrp=$url;
 4403:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4404:         unless (&allowed('mdg',$cwogrp)) {
 4405:             &logthis('Refused group assignrole: '.
 4406:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4407:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4408:             return 'refused';
 4409:         }
 4410:         $mrole='gr';
 4411:     } else {
 4412:         my $cwosec=$url;
 4413:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4414:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4415:            &logthis('Refused assignrole: '.
 4416:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4417: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4418:            return 'refused'; 
 4419:         }
 4420:         $mrole=$role;
 4421:     }
 4422:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4423:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4424:     if ($end) { $command.='_'.$end; }
 4425:     if ($start) {
 4426: 	if ($end) { 
 4427:            $command.='_'.$start; 
 4428:         } else {
 4429:            $command.='_0_'.$start;
 4430:         }
 4431:     }
 4432:     my $origstart = $start;
 4433:     my $origend = $end;
 4434: # actually delete
 4435:     if ($deleteflag) {
 4436: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4437: # modify command to delete the role
 4438:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4439:                 "$udom:$uname:$url".'_'."$mrole";
 4440: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4441: # set start and finish to negative values for userrolelog
 4442:            $start=-1;
 4443:            $end=-1;
 4444:         }
 4445:     }
 4446: # send command
 4447:     my $answer=&reply($command,&homeserver($uname,$udom));
 4448: # log new user role if status is ok
 4449:     if ($answer eq 'ok') {
 4450: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4451: # for course roles, perform group memberships changes triggered by role change.
 4452:         unless ($role =~ /^gr/) {
 4453:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4454:                                              $origstart);
 4455:         }
 4456:     }
 4457:     return $answer;
 4458: }
 4459: 
 4460: # -------------------------------------------------- Modify user authentication
 4461: # Overrides without validation
 4462: 
 4463: sub modifyuserauth {
 4464:     my ($udom,$uname,$umode,$upass)=@_;
 4465:     my $uhome=&homeserver($uname,$udom);
 4466:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4467:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4468:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4469:              ' in domain '.$env{'request.role.domain'});  
 4470:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4471: 		     &escape($upass),$uhome);
 4472:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4473:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4474:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4475:     &log($udom,,$uname,$uhome,
 4476:         'Authentication changed by '.$env{'user.domain'}.', '.
 4477:                                      $env{'user.name'}.', '.$umode.
 4478:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4479:     unless ($reply eq 'ok') {
 4480:         &logthis('Authentication mode error: '.$reply);
 4481: 	return 'error: '.$reply;
 4482:     }   
 4483:     return 'ok';
 4484: }
 4485: 
 4486: # --------------------------------------------------------------- Modify a user
 4487: 
 4488: sub modifyuser {
 4489:     my ($udom,    $uname, $uid,
 4490:         $umode,   $upass, $first,
 4491:         $middle,  $last,  $gene,
 4492:         $forceid, $desiredhome, $email)=@_;
 4493:     $udom=~s/\W//g;
 4494:     $uname=~s/\W//g;
 4495:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4496:              $umode.', '.$first.', '.$middle.', '.
 4497: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4498:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4499:                                      ' desiredhome not specified'). 
 4500:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4501:              ' in domain '.$env{'request.role.domain'});
 4502:     my $uhome=&homeserver($uname,$udom,'true');
 4503: # ----------------------------------------------------------------- Create User
 4504:     if (($uhome eq 'no_host') && 
 4505: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4506:         my $unhome='';
 4507:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4508:             $unhome = $desiredhome;
 4509: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4510: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4511:         } else { # load balancing routine for determining $unhome
 4512:             my $tryserver;
 4513:             my $loadm=10000000;
 4514:             foreach $tryserver (keys %libserv) {
 4515: 	       if ($hostdom{$tryserver} eq $udom) {
 4516:                   my $answer=reply('load',$tryserver);
 4517:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4518: 		      $loadm=$answer;
 4519:                       $unhome=$tryserver;
 4520:                   }
 4521: 	       }
 4522: 	    }
 4523:         }
 4524:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4525: 	    return 'error: unable to find a home server for '.$uname.
 4526:                    ' in domain '.$udom;
 4527:         }
 4528:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4529:                          &escape($upass),$unhome);
 4530: 	unless ($reply eq 'ok') {
 4531:             return 'error: '.$reply;
 4532:         }   
 4533:         $uhome=&homeserver($uname,$udom,'true');
 4534:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4535: 	    return 'error: unable verify users home machine.';
 4536:         }
 4537:     }   # End of creation of new user
 4538: # ---------------------------------------------------------------------- Add ID
 4539:     if ($uid) {
 4540:        $uid=~tr/A-Z/a-z/;
 4541:        my %uidhash=&idrget($udom,$uname);
 4542:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4543:          && (!$forceid)) {
 4544: 	  unless ($uid eq $uidhash{$uname}) {
 4545: 	      return 'error: user id "'.$uid.'" does not match '.
 4546:                   'current user id "'.$uidhash{$uname}.'".';
 4547:           }
 4548:        } else {
 4549: 	  &idput($udom,($uname => $uid));
 4550:        }
 4551:     }
 4552: # -------------------------------------------------------------- Add names, etc
 4553:     my @tmp=&get('environment',
 4554: 		   ['firstname','middlename','lastname','generation'],
 4555: 		   $udom,$uname);
 4556:     my %names;
 4557:     if ($tmp[0] =~ m/^error:.*/) { 
 4558:         %names=(); 
 4559:     } else {
 4560:         %names = @tmp;
 4561:     }
 4562: #
 4563: # Make sure to not trash student environment if instructor does not bother
 4564: # to supply name and email information
 4565: #
 4566:     if ($first)  { $names{'firstname'}  = $first; }
 4567:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4568:     if ($last)   { $names{'lastname'}   = $last; }
 4569:     if (defined($gene))   { $names{'generation'} = $gene; }
 4570:     if ($email) {
 4571:        $email=~s/[^\w\@\.\-\,]//gs;
 4572:        if ($email=~/\@/) { $names{'notification'} = $email;
 4573: 			   $names{'critnotification'} = $email;
 4574: 			   $names{'permanentemail'} = $email; }
 4575:     }
 4576:     my $reply = &put('environment', \%names, $udom,$uname);
 4577:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4578:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4579:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4580:              $umode.', '.$first.', '.$middle.', '.
 4581: 	     $last.', '.$gene.' by '.
 4582:              $env{'user.name'}.' at '.$env{'user.domain'});
 4583:     return 'ok';
 4584: }
 4585: 
 4586: # -------------------------------------------------------------- Modify student
 4587: 
 4588: sub modifystudent {
 4589:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4590:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4591:     if (!$cid) {
 4592: 	unless ($cid=$env{'request.course.id'}) {
 4593: 	    return 'not_in_class';
 4594: 	}
 4595:     }
 4596: # --------------------------------------------------------------- Make the user
 4597:     my $reply=&modifyuser
 4598: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4599:          $desiredhome,$email);
 4600:     unless ($reply eq 'ok') { return $reply; }
 4601:     # This will cause &modify_student_enrollment to get the uid from the
 4602:     # students environment
 4603:     $uid = undef if (!$forceid);
 4604:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4605: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4606:     return $reply;
 4607: }
 4608: 
 4609: sub modify_student_enrollment {
 4610:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4611:     my ($cdom,$cnum,$chome);
 4612:     if (!$cid) {
 4613: 	unless ($cid=$env{'request.course.id'}) {
 4614: 	    return 'not_in_class';
 4615: 	}
 4616: 	$cdom=$env{'course.'.$cid.'.domain'};
 4617: 	$cnum=$env{'course.'.$cid.'.num'};
 4618:     } else {
 4619: 	($cdom,$cnum)=split(/_/,$cid);
 4620:     }
 4621:     $chome=$env{'course.'.$cid.'.home'};
 4622:     if (!$chome) {
 4623: 	$chome=&homeserver($cnum,$cdom);
 4624:     }
 4625:     if (!$chome) { return 'unknown_course'; }
 4626:     # Make sure the user exists
 4627:     my $uhome=&homeserver($uname,$udom);
 4628:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4629: 	return 'error: no such user';
 4630:     }
 4631:     # Get student data if we were not given enough information
 4632:     if (!defined($first)  || $first  eq '' || 
 4633:         !defined($last)   || $last   eq '' || 
 4634:         !defined($uid)    || $uid    eq '' || 
 4635:         !defined($middle) || $middle eq '' || 
 4636:         !defined($gene)   || $gene   eq '') {
 4637:         # They did not supply us with enough data to enroll the student, so
 4638:         # we need to pick up more information.
 4639:         my %tmp = &get('environment',
 4640:                        ['firstname','middlename','lastname', 'generation','id']
 4641:                        ,$udom,$uname);
 4642: 
 4643:         #foreach (keys(%tmp)) {
 4644:         #    &logthis("key $_ = ".$tmp{$_});
 4645:         #}
 4646:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4647:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4648:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4649:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4650:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4651:     }
 4652:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4653:     my $reply=cput('classlist',
 4654: 		   {"$uname:$udom" => 
 4655: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4656: 		   $cdom,$cnum);
 4657:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4658: 	return 'error: '.$reply;
 4659:     } else {
 4660: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4661:     }
 4662:     # Add student role to user
 4663:     my $uurl='/'.$cid;
 4664:     $uurl=~s/\_/\//g;
 4665:     if ($usec) {
 4666: 	$uurl.='/'.$usec;
 4667:     }
 4668:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4669: }
 4670: 
 4671: sub format_name {
 4672:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4673:     my $name;
 4674:     if ($first ne 'lastname') {
 4675: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4676:     } else {
 4677: 	if ($lastname=~/\S/) {
 4678: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4679: 	    $name=~s/\s+,/,/;
 4680: 	} else {
 4681: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4682: 	}
 4683:     }
 4684:     $name=~s/^\s+//;
 4685:     $name=~s/\s+$//;
 4686:     $name=~s/\s+/ /g;
 4687:     return $name;
 4688: }
 4689: 
 4690: # ------------------------------------------------- Write to course preferences
 4691: 
 4692: sub writecoursepref {
 4693:     my ($courseid,%prefs)=@_;
 4694:     $courseid=~s/^\///;
 4695:     $courseid=~s/\_/\//g;
 4696:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4697:     my $chome=homeserver($cnum,$cdomain);
 4698:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4699: 	return 'error: no such course';
 4700:     }
 4701:     my $cstring='';
 4702:     foreach (keys %prefs) {
 4703: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4704:     }
 4705:     $cstring=~s/\&$//;
 4706:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4707: }
 4708: 
 4709: # ---------------------------------------------------------- Make/modify course
 4710: 
 4711: sub createcourse {
 4712:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4713:         $course_owner,$crstype)=@_;
 4714:     $url=&declutter($url);
 4715:     my $cid='';
 4716:     unless (&allowed('ccc',$udom)) {
 4717:         return 'refused';
 4718:     }
 4719: # ------------------------------------------------------------------- Create ID
 4720:    my $uname=int(1+rand(9)).
 4721:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4722:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4723:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4724: # ----------------------------------------------- Make sure that does not exist
 4725:    my $uhome=&homeserver($uname,$udom,'true');
 4726:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4727:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4728:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4729:        $uhome=&homeserver($uname,$udom,'true');       
 4730:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4731:            return 'error: unable to generate unique course-ID';
 4732:        } 
 4733:    }
 4734: # ------------------------------------------------ Check supplied server name
 4735:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4736:     if (! exists($libserv{$course_server})) {
 4737:         return 'error:bad server name '.$course_server;
 4738:     }
 4739: # ------------------------------------------------------------- Make the course
 4740:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4741:                       $course_server);
 4742:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4743:     $uhome=&homeserver($uname,$udom,'true');
 4744:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4745: 	return 'error: no such course';
 4746:     }
 4747: # ----------------------------------------------------------------- Course made
 4748: # log existence
 4749:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4750:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4751:                   &escape($crstype),$uhome);
 4752:     &flushcourselogs();
 4753: # set toplevel url
 4754:     my $topurl=$url;
 4755:     unless ($nonstandard) {
 4756: # ------------------------------------------ For standard courses, make top url
 4757:         my $mapurl=&clutter($url);
 4758:         if ($mapurl eq '/res/') { $mapurl=''; }
 4759:         $env{'form.initmap'}=(<<ENDINITMAP);
 4760: <map>
 4761: <resource id="1" type="start"></resource>
 4762: <resource id="2" src="$mapurl"></resource>
 4763: <resource id="3" type="finish"></resource>
 4764: <link index="1" from="1" to="2"></link>
 4765: <link index="2" from="2" to="3"></link>
 4766: </map>
 4767: ENDINITMAP
 4768:         $topurl=&declutter(
 4769:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4770:                           );
 4771:     }
 4772: # ----------------------------------------------------------- Write preferences
 4773:     &writecoursepref($udom.'_'.$uname,
 4774:                      ('description' => $description,
 4775:                       'url'         => $topurl));
 4776:     return '/'.$udom.'/'.$uname;
 4777: }
 4778: 
 4779: # ---------------------------------------------------------- Assign Custom Role
 4780: 
 4781: sub assigncustomrole {
 4782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4783:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4784:                        $end,$start,$deleteflag);
 4785: }
 4786: 
 4787: # ----------------------------------------------------------------- Revoke Role
 4788: 
 4789: sub revokerole {
 4790:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4791:     my $now=time;
 4792:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4793: }
 4794: 
 4795: # ---------------------------------------------------------- Revoke Custom Role
 4796: 
 4797: sub revokecustomrole {
 4798:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4799:     my $now=time;
 4800:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4801:            $deleteflag);
 4802: }
 4803: 
 4804: # ------------------------------------------------------------ Disk usage
 4805: sub diskusage {
 4806:     my ($udom,$uname,$directoryRoot)=@_;
 4807:     $directoryRoot =~ s/\/$//;
 4808:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4809:     return $listing;
 4810: }
 4811: 
 4812: sub is_locked {
 4813:     my ($file_name, $domain, $user) = @_;
 4814:     my @check;
 4815:     my $is_locked;
 4816:     push @check, $file_name;
 4817:     my %locked = &get('file_permissions',\@check,
 4818: 		      $env{'user.domain'},$env{'user.name'});
 4819:     my ($tmp)=keys(%locked);
 4820:     if ($tmp=~/^error:/) { undef(%locked); }
 4821:     
 4822:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4823:         $is_locked = 'false';
 4824:         foreach my $entry (@{$locked{$file_name}}) {
 4825:            if (ref($entry) eq 'ARRAY') { 
 4826:                $is_locked = 'true';
 4827:                last;
 4828:            }
 4829:        }
 4830:     } else {
 4831:         $is_locked = 'false';
 4832:     }
 4833: }
 4834: 
 4835: sub declutter_portfile {
 4836:     my ($file) = @_;
 4837:     &logthis("got $file");
 4838:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 4839:     &logthis("ret $file");
 4840:     return $file;
 4841: }
 4842: 
 4843: # ------------------------------------------------------------- Mark as Read Only
 4844: 
 4845: sub mark_as_readonly {
 4846:     my ($domain,$user,$files,$what) = @_;
 4847:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4848:     my ($tmp)=keys(%current_permissions);
 4849:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4850:     foreach my $file (@{$files}) {
 4851: 	$file = &declutter_portfile($file);
 4852:         push(@{$current_permissions{$file}},$what);
 4853:     }
 4854:     &put('file_permissions',\%current_permissions,$domain,$user);
 4855:     return;
 4856: }
 4857: 
 4858: # ------------------------------------------------------------Save Selected Files
 4859: 
 4860: sub save_selected_files {
 4861:     my ($user, $path, @files) = @_;
 4862:     my $filename = $user."savedfiles";
 4863:     my @other_files = &files_not_in_path($user, $path);
 4864:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4865:     foreach my $file (@files) {
 4866:         print (OUT $env{'form.currentpath'}.$file."\n");
 4867:     }
 4868:     foreach my $file (@other_files) {
 4869:         print (OUT $file."\n");
 4870:     }
 4871:     close (OUT);
 4872:     return 'ok';
 4873: }
 4874: 
 4875: sub clear_selected_files {
 4876:     my ($user) = @_;
 4877:     my $filename = $user."savedfiles";
 4878:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4879:     print (OUT undef);
 4880:     close (OUT);
 4881:     return ("ok");    
 4882: }
 4883: 
 4884: sub files_in_path {
 4885:     my ($user, $path) = @_;
 4886:     my $filename = $user."savedfiles";
 4887:     my %return_files;
 4888:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4889:     while (my $line_in = <IN>) {
 4890:         chomp ($line_in);
 4891:         my @paths_and_file = split (m!/!, $line_in);
 4892:         my $file_part = pop (@paths_and_file);
 4893:         my $path_part = join ('/', @paths_and_file);
 4894:         $path_part.='/';
 4895:         my $path_and_file = $path_part.$file_part;
 4896:         if ($path_part eq $path) {
 4897:             $return_files{$file_part}= 'selected';
 4898:         }
 4899:     }
 4900:     close (IN);
 4901:     return (\%return_files);
 4902: }
 4903: 
 4904: # called in portfolio select mode, to show files selected NOT in current directory
 4905: sub files_not_in_path {
 4906:     my ($user, $path) = @_;
 4907:     my $filename = $user."savedfiles";
 4908:     my @return_files;
 4909:     my $path_part;
 4910:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4911:     while (<IN>) {
 4912:         #ok, I know it's clunky, but I want it to work
 4913:         my @paths_and_file = split m!/!, $_;
 4914:         my $file_part = pop (@paths_and_file);
 4915:         chomp ($file_part);
 4916:         my $path_part = join ('/', @paths_and_file);
 4917:         $path_part .= '/';
 4918:         my $path_and_file = $path_part.$file_part;
 4919:         if ($path_part ne $path) {
 4920:             push (@return_files, ($path_and_file));
 4921:         }
 4922:     }
 4923:     close (OUT);
 4924:     return (@return_files);
 4925: }
 4926: 
 4927: #----------------------------------------------Get portfolio file permissions
 4928: 
 4929: sub get_portfile_permissions {
 4930:     my ($domain,$user) = @_;
 4931:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4932:     my ($tmp)=keys(%current_permissions);
 4933:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4934:     return \%current_permissions;
 4935: }
 4936: 
 4937: #---------------------------------------------Get portfolio file access controls
 4938: 
 4939: sub get_access_controls {
 4940:     my ($current_permissions,$group,$file) = @_;
 4941:     my %access;
 4942:     my $real_file = $file;
 4943:     $file =~ s/\.meta$//;
 4944:     if (defined($file)) {
 4945:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 4946:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 4947:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 4948:             }
 4949:         }
 4950:     } else {
 4951:         foreach my $key (keys(%{$current_permissions})) {
 4952:             if ($key =~ /\0accesscontrol$/) {
 4953:                 if (defined($group)) {
 4954:                     if ($key !~ m-^\Q$group\E/-) {
 4955:                         next;
 4956:                     }
 4957:                 }
 4958:                 my ($fullpath) = split(/\0/,$key);
 4959:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 4960:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 4961:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 4962:                     }
 4963:                 }
 4964:             }
 4965:         }
 4966:     }
 4967:     return %access;
 4968: }
 4969: 
 4970: sub modify_access_controls {
 4971:     my ($file_name,$changes,$domain,$user)=@_;
 4972:     my ($outcome,$deloutcome);
 4973:     my %store_permissions;
 4974:     my %new_values;
 4975:     my %new_control;
 4976:     my %translation;
 4977:     my @deletions = ();
 4978:     my $now = time;
 4979:     if (exists($$changes{'activate'})) {
 4980:         if (ref($$changes{'activate'}) eq 'HASH') {
 4981:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 4982:             my $numnew = scalar(@newitems);
 4983:             for (my $i=0; $i<$numnew; $i++) {
 4984:                 my $newkey = $newitems[$i];
 4985:                 my $newid = &Apache::loncommon::get_cgi_id();
 4986:                 $newkey =~ s/^(\d+)/$newid/;
 4987:                 $translation{$1} = $newid;
 4988:                 $new_values{$file_name."\0".$newkey} = 
 4989:                                           $$changes{'activate'}{$newitems[$i]};
 4990:                 $new_control{$newkey} = $now;
 4991:             }
 4992:         }
 4993:     }
 4994:     my %todelete;
 4995:     my %changed_items;
 4996:     foreach my $action ('delete','update') {
 4997:         if (exists($$changes{$action})) {
 4998:             if (ref($$changes{$action}) eq 'HASH') {
 4999:                 foreach my $key (keys(%{$$changes{$action}})) {
 5000:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5001:                     if ($action eq 'delete') { 
 5002:                         $todelete{$itemnum} = 1;
 5003:                     } else {
 5004:                         $changed_items{$itemnum} = $key;
 5005:                     }
 5006:                 }
 5007:             }
 5008:         }
 5009:     }
 5010:     # get lock on access controls for file.
 5011:     my $lockhash = {
 5012:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5013:                                                        ':'.$env{'user.domain'},
 5014:                    }; 
 5015:     my $tries = 0;
 5016:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5017:    
 5018:     while (($gotlock ne 'ok') && $tries <3) {
 5019:         $tries ++;
 5020:         sleep 1;
 5021:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5022:     }
 5023:     if ($gotlock eq 'ok') {
 5024:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5025:         my ($tmp)=keys(%curr_permissions);
 5026:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5027:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5028:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5029:             if (ref($curr_controls) eq 'HASH') {
 5030:                 foreach my $control_item (keys(%{$curr_controls})) {
 5031:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5032:                     if (defined($todelete{$itemnum})) {
 5033:                         push(@deletions,$file_name."\0".$control_item);
 5034:                     } else {
 5035:                         if (defined($changed_items{$itemnum})) {
 5036:                             $new_control{$changed_items{$itemnum}} = $now;
 5037:                             push(@deletions,$file_name."\0".$control_item);
 5038:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5039:                         } else {
 5040:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5041:                         }
 5042:                     }
 5043:                 }
 5044:             }
 5045:         }
 5046:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5047:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5048:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5049:         #  remove lock
 5050:         my @del_lock = ($file_name."\0".'locked_access_records');
 5051:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5052:     } else {
 5053:         $outcome = "error: could not obtain lockfile\n";  
 5054:     }
 5055:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5056: }
 5057: 
 5058: #------------------------------------------------------Get Marked as Read Only
 5059: 
 5060: sub get_marked_as_readonly {
 5061:     my ($domain,$user,$what,$group) = @_;
 5062:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5063:     my @readonly_files;
 5064:     my $cmp1=$what;
 5065:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5066:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5067:         if (defined($group)) {
 5068:             if ($file_name !~ m-^\Q$group\E/-) {
 5069:                 next;
 5070:             }
 5071:         }
 5072:         if (ref($value) eq "ARRAY"){
 5073:             foreach my $stored_what (@{$value}) {
 5074:                 my $cmp2=$stored_what;
 5075:                 if (ref($stored_what) eq 'ARRAY') {
 5076:                     $cmp2=join('',@{$stored_what});
 5077:                 }
 5078:                 if ($cmp1 eq $cmp2) {
 5079:                     push(@readonly_files, $file_name);
 5080:                     last;
 5081:                 } elsif (!defined($what)) {
 5082:                     push(@readonly_files, $file_name);
 5083:                     last;
 5084:                 }
 5085:             }
 5086:         }
 5087:     }
 5088:     return @readonly_files;
 5089: }
 5090: #-----------------------------------------------------------Get Marked as Read Only Hash
 5091: 
 5092: sub get_marked_as_readonly_hash {
 5093:     my ($current_permissions,$group,$what) = @_;
 5094:     my %readonly_files;
 5095:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5096:         if (defined($group)) {
 5097:             if ($file_name !~ m-^\Q$group\E/-) {
 5098:                 next;
 5099:             }
 5100:         }
 5101:         if (ref($value) eq "ARRAY"){
 5102:             foreach my $stored_what (@{$value}) {
 5103:                 if (ref($stored_what) eq 'ARRAY') {
 5104:                     foreach my $lock_descriptor(@{$stored_what}) {
 5105:                         if ($lock_descriptor eq 'graded') {
 5106:                             $readonly_files{$file_name} = 'graded';
 5107:                         } elsif ($lock_descriptor eq 'handback') {
 5108:                             $readonly_files{$file_name} = 'handback';
 5109:                         } else {
 5110:                             if (!exists($readonly_files{$file_name})) {
 5111:                                 $readonly_files{$file_name} = 'locked';
 5112:                             }
 5113:                         }
 5114:                     }
 5115:                 } 
 5116:             }
 5117:         } 
 5118:     }
 5119:     return %readonly_files;
 5120: }
 5121: # ------------------------------------------------------------ Unmark as Read Only
 5122: 
 5123: sub unmark_as_readonly {
 5124:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5125:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5126:     my ($domain,$user,$what,$file_name,$group) = @_;
 5127:     $file_name = &declutter_portfile($file_name);
 5128:     my $symb_crs = $what;
 5129:     if (ref($what)) { $symb_crs=join('',@$what); }
 5130:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5131:     my ($tmp)=keys(%current_permissions);
 5132:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5133:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5134:     foreach my $file (@readonly_files) {
 5135: 	my $clean_file = &declutter_portfile($file);
 5136: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5137: 	my $current_locks = $current_permissions{$file};
 5138:         my @new_locks;
 5139:         my @del_keys;
 5140:         if (ref($current_locks) eq "ARRAY"){
 5141:             foreach my $locker (@{$current_locks}) {
 5142:                 my $compare=$locker;
 5143:                 if (ref($locker) eq 'ARRAY') {
 5144:                     $compare=join('',@{$locker});
 5145:                     if ($compare ne $symb_crs) {
 5146:                         push(@new_locks, $locker);
 5147:                     }
 5148:                 }
 5149:             }
 5150:             if (scalar(@new_locks) > 0) {
 5151:                 $current_permissions{$file} = \@new_locks;
 5152:             } else {
 5153:                 push(@del_keys, $file);
 5154:                 &del('file_permissions',\@del_keys, $domain, $user);
 5155:                 delete($current_permissions{$file});
 5156:             }
 5157:         }
 5158:     }
 5159:     &put('file_permissions',\%current_permissions,$domain,$user);
 5160:     return;
 5161: }
 5162: 
 5163: # ------------------------------------------------------------ Directory lister
 5164: 
 5165: sub dirlist {
 5166:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5167: 
 5168:     $uri=~s/^\///;
 5169:     $uri=~s/\/$//;
 5170:     my ($udom, $uname);
 5171:     (undef,$udom,$uname)=split(/\//,$uri);
 5172:     if(defined($userdomain)) {
 5173:         $udom = $userdomain;
 5174:     }
 5175:     if(defined($username)) {
 5176:         $uname = $username;
 5177:     }
 5178: 
 5179:     my $dirRoot = $perlvar{'lonDocRoot'};
 5180:     if(defined($alternateDirectoryRoot)) {
 5181:         $dirRoot = $alternateDirectoryRoot;
 5182:         $dirRoot =~ s/\/$//;
 5183:     }
 5184: 
 5185:     if($udom) {
 5186:         if($uname) {
 5187:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 5188:                               homeserver($uname,$udom));
 5189:             my @listing_results;
 5190:             if ($listing eq 'unknown_cmd') {
 5191:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 5192:                                homeserver($uname,$udom));
 5193:                 @listing_results = split(/:/,$listing);
 5194:             } else {
 5195:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5196:             }
 5197:             return @listing_results;
 5198:         } elsif(!defined($alternateDirectoryRoot)) {
 5199:             my $tryserver;
 5200:             my %allusers=();
 5201:             foreach $tryserver (keys %libserv) {
 5202:                 if($hostdom{$tryserver} eq $udom) {
 5203:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5204:                                       $udom, $tryserver);
 5205:                     my @listing_results;
 5206:                     if ($listing eq 'unknown_cmd') {
 5207:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5208:                                        $udom, $tryserver);
 5209:                         @listing_results = split(/:/,$listing);
 5210:                     } else {
 5211:                         @listing_results =
 5212:                             map { &unescape($_); } split(/:/,$listing);
 5213:                     }
 5214:                     if ($listing_results[0] ne 'no_such_dir' && 
 5215:                         $listing_results[0] ne 'empty'       &&
 5216:                         $listing_results[0] ne 'con_lost') {
 5217:                         foreach (@listing_results) {
 5218:                             my ($entry,@stat)=split(/&/,$_);
 5219:                             $allusers{$entry}=1;
 5220:                         }
 5221:                     }
 5222:                 }
 5223:             }
 5224:             my $alluserstr='';
 5225:             foreach (sort keys %allusers) {
 5226:                 $alluserstr.=$_.'&user:';
 5227:             }
 5228:             $alluserstr=~s/:$//;
 5229:             return split(/:/,$alluserstr);
 5230:         } else {
 5231:             my @emptyResults = ();
 5232:             push(@emptyResults, 'missing user name');
 5233:             return split(':',@emptyResults);
 5234:         }
 5235:     } elsif(!defined($alternateDirectoryRoot)) {
 5236:         my $tryserver;
 5237:         my %alldom=();
 5238:         foreach $tryserver (keys %libserv) {
 5239:             $alldom{$hostdom{$tryserver}}=1;
 5240:         }
 5241:         my $alldomstr='';
 5242:         foreach (sort keys %alldom) {
 5243:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 5244:         }
 5245:         $alldomstr=~s/:$//;
 5246:         return split(/:/,$alldomstr);       
 5247:     } else {
 5248:         my @emptyResults = ();
 5249:         push(@emptyResults, 'missing domain');
 5250:         return split(':',@emptyResults);
 5251:     }
 5252: }
 5253: 
 5254: # --------------------------------------------- GetFileTimestamp
 5255: # This function utilizes dirlist and returns the date stamp for
 5256: # when it was last modified.  It will also return an error of -1
 5257: # if an error occurs
 5258: 
 5259: ##
 5260: ## FIXME: This subroutine assumes its caller knows something about the
 5261: ## directory structure of the home server for the student ($root).
 5262: ## Not a good assumption to make.  Since this is for looking up files
 5263: ## in user directories, the full path should be constructed by lond, not
 5264: ## whatever machine we request data from.
 5265: ##
 5266: sub GetFileTimestamp {
 5267:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5268:     $studentDomain=~s/\W//g;
 5269:     $studentName=~s/\W//g;
 5270:     my $subdir=$studentName.'__';
 5271:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5272:     my $proname="$studentDomain/$subdir/$studentName";
 5273:     $proname .= '/'.$filename;
 5274:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5275:                                               $studentName, $root);
 5276:     my @stats = split('&', $fileStat);
 5277:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5278:         # @stats contains first the filename, then the stat output
 5279:         return $stats[10]; # so this is 10 instead of 9.
 5280:     } else {
 5281:         return -1;
 5282:     }
 5283: }
 5284: 
 5285: sub stat_file {
 5286:     my ($uri) = @_;
 5287:     $uri = &clutter($uri);
 5288: 
 5289:     # we want just the url part without the unneeded accessor url bits
 5290:     if ($uri =~ m-^/adm/-) {
 5291: 	$uri=~s-^/adm/wrapper/-/-;
 5292: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 5293:     }
 5294:     my ($udom,$uname,$file,$dir);
 5295:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5296: 	($udom,$uname,$file) =
 5297: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5298: 	$file = 'userfiles/'.$file;
 5299: 	$dir = &propath($udom,$uname);
 5300:     }
 5301:     if ($uri =~ m-^/res/-) {
 5302: 	($udom,$uname) = 
 5303: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5304: 	$file = $uri;
 5305:     }
 5306: 
 5307:     if (!$udom || !$uname || !$file) {
 5308: 	# unable to handle the uri
 5309: 	return ();
 5310:     }
 5311: 
 5312:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5313:     my @stats = split('&', $result);
 5314:     
 5315:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5316: 	shift(@stats); #filename is first
 5317: 	return @stats;
 5318:     }
 5319:     return ();
 5320: }
 5321: 
 5322: # -------------------------------------------------------- Value of a Condition
 5323: 
 5324: # gets the value of a specific preevaluated condition
 5325: #    stored in the string  $env{user.state.<cid>}
 5326: # or looks up a condition reference in the bighash and if if hasn't
 5327: # already been evaluated recurses into docondval to get the value of
 5328: # the condition, then memoizing it to 
 5329: #   $env{user.state.<cid>.<condition>}
 5330: sub directcondval {
 5331:     my $number=shift;
 5332:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5333: 	&Apache::lonuserstate::evalstate();
 5334:     }
 5335:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5336: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5337:     } elsif ($number =~ /^_/) {
 5338: 	my $sub_condition;
 5339: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5340: 		&GDBM_READER(),0640)) {
 5341: 	    $sub_condition=$bighash{'conditions'.$number};
 5342: 	    untie(%bighash);
 5343: 	}
 5344: 	my $value = &docondval($sub_condition);
 5345: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5346: 	return $value;
 5347:     }
 5348:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5349:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5350:     } else {
 5351:        return 2;
 5352:     }
 5353: }
 5354: 
 5355: # get the collection of conditions for this resource
 5356: sub condval {
 5357:     my $condidx=shift;
 5358:     my $allpathcond='';
 5359:     foreach my $cond (split(/\|/,$condidx)) {
 5360: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5361: 	    $allpathcond.=
 5362: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5363: 	}
 5364:     }
 5365:     $allpathcond=~s/\|$//;
 5366:     return &docondval($allpathcond);
 5367: }
 5368: 
 5369: #evaluates an expression of conditions
 5370: sub docondval {
 5371:     my ($allpathcond) = @_;
 5372:     my $result=0;
 5373:     if ($env{'request.course.id'}
 5374: 	&& defined($allpathcond)) {
 5375: 	my $operand='|';
 5376: 	my @stack;
 5377: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5378: 	    if ($chunk eq '(') {
 5379: 		push @stack,($operand,$result);
 5380: 	    } elsif ($chunk eq ')') {
 5381: 		my $before=pop @stack;
 5382: 		if (pop @stack eq '&') {
 5383: 		    $result=$result>$before?$before:$result;
 5384: 		} else {
 5385: 		    $result=$result>$before?$result:$before;
 5386: 		}
 5387: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5388: 		$operand=$chunk;
 5389: 	    } else {
 5390: 		my $new=directcondval($chunk);
 5391: 		if ($operand eq '&') {
 5392: 		    $result=$result>$new?$new:$result;
 5393: 		} else {
 5394: 		    $result=$result>$new?$result:$new;
 5395: 		}
 5396: 	    }
 5397: 	}
 5398:     }
 5399:     return $result;
 5400: }
 5401: 
 5402: # ---------------------------------------------------- Devalidate courseresdata
 5403: 
 5404: sub devalidatecourseresdata {
 5405:     my ($coursenum,$coursedomain)=@_;
 5406:     my $hashid=$coursenum.':'.$coursedomain;
 5407:     &devalidate_cache_new('courseres',$hashid);
 5408: }
 5409: 
 5410: 
 5411: # --------------------------------------------------- Course Resourcedata Query
 5412: 
 5413: sub get_courseresdata {
 5414:     my ($coursenum,$coursedomain)=@_;
 5415:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5416:     my $hashid=$coursenum.':'.$coursedomain;
 5417:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5418:     my %dumpreply;
 5419:     unless (defined($cached)) {
 5420: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5421: 	$result=\%dumpreply;
 5422: 	my ($tmp) = keys(%dumpreply);
 5423: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5424: 	    &do_cache_new('courseres',$hashid,$result,600);
 5425: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5426: 	    return $tmp;
 5427: 	} elsif ($tmp =~ /^(error)/) {
 5428: 	    $result=undef;
 5429: 	    &do_cache_new('courseres',$hashid,$result,600);
 5430: 	}
 5431:     }
 5432:     return $result;
 5433: }
 5434: 
 5435: sub devalidateuserresdata {
 5436:     my ($uname,$udom)=@_;
 5437:     my $hashid="$udom:$uname";
 5438:     &devalidate_cache_new('userres',$hashid);
 5439: }
 5440: 
 5441: sub get_userresdata {
 5442:     my ($uname,$udom)=@_;
 5443:     #most student don\'t have any data set, check if there is some data
 5444:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5445: 
 5446:     my $hashid="$udom:$uname";
 5447:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5448:     if (!defined($cached)) {
 5449: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5450: 	$result=\%resourcedata;
 5451: 	&do_cache_new('userres',$hashid,$result,600);
 5452:     }
 5453:     my ($tmp)=keys(%$result);
 5454:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5455: 	return $result;
 5456:     }
 5457:     #error 2 occurs when the .db doesn't exist
 5458:     if ($tmp!~/error: 2 /) {
 5459: 	&logthis("<font color=\"blue\">WARNING:".
 5460: 		 " Trying to get resource data for ".
 5461: 		 $uname." at ".$udom.": ".
 5462: 		 $tmp."</font>");
 5463:     } elsif ($tmp=~/error: 2 /) {
 5464: 	#&EXT_cache_set($udom,$uname);
 5465: 	&do_cache_new('userres',$hashid,undef,600);
 5466: 	undef($tmp); # not really an error so don't send it back
 5467:     }
 5468:     return $tmp;
 5469: }
 5470: 
 5471: sub resdata {
 5472:     my ($name,$domain,$type,@which)=@_;
 5473:     my $result;
 5474:     if ($type eq 'course') {
 5475: 	$result=&get_courseresdata($name,$domain);
 5476:     } elsif ($type eq 'user') {
 5477: 	$result=&get_userresdata($name,$domain);
 5478:     }
 5479:     if (!ref($result)) { return $result; }    
 5480:     foreach my $item (@which) {
 5481: 	if (defined($result->{$item})) {
 5482: 	    return $result->{$item};
 5483: 	}
 5484:     }
 5485:     return undef;
 5486: }
 5487: 
 5488: #
 5489: # EXT resource caching routines
 5490: #
 5491: 
 5492: sub clear_EXT_cache_status {
 5493:     &delenv('cache.EXT.');
 5494: }
 5495: 
 5496: sub EXT_cache_status {
 5497:     my ($target_domain,$target_user) = @_;
 5498:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5499:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5500:         # We know already the user has no data
 5501:         return 1;
 5502:     } else {
 5503:         return 0;
 5504:     }
 5505: }
 5506: 
 5507: sub EXT_cache_set {
 5508:     my ($target_domain,$target_user) = @_;
 5509:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5510:     #&appenv($cachename => time);
 5511: }
 5512: 
 5513: # --------------------------------------------------------- Value of a Variable
 5514: sub EXT {
 5515: 
 5516:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5517:     unless ($varname) { return ''; }
 5518:     #get real user name/domain, courseid and symb
 5519:     my $courseid;
 5520:     my $publicuser;
 5521:     if ($symbparm) {
 5522: 	$symbparm=&get_symb_from_alias($symbparm);
 5523:     }
 5524:     if (!($uname && $udom)) {
 5525:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5526: 	  &Apache::lonxml::whichuser($symbparm);
 5527:       if (!$symbparm) {	$symbparm=$cursymb; }
 5528:     } else {
 5529: 	$courseid=$env{'request.course.id'};
 5530:     }
 5531:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5532:     my $rest;
 5533:     if (defined($therest[0])) {
 5534:        $rest=join('.',@therest);
 5535:     } else {
 5536:        $rest='';
 5537:     }
 5538: 
 5539:     my $qualifierrest=$qualifier;
 5540:     if ($rest) { $qualifierrest.='.'.$rest; }
 5541:     my $spacequalifierrest=$space;
 5542:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5543:     if ($realm eq 'user') {
 5544: # --------------------------------------------------------------- user.resource
 5545: 	if ($space eq 'resource') {
 5546: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5547: 		  || defined($Apache::lonhomework::parsing_a_task))
 5548: 		 &&
 5549: 		 ($symbparm eq &symbread()) ) {	
 5550: 		# if we are in the middle of processing the resource the
 5551: 		# get the value we are planning on committing
 5552:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5553:                     return $Apache::lonhomework::results{$qualifierrest};
 5554:                 } else {
 5555:                     return $Apache::lonhomework::history{$qualifierrest};
 5556:                 }
 5557: 	    } else {
 5558: 		my %restored;
 5559: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5560: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5561: 		} else {
 5562: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5563: 		}
 5564: 		return $restored{$qualifierrest};
 5565: 	    }
 5566: # ----------------------------------------------------------------- user.access
 5567:         } elsif ($space eq 'access') {
 5568: 	    # FIXME - not supporting calls for a specific user
 5569:             return &allowed($qualifier,$rest);
 5570: # ------------------------------------------ user.preferences, user.environment
 5571:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5572: 	    if (($uname eq $env{'user.name'}) &&
 5573: 		($udom eq $env{'user.domain'})) {
 5574: 		return $env{join('.',('environment',$qualifierrest))};
 5575: 	    } else {
 5576: 		my %returnhash;
 5577: 		if (!$publicuser) {
 5578: 		    %returnhash=&userenvironment($udom,$uname,
 5579: 						 $qualifierrest);
 5580: 		}
 5581: 		return $returnhash{$qualifierrest};
 5582: 	    }
 5583: # ----------------------------------------------------------------- user.course
 5584:         } elsif ($space eq 'course') {
 5585: 	    # FIXME - not supporting calls for a specific user
 5586:             return $env{join('.',('request.course',$qualifier))};
 5587: # ------------------------------------------------------------------- user.role
 5588:         } elsif ($space eq 'role') {
 5589: 	    # FIXME - not supporting calls for a specific user
 5590:             my ($role,$where)=split(/\./,$env{'request.role'});
 5591:             if ($qualifier eq 'value') {
 5592: 		return $role;
 5593:             } elsif ($qualifier eq 'extent') {
 5594:                 return $where;
 5595:             }
 5596: # ----------------------------------------------------------------- user.domain
 5597:         } elsif ($space eq 'domain') {
 5598:             return $udom;
 5599: # ------------------------------------------------------------------- user.name
 5600:         } elsif ($space eq 'name') {
 5601:             return $uname;
 5602: # ---------------------------------------------------- Any other user namespace
 5603:         } else {
 5604: 	    my %reply;
 5605: 	    if (!$publicuser) {
 5606: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5607: 	    }
 5608: 	    return $reply{$qualifierrest};
 5609:         }
 5610:     } elsif ($realm eq 'query') {
 5611: # ---------------------------------------------- pull stuff out of query string
 5612:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5613: 						[$spacequalifierrest]);
 5614: 	return $env{'form.'.$spacequalifierrest}; 
 5615:    } elsif ($realm eq 'request') {
 5616: # ------------------------------------------------------------- request.browser
 5617:         if ($space eq 'browser') {
 5618: 	    if ($qualifier eq 'textremote') {
 5619: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5620: 		    return 1;
 5621: 		} else {
 5622: 		    return 0;
 5623: 		}
 5624: 	    } else {
 5625: 		return $env{'browser.'.$qualifier};
 5626: 	    }
 5627: # ------------------------------------------------------------ request.filename
 5628:         } else {
 5629:             return $env{'request.'.$spacequalifierrest};
 5630:         }
 5631:     } elsif ($realm eq 'course') {
 5632: # ---------------------------------------------------------- course.description
 5633:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5634:     } elsif ($realm eq 'resource') {
 5635: 
 5636: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5637: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5638: 	}
 5639: 
 5640: 	if ($space eq 'title') {
 5641: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5642: 	    return &gettitle($symbparm);
 5643: 	}
 5644: 	
 5645: 	if ($space eq 'map') {
 5646: 	    my ($map) = &decode_symb($symbparm);
 5647: 	    return &symbread($map);
 5648: 	}
 5649: 
 5650: 	my ($section, $group, @groups);
 5651: 	my ($courselevelm,$courselevel);
 5652: 	if ($symbparm && defined($courseid) && 
 5653: 	    $courseid eq $env{'request.course.id'}) {
 5654: 
 5655: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5656: 
 5657: # ----------------------------------------------------- Cascading lookup scheme
 5658: 	    my $symbp=$symbparm;
 5659: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5660: 
 5661: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5662: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5663: 
 5664: 	    if (($env{'user.name'} eq $uname) &&
 5665: 		($env{'user.domain'} eq $udom)) {
 5666: 		$section=$env{'request.course.sec'};
 5667:                 @groups = split(/:/,$env{'request.course.groups'});  
 5668:                 @groups=&sort_course_groups($courseid,@groups); 
 5669: 	    } else {
 5670: 		if (! defined($usection)) {
 5671: 		    $section=&getsection($udom,$uname,$courseid);
 5672: 		} else {
 5673: 		    $section = $usection;
 5674: 		}
 5675:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5676: 	    }
 5677: 
 5678: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5679: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5680: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5681: 
 5682: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5683: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5684: 	    $courselevelm=$courseid.'.'.$mapparm;
 5685: 
 5686: # ----------------------------------------------------------- first, check user
 5687: 
 5688: 	    my $userreply=&resdata($uname,$udom,'user',
 5689: 				       ($courselevelr,$courselevelm,
 5690: 					$courselevel));
 5691: 	    if (defined($userreply)) { return $userreply; }
 5692: 
 5693: # ------------------------------------------------ second, check some of course
 5694:             my $coursereply;
 5695:             if (@groups > 0) {
 5696:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5697:                                        $mapparm,$spacequalifierrest);
 5698:                 if (defined($coursereply)) { return $coursereply; }
 5699:             }
 5700: 
 5701: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5702: 				     $env{'course.'.$courseid.'.domain'},
 5703: 				     'course',
 5704: 				     ($seclevelr,$seclevelm,$seclevel,
 5705: 				      $courselevelr));
 5706: 	    if (defined($coursereply)) { return $coursereply; }
 5707: 
 5708: # ------------------------------------------------------ third, check map parms
 5709: 	    my %parmhash=();
 5710: 	    my $thisparm='';
 5711: 	    if (tie(%parmhash,'GDBM_File',
 5712: 		    $env{'request.course.fn'}.'_parms.db',
 5713: 		    &GDBM_READER(),0640)) {
 5714: 		$thisparm=$parmhash{$symbparm};
 5715: 		untie(%parmhash);
 5716: 	    }
 5717: 	    if ($thisparm) { return $thisparm; }
 5718: 	}
 5719: # ------------------------------------------ fourth, look in resource metadata
 5720: 
 5721: 	$spacequalifierrest=~s/\./\_/;
 5722: 	my $filename;
 5723: 	if (!$symbparm) { $symbparm=&symbread(); }
 5724: 	if ($symbparm) {
 5725: 	    $filename=(&decode_symb($symbparm))[2];
 5726: 	} else {
 5727: 	    $filename=$env{'request.filename'};
 5728: 	}
 5729: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5730: 	if (defined($metadata)) { return $metadata; }
 5731: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5732: 	if (defined($metadata)) { return $metadata; }
 5733: 
 5734: # ---------------------------------------------- fourth, look in rest pf course
 5735: 	if ($symbparm && defined($courseid) && 
 5736: 	    $courseid eq $env{'request.course.id'}) {
 5737: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5738: 				     $env{'course.'.$courseid.'.domain'},
 5739: 				     'course',
 5740: 				     ($courselevelm,$courselevel));
 5741: 	    if (defined($coursereply)) { return $coursereply; }
 5742: 	}
 5743: # ------------------------------------------------------------------ Cascade up
 5744: 	unless ($space eq '0') {
 5745: 	    my @parts=split(/_/,$space);
 5746: 	    my $id=pop(@parts);
 5747: 	    my $part=join('_',@parts);
 5748: 	    if ($part eq '') { $part='0'; }
 5749: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5750: 				 $symbparm,$udom,$uname,$section,1);
 5751: 	    if (defined($partgeneral)) { return $partgeneral; }
 5752: 	}
 5753: 	if ($recurse) { return undef; }
 5754: 	my $pack_def=&packages_tab_default($filename,$varname);
 5755: 	if (defined($pack_def)) { return $pack_def; }
 5756: 
 5757: # ---------------------------------------------------- Any other user namespace
 5758:     } elsif ($realm eq 'environment') {
 5759: # ----------------------------------------------------------------- environment
 5760: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5761: 	    return $env{'environment.'.$spacequalifierrest};
 5762: 	} else {
 5763: 	    if ($uname eq 'anonymous' && $udom eq '') {
 5764: 		return '';
 5765: 	    }
 5766: 	    my %returnhash=&userenvironment($udom,$uname,
 5767: 					    $spacequalifierrest);
 5768: 	    return $returnhash{$spacequalifierrest};
 5769: 	}
 5770:     } elsif ($realm eq 'system') {
 5771: # ----------------------------------------------------------------- system.time
 5772: 	if ($space eq 'time') {
 5773: 	    return time;
 5774:         }
 5775:     } elsif ($realm eq 'server') {
 5776: # ----------------------------------------------------------------- system.time
 5777: 	if ($space eq 'name') {
 5778: 	    return $ENV{'SERVER_NAME'};
 5779:         }
 5780:     }
 5781:     return '';
 5782: }
 5783: 
 5784: sub check_group_parms {
 5785:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5786:     my @groupitems = ();
 5787:     my $resultitem;
 5788:     my @levels = ($symbparm,$mapparm,$what);
 5789:     foreach my $group (@{$groups}) {
 5790:         foreach my $level (@levels) {
 5791:              my $item = $courseid.'.['.$group.'].'.$level;
 5792:              push(@groupitems,$item);
 5793:         }
 5794:     }
 5795:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5796:                             $env{'course.'.$courseid.'.domain'},
 5797:                                      'course',@groupitems);
 5798:     return $coursereply;
 5799: }
 5800: 
 5801: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5802:     my ($courseid,@groups) = @_;
 5803:     @groups = sort(@groups);
 5804:     return @groups;
 5805: }
 5806: 
 5807: sub packages_tab_default {
 5808:     my ($uri,$varname)=@_;
 5809:     my (undef,$part,$name)=split(/\./,$varname);
 5810: 
 5811:     my (@extension,@specifics,$do_default);
 5812:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5813: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5814: 	if ($pack_type eq 'default') {
 5815: 	    $do_default=1;
 5816: 	} elsif ($pack_type eq 'extension') {
 5817: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5818: 	} else {
 5819: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5820: 	}
 5821:     }
 5822:     # first look for a package that matches the requested part id
 5823:     foreach my $package (@specifics) {
 5824: 	my (undef,$pack_type,$pack_part)=@{$package};
 5825: 	next if ($pack_part ne $part);
 5826: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5827: 	    return $packagetab{"$pack_type&$name&default"};
 5828: 	}
 5829:     }
 5830:     # look for any possible matching non extension_ package
 5831:     foreach my $package (@specifics) {
 5832: 	my (undef,$pack_type,$pack_part)=@{$package};
 5833: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5834: 	    return $packagetab{"$pack_type&$name&default"};
 5835: 	}
 5836: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5837: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5838: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5839: 	}
 5840:     }
 5841:     # look for any posible extension_ match
 5842:     foreach my $package (@extension) {
 5843: 	my ($package,$pack_type)=@{$package};
 5844: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5845: 	    return $packagetab{"$pack_type&$name&default"};
 5846: 	}
 5847: 	if (defined($packagetab{$package."&$name&default"})) {
 5848: 	    return $packagetab{$package."&$name&default"};
 5849: 	}
 5850:     }
 5851:     # look for a global default setting
 5852:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5853: 	return $packagetab{"default&$name&default"};
 5854:     }
 5855:     return undef;
 5856: }
 5857: 
 5858: sub add_prefix_and_part {
 5859:     my ($prefix,$part)=@_;
 5860:     my $keyroot;
 5861:     if (defined($prefix) && $prefix !~ /^__/) {
 5862: 	# prefix that has a part already
 5863: 	$keyroot=$prefix;
 5864:     } elsif (defined($prefix)) {
 5865: 	# prefix that is missing a part
 5866: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5867:     } else {
 5868: 	# no prefix at all
 5869: 	if (defined($part)) { $keyroot='_'.$part; }
 5870:     }
 5871:     return $keyroot;
 5872: }
 5873: 
 5874: # ---------------------------------------------------------------- Get metadata
 5875: 
 5876: my %metaentry;
 5877: sub metadata {
 5878:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5879:     $uri=&declutter($uri);
 5880:     # if it is a non metadata possible uri return quickly
 5881:     if (($uri eq '') || 
 5882: 	(($uri =~ m|^/*adm/|) && 
 5883: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5884:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5885: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5886: 	return undef;
 5887:     }
 5888:     my $filename=$uri;
 5889:     $uri=~s/\.meta$//;
 5890: #
 5891: # Is the metadata already cached?
 5892: # Look at timestamp of caching
 5893: # Everything is cached by the main uri, libraries are never directly cached
 5894: #
 5895:     if (!defined($liburi)) {
 5896: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5897: 	if (defined($cached)) { return $result->{':'.$what}; }
 5898:     }
 5899:     {
 5900: #
 5901: # Is this a recursive call for a library?
 5902: #
 5903: #	if (! exists($metacache{$uri})) {
 5904: #	    $metacache{$uri}={};
 5905: #	}
 5906:         if ($liburi) {
 5907: 	    $liburi=&declutter($liburi);
 5908:             $filename=$liburi;
 5909:         } else {
 5910: 	    &devalidate_cache_new('meta',$uri);
 5911: 	    undef(%metaentry);
 5912: 	}
 5913:         my %metathesekeys=();
 5914:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5915: 	my $metastring;
 5916: 	if ($uri !~ m -^(editupload)/-) {
 5917: 	    my $file=&filelocation('',&clutter($filename));
 5918: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5919: 	    $metastring=&getfile($file);
 5920: 	}
 5921:         my $parser=HTML::LCParser->new(\$metastring);
 5922:         my $token;
 5923:         undef %metathesekeys;
 5924:         while ($token=$parser->get_token) {
 5925: 	    if ($token->[0] eq 'S') {
 5926: 		if (defined($token->[2]->{'package'})) {
 5927: #
 5928: # This is a package - get package info
 5929: #
 5930: 		    my $package=$token->[2]->{'package'};
 5931: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5932: 		    if (defined($token->[2]->{'id'})) { 
 5933: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5934: 		    }
 5935: 		    if ($metaentry{':packages'}) {
 5936: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5937: 		    } else {
 5938: 			$metaentry{':packages'}=$package.$keyroot;
 5939: 		    }
 5940: 		    foreach my $pack_entry (keys(%packagetab)) {
 5941: 			my $part=$keyroot;
 5942: 			$part=~s/^\_//;
 5943: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 5944: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 5945: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 5946: 			    # ignore package.tab specified default values
 5947:                             # here &package_tab_default() will fetch those
 5948: 			    if ($subp eq 'default') { next; }
 5949: 			    my $value=$packagetab{$pack_entry};
 5950: 			    my $unikey;
 5951: 			    if ($pack =~ /_0$/) {
 5952: 				$unikey='parameter_0_'.$name;
 5953: 				$part=0;
 5954: 			    } else {
 5955: 				$unikey='parameter'.$keyroot.'_'.$name;
 5956: 			    }
 5957: 			    if ($subp eq 'display') {
 5958: 				$value.=' [Part: '.$part.']';
 5959: 			    }
 5960: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5961: 			    $metathesekeys{$unikey}=1;
 5962: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5963: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5964: 			    }
 5965: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5966: 				$metaentry{':'.$unikey}=
 5967: 				    $metaentry{':'.$unikey.'.default'};
 5968: 			    }
 5969: 			}
 5970: 		    }
 5971: 		} else {
 5972: #
 5973: # This is not a package - some other kind of start tag
 5974: #
 5975: 		    my $entry=$token->[1];
 5976: 		    my $unikey;
 5977: 		    if ($entry eq 'import') {
 5978: 			$unikey='';
 5979: 		    } else {
 5980: 			$unikey=$entry;
 5981: 		    }
 5982: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5983: 
 5984: 		    if (defined($token->[2]->{'id'})) { 
 5985: 			$unikey.='_'.$token->[2]->{'id'}; 
 5986: 		    }
 5987: 
 5988: 		    if ($entry eq 'import') {
 5989: #
 5990: # Importing a library here
 5991: #
 5992: 			if ($depthcount<20) {
 5993: 			    my $location=$parser->get_text('/import');
 5994: 			    my $dir=$filename;
 5995: 			    $dir=~s|[^/]*$||;
 5996: 			    $location=&filelocation($dir,$location);
 5997: 			    my $metadata = 
 5998: 				&metadata($uri,'keys', $location,$unikey,
 5999: 					  $depthcount+1);
 6000: 			    foreach my $meta (split(',',$metadata)) {
 6001: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6002: 				$metathesekeys{$meta}=1;
 6003: 			    }
 6004: 			}
 6005: 		    } else { 
 6006: 			
 6007: 			if (defined($token->[2]->{'name'})) { 
 6008: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6009: 			}
 6010: 			$metathesekeys{$unikey}=1;
 6011: 			foreach my $param (@{$token->[3]}) {
 6012: 			    $metaentry{':'.$unikey.'.'.$param} =
 6013: 				$token->[2]->{$param};
 6014: 			}
 6015: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6016: 			my $default=$metaentry{':'.$unikey.'.default'};
 6017: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6018: 		 # only ws inside the tag, and not in default, so use default
 6019: 		 # as value
 6020: 			    $metaentry{':'.$unikey}=$default;
 6021: 			} else {
 6022: 		  # either something interesting inside the tag or default
 6023:                   # uninteresting
 6024: 			    $metaentry{':'.$unikey}=$internaltext;
 6025: 			}
 6026: # end of not-a-package not-a-library import
 6027: 		    }
 6028: # end of not-a-package start tag
 6029: 		}
 6030: # the next is the end of "start tag"
 6031: 	    }
 6032: 	}
 6033: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6034: 	foreach my $key (keys(%packagetab)) {
 6035: 	    #no specific packages #how's our extension
 6036: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6037: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6038: 					 \%metathesekeys);
 6039: 	}
 6040: 	if (!exists($metaentry{':packages'})) {
 6041: 	    foreach my $key (keys(%packagetab)) {
 6042: 		#no specific packages well let's get default then
 6043: 		if ($key!~/^default&/) { next; }
 6044: 		&metadata_create_package_def($uri,$key,'default',
 6045: 					     \%metathesekeys);
 6046: 	    }
 6047: 	}
 6048: # are there custom rights to evaluate
 6049: 	if ($metaentry{':copyright'} eq 'custom') {
 6050: 
 6051:     #
 6052:     # Importing a rights file here
 6053:     #
 6054: 	    unless ($depthcount) {
 6055: 		my $location=$metaentry{':customdistributionfile'};
 6056: 		my $dir=$filename;
 6057: 		$dir=~s|[^/]*$||;
 6058: 		$location=&filelocation($dir,$location);
 6059: 		my $rights_metadata =
 6060: 		    &metadata($uri,'keys',$location,'_rights',
 6061: 			      $depthcount+1);
 6062: 		foreach my $rights (split(',',$rights_metadata)) {
 6063: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6064: 		    $metathesekeys{$rights}=1;
 6065: 		}
 6066: 	    }
 6067: 	}
 6068: 	# uniqifiy package listing
 6069: 	my %seen;
 6070: 	my @uniq_packages =
 6071: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6072: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6073: 
 6074: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6075: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6076: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6077: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6078: # this is the end of "was not already recently cached
 6079:     }
 6080:     return $metaentry{':'.$what};
 6081: }
 6082: 
 6083: sub metadata_create_package_def {
 6084:     my ($uri,$key,$package,$metathesekeys)=@_;
 6085:     my ($pack,$name,$subp)=split(/\&/,$key);
 6086:     if ($subp eq 'default') { next; }
 6087:     
 6088:     if (defined($metaentry{':packages'})) {
 6089: 	$metaentry{':packages'}.=','.$package;
 6090:     } else {
 6091: 	$metaentry{':packages'}=$package;
 6092:     }
 6093:     my $value=$packagetab{$key};
 6094:     my $unikey;
 6095:     $unikey='parameter_0_'.$name;
 6096:     $metaentry{':'.$unikey.'.part'}=0;
 6097:     $$metathesekeys{$unikey}=1;
 6098:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6099: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6100:     }
 6101:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6102: 	$metaentry{':'.$unikey}=
 6103: 	    $metaentry{':'.$unikey.'.default'};
 6104:     }
 6105: }
 6106: 
 6107: sub metadata_generate_part0 {
 6108:     my ($metadata,$metacache,$uri) = @_;
 6109:     my %allnames;
 6110:     foreach my $metakey (keys(%$metadata)) {
 6111: 	if ($metakey=~/^parameter\_(.*)/) {
 6112: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6113: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6114: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6115: 	    $allnames{$name}=$part;
 6116: 	  }
 6117: 	}
 6118:     }
 6119:     foreach my $name (keys(%allnames)) {
 6120:       $$metadata{"parameter_0_$name"}=1;
 6121:       my $key=":parameter_0_$name";
 6122:       $$metacache{"$key.part"}='0';
 6123:       $$metacache{"$key.name"}=$name;
 6124:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6125: 					   $allnames{$name}.'_'.$name.
 6126: 					   '.type'};
 6127:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6128: 			     '.display'};
 6129:       my $expr='[Part: '.$allnames{$name}.']';
 6130:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6131:       $$metacache{"$key.display"}=$olddis;
 6132:     }
 6133: }
 6134: 
 6135: # ------------------------------------------------------ Devalidate title cache
 6136: 
 6137: sub devalidate_title_cache {
 6138:     my ($url)=@_;
 6139:     if (!$env{'request.course.id'}) { return; }
 6140:     my $symb=&symbread($url);
 6141:     if (!$symb) { return; }
 6142:     my $key=$env{'request.course.id'}."\0".$symb;
 6143:     &devalidate_cache_new('title',$key);
 6144: }
 6145: 
 6146: # ------------------------------------------------- Get the title of a resource
 6147: 
 6148: sub gettitle {
 6149:     my $urlsymb=shift;
 6150:     my $symb=&symbread($urlsymb);
 6151:     if ($symb) {
 6152: 	my $key=$env{'request.course.id'}."\0".$symb;
 6153: 	my ($result,$cached)=&is_cached_new('title',$key);
 6154: 	if (defined($cached)) { 
 6155: 	    return $result;
 6156: 	}
 6157: 	my ($map,$resid,$url)=&decode_symb($symb);
 6158: 	my $title='';
 6159: 	my %bighash;
 6160: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6161: 		&GDBM_READER(),0640)) {
 6162: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6163: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6164: 	    untie %bighash;
 6165: 	}
 6166: 	$title=~s/\&colon\;/\:/gs;
 6167: 	if ($title) {
 6168: 	    return &do_cache_new('title',$key,$title,600);
 6169: 	}
 6170: 	$urlsymb=$url;
 6171:     }
 6172:     my $title=&metadata($urlsymb,'title');
 6173:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6174:     return $title;
 6175: }
 6176: 
 6177: sub get_slot {
 6178:     my ($which,$cnum,$cdom)=@_;
 6179:     if (!$cnum || !$cdom) {
 6180: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 6181: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6182: 	$cnum=$env{'course.'.$courseid.'.num'};
 6183:     }
 6184:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6185:     my %slotinfo;
 6186:     if (exists($remembered{$key})) {
 6187: 	$slotinfo{$which} = $remembered{$key};
 6188:     } else {
 6189: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6190: 	&Apache::lonhomework::showhash(%slotinfo);
 6191: 	my ($tmp)=keys(%slotinfo);
 6192: 	if ($tmp=~/^error:/) { return (); }
 6193: 	$remembered{$key} = $slotinfo{$which};
 6194:     }
 6195:     if (ref($slotinfo{$which}) eq 'HASH') {
 6196: 	return %{$slotinfo{$which}};
 6197:     }
 6198:     return $slotinfo{$which};
 6199: }
 6200: # ------------------------------------------------- Update symbolic store links
 6201: 
 6202: sub symblist {
 6203:     my ($mapname,%newhash)=@_;
 6204:     $mapname=&deversion(&declutter($mapname));
 6205:     my %hash;
 6206:     if (($env{'request.course.fn'}) && (%newhash)) {
 6207:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6208:                       &GDBM_WRCREAT(),0640)) {
 6209: 	    foreach my $url (keys %newhash) {
 6210: 		next if ($url eq 'last_known'
 6211: 			 && $env{'form.no_update_last_known'});
 6212: 		$hash{declutter($url)}=&encode_symb($mapname,
 6213: 						    $newhash{$url}->[1],
 6214: 						    $newhash{$url}->[0]);
 6215:             }
 6216:             if (untie(%hash)) {
 6217: 		return 'ok';
 6218:             }
 6219:         }
 6220:     }
 6221:     return 'error';
 6222: }
 6223: 
 6224: # --------------------------------------------------------------- Verify a symb
 6225: 
 6226: sub symbverify {
 6227:     my ($symb,$thisurl)=@_;
 6228:     my $thisfn=$thisurl;
 6229: # wrapper not part of symbs
 6230:     $thisfn=~s/^\/adm\/wrapper//;
 6231:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 6232:     $thisfn=&declutter($thisfn);
 6233: # direct jump to resource in page or to a sequence - will construct own symbs
 6234:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6235: # check URL part
 6236:     my ($map,$resid,$url)=&decode_symb($symb);
 6237: 
 6238:     unless ($url eq $thisfn) { return 0; }
 6239: 
 6240:     $symb=&symbclean($symb);
 6241:     $thisurl=&deversion($thisurl);
 6242:     $thisfn=&deversion($thisfn);
 6243: 
 6244:     my %bighash;
 6245:     my $okay=0;
 6246: 
 6247:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6248:                             &GDBM_READER(),0640)) {
 6249:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6250:         unless ($ids) { 
 6251:            $ids=$bighash{'ids_/'.$thisurl};
 6252:         }
 6253:         if ($ids) {
 6254: # ------------------------------------------------------------------- Has ID(s)
 6255: 	    foreach (split(/\,/,$ids)) {
 6256: 	       my ($mapid,$resid)=split(/\./,$_);
 6257:                if (
 6258:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6259:    eq $symb) { 
 6260: 		   if (($env{'request.role.adv'}) ||
 6261: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 6262: 		       $okay=1; 
 6263: 		   }
 6264: 	       }
 6265: 	   }
 6266:         }
 6267: 	untie(%bighash);
 6268:     }
 6269:     return $okay;
 6270: }
 6271: 
 6272: # --------------------------------------------------------------- Clean-up symb
 6273: 
 6274: sub symbclean {
 6275:     my $symb=shift;
 6276:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6277: # remove version from map
 6278:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6279: 
 6280: # remove version from URL
 6281:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6282: 
 6283: # remove wrapper
 6284: 
 6285:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6286:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6287:     return $symb;
 6288: }
 6289: 
 6290: # ---------------------------------------------- Split symb to find map and url
 6291: 
 6292: sub encode_symb {
 6293:     my ($map,$resid,$url)=@_;
 6294:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6295: }
 6296: 
 6297: sub decode_symb {
 6298:     my $symb=shift;
 6299:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6300:     my ($map,$resid,$url)=split(/___/,$symb);
 6301:     return (&fixversion($map),$resid,&fixversion($url));
 6302: }
 6303: 
 6304: sub fixversion {
 6305:     my $fn=shift;
 6306:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6307:     my %bighash;
 6308:     my $uri=&clutter($fn);
 6309:     my $key=$env{'request.course.id'}.'_'.$uri;
 6310: # is this cached?
 6311:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6312:     if (defined($cached)) { return $result; }
 6313: # unfortunately not cached, or expired
 6314:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6315: 	    &GDBM_READER(),0640)) {
 6316:  	if ($bighash{'version_'.$uri}) {
 6317:  	    my $version=$bighash{'version_'.$uri};
 6318:  	    unless (($version eq 'mostrecent') || 
 6319: 		    ($version==&getversion($uri))) {
 6320:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6321:  	    }
 6322:  	}
 6323:  	untie %bighash;
 6324:     }
 6325:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6326: }
 6327: 
 6328: sub deversion {
 6329:     my $url=shift;
 6330:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6331:     return $url;
 6332: }
 6333: 
 6334: # ------------------------------------------------------ Return symb list entry
 6335: 
 6336: sub symbread {
 6337:     my ($thisfn,$donotrecurse)=@_;
 6338:     my $cache_str='request.symbread.cached.'.$thisfn;
 6339:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6340: # no filename provided? try from environment
 6341:     unless ($thisfn) {
 6342:         if ($env{'request.symb'}) {
 6343: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6344: 	}
 6345: 	$thisfn=$env{'request.filename'};
 6346:     }
 6347:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6348: # is that filename actually a symb? Verify, clean, and return
 6349:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6350: 	if (&symbverify($thisfn,$1)) {
 6351: 	    return $env{$cache_str}=&symbclean($thisfn);
 6352: 	}
 6353:     }
 6354:     $thisfn=declutter($thisfn);
 6355:     my %hash;
 6356:     my %bighash;
 6357:     my $syval='';
 6358:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6359:         my $targetfn = $thisfn;
 6360:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6361:             $targetfn = 'adm/wrapper/'.$thisfn;
 6362:         }
 6363: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6364: 	    $targetfn=$1;
 6365: 	}
 6366:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6367:                       &GDBM_READER(),0640)) {
 6368: 	    $syval=$hash{$targetfn};
 6369:             untie(%hash);
 6370:         }
 6371: # ---------------------------------------------------------- There was an entry
 6372:         if ($syval) {
 6373: 	    #unless ($syval=~/\_\d+$/) {
 6374: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6375: 		    #&appenv('request.ambiguous' => $thisfn);
 6376: 		    #return $env{$cache_str}='';
 6377: 		#}    
 6378: 		#$syval.=$1;
 6379: 	    #}
 6380:         } else {
 6381: # ------------------------------------------------------- Was not in symb table
 6382:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6383:                             &GDBM_READER(),0640)) {
 6384: # ---------------------------------------------- Get ID(s) for current resource
 6385:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6386:               unless ($ids) { 
 6387:                  $ids=$bighash{'ids_/'.$thisfn};
 6388:               }
 6389:               unless ($ids) {
 6390: # alias?
 6391: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6392:               }
 6393:               if ($ids) {
 6394: # ------------------------------------------------------------------- Has ID(s)
 6395:                  my @possibilities=split(/\,/,$ids);
 6396:                  if ($#possibilities==0) {
 6397: # ----------------------------------------------- There is only one possibility
 6398: 		     my ($mapid,$resid)=split(/\./,$ids);
 6399: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6400: 						    $resid,$thisfn);
 6401:                  } elsif (!$donotrecurse) {
 6402: # ------------------------------------------ There is more than one possibility
 6403:                      my $realpossible=0;
 6404:                      foreach (@possibilities) {
 6405: 			 my $file=$bighash{'src_'.$_};
 6406:                          if (&allowed('bre',$file)) {
 6407:          		    my ($mapid,$resid)=split(/\./,$_);
 6408:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6409: 				$realpossible++;
 6410:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6411: 						    $resid,$thisfn);
 6412:                             }
 6413: 			 }
 6414:                      }
 6415: 		     if ($realpossible!=1) { $syval=''; }
 6416:                  } else {
 6417:                      $syval='';
 6418:                  }
 6419: 	      }
 6420:               untie(%bighash)
 6421:            }
 6422:         }
 6423:         if ($syval) {
 6424: 	    return $env{$cache_str}=$syval;
 6425:         }
 6426:     }
 6427:     &appenv('request.ambiguous' => $thisfn);
 6428:     return $env{$cache_str}='';
 6429: }
 6430: 
 6431: # ---------------------------------------------------------- Return random seed
 6432: 
 6433: sub numval {
 6434:     my $txt=shift;
 6435:     $txt=~tr/A-J/0-9/;
 6436:     $txt=~tr/a-j/0-9/;
 6437:     $txt=~tr/K-T/0-9/;
 6438:     $txt=~tr/k-t/0-9/;
 6439:     $txt=~tr/U-Z/0-5/;
 6440:     $txt=~tr/u-z/0-5/;
 6441:     $txt=~s/\D//g;
 6442:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6443:     return int($txt);
 6444: }
 6445: 
 6446: sub numval2 {
 6447:     my $txt=shift;
 6448:     $txt=~tr/A-J/0-9/;
 6449:     $txt=~tr/a-j/0-9/;
 6450:     $txt=~tr/K-T/0-9/;
 6451:     $txt=~tr/k-t/0-9/;
 6452:     $txt=~tr/U-Z/0-5/;
 6453:     $txt=~tr/u-z/0-5/;
 6454:     $txt=~s/\D//g;
 6455:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6456:     my $total;
 6457:     foreach my $val (@txts) { $total+=$val; }
 6458:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6459:     return int($total);
 6460: }
 6461: 
 6462: sub numval3 {
 6463:     use integer;
 6464:     my $txt=shift;
 6465:     $txt=~tr/A-J/0-9/;
 6466:     $txt=~tr/a-j/0-9/;
 6467:     $txt=~tr/K-T/0-9/;
 6468:     $txt=~tr/k-t/0-9/;
 6469:     $txt=~tr/U-Z/0-5/;
 6470:     $txt=~tr/u-z/0-5/;
 6471:     $txt=~s/\D//g;
 6472:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6473:     my $total;
 6474:     foreach my $val (@txts) { $total+=$val; }
 6475:     if ($_64bit) { $total=(($total<<32)>>32); }
 6476:     return $total;
 6477: }
 6478: 
 6479: sub digest {
 6480:     my ($data)=@_;
 6481:     my $digest=&Digest::MD5::md5($data);
 6482:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6483:     my ($e,$f);
 6484:     {
 6485:         use integer;
 6486:         $e=($a+$b);
 6487:         $f=($c+$d);
 6488:         if ($_64bit) {
 6489:             $e=(($e<<32)>>32);
 6490:             $f=(($f<<32)>>32);
 6491:         }
 6492:     }
 6493:     if (wantarray) {
 6494: 	return ($e,$f);
 6495:     } else {
 6496: 	my $g;
 6497: 	{
 6498: 	    use integer;
 6499: 	    $g=($e+$f);
 6500: 	    if ($_64bit) {
 6501: 		$g=(($g<<32)>>32);
 6502: 	    }
 6503: 	}
 6504: 	return $g;
 6505:     }
 6506: }
 6507: 
 6508: sub latest_rnd_algorithm_id {
 6509:     return '64bit5';
 6510: }
 6511: 
 6512: sub get_rand_alg {
 6513:     my ($courseid)=@_;
 6514:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 6515:     if ($courseid) {
 6516: 	return $env{"course.$courseid.rndseed"};
 6517:     }
 6518:     return &latest_rnd_algorithm_id();
 6519: }
 6520: 
 6521: sub validCODE {
 6522:     my ($CODE)=@_;
 6523:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6524:     return 0;
 6525: }
 6526: 
 6527: sub getCODE {
 6528:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6529:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6530: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6531: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6532: 	return $Apache::lonhomework::history{'resource.CODE'};
 6533:     }
 6534:     return undef;
 6535: }
 6536: 
 6537: sub rndseed {
 6538:     my ($symb,$courseid,$domain,$username)=@_;
 6539: 
 6540:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 6541:     if (!$symb) {
 6542: 	unless ($symb=$wsymb) { return time; }
 6543:     }
 6544:     if (!$courseid) { $courseid=$wcourseid; }
 6545:     if (!$domain) { $domain=$wdomain; }
 6546:     if (!$username) { $username=$wusername }
 6547:     my $which=&get_rand_alg();
 6548:     if (defined(&getCODE())) {
 6549: 	if ($which eq '64bit5') {
 6550: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6551: 	} elsif ($which eq '64bit4') {
 6552: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6553: 	} else {
 6554: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6555: 	}
 6556:     } elsif ($which eq '64bit5') {
 6557: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6558:     } elsif ($which eq '64bit4') {
 6559: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6560:     } elsif ($which eq '64bit3') {
 6561: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6562:     } elsif ($which eq '64bit2') {
 6563: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6564:     } elsif ($which eq '64bit') {
 6565: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6566:     }
 6567:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6568: }
 6569: 
 6570: sub rndseed_32bit {
 6571:     my ($symb,$courseid,$domain,$username)=@_;
 6572:     {
 6573: 	use integer;
 6574: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6575: 	my $symbseed=numval($symb) << 22;
 6576: 	my $namechck=unpack("%32C*",$username) << 17;
 6577: 	my $nameseed=numval($username) << 12;
 6578: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6579: 	my $courseseed=unpack("%32C*",$courseid);
 6580: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6581: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6582: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6583: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6584: 	return $num;
 6585:     }
 6586: }
 6587: 
 6588: sub rndseed_64bit {
 6589:     my ($symb,$courseid,$domain,$username)=@_;
 6590:     {
 6591: 	use integer;
 6592: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6593: 	my $symbseed=numval($symb) << 10;
 6594: 	my $namechck=unpack("%32S*",$username);
 6595: 	
 6596: 	my $nameseed=numval($username) << 21;
 6597: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6598: 	my $courseseed=unpack("%32S*",$courseid);
 6599: 	
 6600: 	my $num1=$symbchck+$symbseed+$namechck;
 6601: 	my $num2=$nameseed+$domainseed+$courseseed;
 6602: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6603: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6604: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6605: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6606: 	return "$num1,$num2";
 6607:     }
 6608: }
 6609: 
 6610: sub rndseed_64bit2 {
 6611:     my ($symb,$courseid,$domain,$username)=@_;
 6612:     {
 6613: 	use integer;
 6614: 	# strings need to be an even # of cahracters long, it it is odd the
 6615:         # last characters gets thrown away
 6616: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6617: 	my $symbseed=numval($symb) << 10;
 6618: 	my $namechck=unpack("%32S*",$username.' ');
 6619: 	
 6620: 	my $nameseed=numval($username) << 21;
 6621: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6622: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6623: 	
 6624: 	my $num1=$symbchck+$symbseed+$namechck;
 6625: 	my $num2=$nameseed+$domainseed+$courseseed;
 6626: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6627: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6628: 	return "$num1,$num2";
 6629:     }
 6630: }
 6631: 
 6632: sub rndseed_64bit3 {
 6633:     my ($symb,$courseid,$domain,$username)=@_;
 6634:     {
 6635: 	use integer;
 6636: 	# strings need to be an even # of cahracters long, it it is odd the
 6637:         # last characters gets thrown away
 6638: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6639: 	my $symbseed=numval2($symb) << 10;
 6640: 	my $namechck=unpack("%32S*",$username.' ');
 6641: 	
 6642: 	my $nameseed=numval2($username) << 21;
 6643: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6644: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6645: 	
 6646: 	my $num1=$symbchck+$symbseed+$namechck;
 6647: 	my $num2=$nameseed+$domainseed+$courseseed;
 6648: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6649: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6650: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6651: 	
 6652: 	return "$num1:$num2";
 6653:     }
 6654: }
 6655: 
 6656: sub rndseed_64bit4 {
 6657:     my ($symb,$courseid,$domain,$username)=@_;
 6658:     {
 6659: 	use integer;
 6660: 	# strings need to be an even # of cahracters long, it it is odd the
 6661:         # last characters gets thrown away
 6662: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6663: 	my $symbseed=numval3($symb) << 10;
 6664: 	my $namechck=unpack("%32S*",$username.' ');
 6665: 	
 6666: 	my $nameseed=numval3($username) << 21;
 6667: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6668: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6669: 	
 6670: 	my $num1=$symbchck+$symbseed+$namechck;
 6671: 	my $num2=$nameseed+$domainseed+$courseseed;
 6672: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6673: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6674: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6675: 	
 6676: 	return "$num1:$num2";
 6677:     }
 6678: }
 6679: 
 6680: sub rndseed_64bit5 {
 6681:     my ($symb,$courseid,$domain,$username)=@_;
 6682:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6683:     return "$num1:$num2";
 6684: }
 6685: 
 6686: sub rndseed_CODE_64bit {
 6687:     my ($symb,$courseid,$domain,$username)=@_;
 6688:     {
 6689: 	use integer;
 6690: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6691: 	my $symbseed=numval2($symb);
 6692: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6693: 	my $CODEseed=numval(&getCODE());
 6694: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6695: 	my $num1=$symbseed+$CODEchck;
 6696: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6697: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6698: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6699: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6700: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6701: 	return "$num1:$num2";
 6702:     }
 6703: }
 6704: 
 6705: sub rndseed_CODE_64bit4 {
 6706:     my ($symb,$courseid,$domain,$username)=@_;
 6707:     {
 6708: 	use integer;
 6709: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6710: 	my $symbseed=numval3($symb);
 6711: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6712: 	my $CODEseed=numval3(&getCODE());
 6713: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6714: 	my $num1=$symbseed+$CODEchck;
 6715: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6716: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6717: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6718: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6719: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6720: 	return "$num1:$num2";
 6721:     }
 6722: }
 6723: 
 6724: sub rndseed_CODE_64bit5 {
 6725:     my ($symb,$courseid,$domain,$username)=@_;
 6726:     my $code = &getCODE();
 6727:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6728:     return "$num1:$num2";
 6729: }
 6730: 
 6731: sub setup_random_from_rndseed {
 6732:     my ($rndseed)=@_;
 6733:     if ($rndseed =~/([,:])/) {
 6734: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6735: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6736:     } else {
 6737: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6738:     }
 6739: }
 6740: 
 6741: sub latest_receipt_algorithm_id {
 6742:     return 'receipt2';
 6743: }
 6744: 
 6745: sub recunique {
 6746:     my $fucourseid=shift;
 6747:     my $unique;
 6748:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6749: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6750:     } else {
 6751: 	$unique=$perlvar{'lonReceipt'};
 6752:     }
 6753:     return unpack("%32C*",$unique);
 6754: }
 6755: 
 6756: sub recprefix {
 6757:     my $fucourseid=shift;
 6758:     my $prefix;
 6759:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6760: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6761:     } else {
 6762: 	$prefix=$perlvar{'lonHostID'};
 6763:     }
 6764:     return unpack("%32C*",$prefix);
 6765: }
 6766: 
 6767: sub ireceipt {
 6768:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6769:     my $cuname=unpack("%32C*",$funame);
 6770:     my $cudom=unpack("%32C*",$fudom);
 6771:     my $cucourseid=unpack("%32C*",$fucourseid);
 6772:     my $cusymb=unpack("%32C*",$fusymb);
 6773:     my $cunique=&recunique($fucourseid);
 6774:     my $cpart=unpack("%32S*",$part);
 6775:     my $return =&recprefix($fucourseid).'-';
 6776:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6777: 	$env{'request.state'} eq 'construct') {
 6778: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6779: 			       " and ".($cpart%$cudom));
 6780: 			       
 6781: 	$return.= ($cunique%$cuname+
 6782: 		   $cunique%$cudom+
 6783: 		   $cusymb%$cuname+
 6784: 		   $cusymb%$cudom+
 6785: 		   $cucourseid%$cuname+
 6786: 		   $cucourseid%$cudom+
 6787: 		   $cpart%$cuname+
 6788: 		   $cpart%$cudom);
 6789:     } else {
 6790: 	$return.= ($cunique%$cuname+
 6791: 		   $cunique%$cudom+
 6792: 		   $cusymb%$cuname+
 6793: 		   $cusymb%$cudom+
 6794: 		   $cucourseid%$cuname+
 6795: 		   $cucourseid%$cudom);
 6796:     }
 6797:     return $return;
 6798: }
 6799: 
 6800: sub receipt {
 6801:     my ($part)=@_;
 6802:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6803:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6804: }
 6805: 
 6806: # ------------------------------------------------------------ Serves up a file
 6807: # returns either the contents of the file or 
 6808: # -1 if the file doesn't exist
 6809: #
 6810: # if the target is a file that was uploaded via DOCS, 
 6811: # a check will be made to see if a current copy exists on the local server,
 6812: # if it does this will be served, otherwise a copy will be retrieved from
 6813: # the home server for the course and stored in /home/httpd/html/userfiles on
 6814: # the local server.   
 6815: 
 6816: sub getfile {
 6817:     my ($file) = @_;
 6818:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6819:     &repcopy($file);
 6820:     return &readfile($file);
 6821: }
 6822: 
 6823: sub repcopy_userfile {
 6824:     my ($file)=@_;
 6825:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6826:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6827:     my ($cdom,$cnum,$filename) = 
 6828: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6829:     my ($info,$rtncode);
 6830:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6831:     if (-e "$file") {
 6832: 	my @fileinfo = stat($file);
 6833: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6834: 	if ($lwpresp ne 'ok') {
 6835: 	    if ($rtncode eq '404') {
 6836: 		unlink($file);
 6837: 	    }
 6838: 	    #my $ua=new LWP::UserAgent;
 6839: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6840: 	    #my $response=$ua->request($request);
 6841: 	    #if ($response->is_success()) {
 6842: 	#	return $response->content;
 6843: 	#    } else {
 6844: 	#	return -1;
 6845: 	#    }
 6846: 	    return -1;
 6847: 	}
 6848: 	if ($info < $fileinfo[9]) {
 6849: 	    return 'ok';
 6850: 	}
 6851: 	$info = '';
 6852: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6853: 	if ($lwpresp ne 'ok') {
 6854: 	    return -1;
 6855: 	}
 6856:     } else {
 6857: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6858: 	if ($lwpresp ne 'ok') {
 6859: 	    my $ua=new LWP::UserAgent;
 6860: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6861: 	    my $response=$ua->request($request);
 6862: 	    if ($response->is_success()) {
 6863: 		$info=$response->content;
 6864: 	    } else {
 6865: 		return -1;
 6866: 	    }
 6867: 	}
 6868: 	my @parts = ($cdom,$cnum); 
 6869: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6870: 	    push @parts, split(/\//,$1);
 6871: 	}
 6872: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6873: 	foreach my $part (@parts) {
 6874: 	    $path .= '/'.$part;
 6875: 	    if (!-e $path) {
 6876: 		mkdir($path,0770);
 6877: 	    }
 6878: 	}
 6879:     }
 6880:     open(FILE,">$file");
 6881:     print FILE $info;
 6882:     close(FILE);
 6883:     return 'ok';
 6884: }
 6885: 
 6886: sub tokenwrapper {
 6887:     my $uri=shift;
 6888:     $uri=~s|^http\://([^/]+)||;
 6889:     $uri=~s|^/||;
 6890:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6891:     my $token=$1;
 6892:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6893:     if ($udom && $uname && $file) {
 6894: 	$file=~s|(\?\.*)*$||;
 6895:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6896:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6897:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6898:                                '&tokenissued='.$perlvar{'lonHostID'};
 6899:     } else {
 6900:         return '/adm/notfound.html';
 6901:     }
 6902: }
 6903: 
 6904: sub getuploaded {
 6905:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6906:     $uri=~s/^\///;
 6907:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6908:     my $ua=new LWP::UserAgent;
 6909:     my $request=new HTTP::Request($reqtype,$uri);
 6910:     my $response=$ua->request($request);
 6911:     $$rtncode = $response->code;
 6912:     if (! $response->is_success()) {
 6913: 	return 'failed';
 6914:     }      
 6915:     if ($reqtype eq 'HEAD') {
 6916: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6917:     } elsif ($reqtype eq 'GET') {
 6918: 	$$info = $response->content;
 6919:     }
 6920:     return 'ok';
 6921: }
 6922: 
 6923: sub readfile {
 6924:     my $file = shift;
 6925:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6926:     my $fh;
 6927:     open($fh,"<$file");
 6928:     my $a='';
 6929:     while (<$fh>) { $a .=$_; }
 6930:     return $a;
 6931: }
 6932: 
 6933: sub filelocation {
 6934:     my ($dir,$file) = @_;
 6935:     my $location;
 6936:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6937: 
 6938:     if ($file =~ m-^/adm/-) {
 6939: 	$file=~s-^/adm/wrapper/-/-;
 6940: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6941:     }
 6942:     if ($file=~m:^/~:) { # is a contruction space reference
 6943:         $location = $file;
 6944:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6945:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6946: 	# is a correct contruction space reference
 6947:         $location = $file;
 6948:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6949:         my ($udom,$uname,$filename)=
 6950:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6951:         my $home=&homeserver($uname,$udom);
 6952:         my $is_me=0;
 6953:         my @ids=&current_machine_ids();
 6954:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6955:         if ($is_me) {
 6956:   	    $location=&propath($udom,$uname).
 6957:   	      '/userfiles/'.$filename;
 6958:         } else {
 6959:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6960:   	      $udom.'/'.$uname.'/'.$filename;
 6961:         }
 6962:     } else {
 6963:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6964:         $file=~s:^/res/:/:;
 6965:         if ( !( $file =~ m:^/:) ) {
 6966:             $location = $dir. '/'.$file;
 6967:         } else {
 6968:             $location = '/home/httpd/html/res'.$file;
 6969:         }
 6970:     }
 6971:     $location=~s://+:/:g; # remove duplicate /
 6972:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6973:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6974:     return $location;
 6975: }
 6976: 
 6977: sub hreflocation {
 6978:     my ($dir,$file)=@_;
 6979:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6980: 	$file=filelocation($dir,$file);
 6981:     } elsif ($file=~m-^/adm/-) {
 6982: 	$file=~s-^/adm/wrapper/-/-;
 6983: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6984:     }
 6985:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6986: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6987:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6988: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6989:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6990: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6991: 	    -/uploaded/$1/$2/-x;
 6992:     }
 6993:     return $file;
 6994: }
 6995: 
 6996: sub current_machine_domains {
 6997:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6998:     my @domains;
 6999:     while( my($id, $name) = each(%hostname)) {
 7000: #	&logthis("-$id-$name-$hostname-");
 7001: 	if ($hostname eq $name) {
 7002: 	    push(@domains,$hostdom{$id});
 7003: 	}
 7004:     }
 7005:     return @domains;
 7006: }
 7007: 
 7008: sub current_machine_ids {
 7009:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7010:     my @ids;
 7011:     while( my($id, $name) = each(%hostname)) {
 7012: #	&logthis("-$id-$name-$hostname-");
 7013: 	if ($hostname eq $name) {
 7014: 	    push(@ids,$id);
 7015: 	}
 7016:     }
 7017:     return @ids;
 7018: }
 7019: 
 7020: # ------------------------------------------------------------- Declutters URLs
 7021: 
 7022: sub declutter {
 7023:     my $thisfn=shift;
 7024:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7025:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7026:     $thisfn=~s/^\///;
 7027:     $thisfn=~s|^adm/wrapper/||;
 7028:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7029:     $thisfn=~s/^res\///;
 7030:     $thisfn=~s/\?.+$//;
 7031:     return $thisfn;
 7032: }
 7033: 
 7034: # ------------------------------------------------------------- Clutter up URLs
 7035: 
 7036: sub clutter {
 7037:     my $thisfn='/'.&declutter(shift);
 7038:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7039:        $thisfn='/res'.$thisfn; 
 7040:     }
 7041:     if ($thisfn !~m|/adm|) {
 7042: 	if ($thisfn =~ m|/ext/|) {
 7043: 	    $thisfn='/adm/wrapper'.$thisfn;
 7044: 	} else {
 7045: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7046: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7047: 	    if ($embstyle eq 'ssi'
 7048: 		|| ($embstyle eq 'hdn')
 7049: 		|| ($embstyle eq 'rat')
 7050: 		|| ($embstyle eq 'prv')
 7051: 		|| ($embstyle eq 'ign')) {
 7052: 		#do nothing with these
 7053: 	    } elsif (($embstyle eq 'img') 
 7054: 		|| ($embstyle eq 'emb')
 7055: 		|| ($embstyle eq 'wrp')) {
 7056: 		$thisfn='/adm/wrapper'.$thisfn;
 7057: 	    } elsif ($embstyle eq 'unk'
 7058: 		     && $thisfn!~/\.(sequence|page)$/) {
 7059: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7060: 	    } else {
 7061: #		&logthis("Got a blank emb style");
 7062: 	    }
 7063: 	}
 7064:     }
 7065:     return $thisfn;
 7066: }
 7067: 
 7068: sub freeze_escape {
 7069:     my ($value)=@_;
 7070:     if (ref($value)) {
 7071: 	$value=&nfreeze($value);
 7072: 	return '__FROZEN__'.&escape($value);
 7073:     }
 7074:     return &escape($value);
 7075: }
 7076: 
 7077: 
 7078: sub thaw_unescape {
 7079:     my ($value)=@_;
 7080:     if ($value =~ /^__FROZEN__/) {
 7081: 	substr($value,0,10,undef);
 7082: 	$value=&unescape($value);
 7083: 	return &thaw($value);
 7084:     }
 7085:     return &unescape($value);
 7086: }
 7087: 
 7088: sub correct_line_ends {
 7089:     my ($result)=@_;
 7090:     $$result =~s/\r\n/\n/mg;
 7091:     $$result =~s/\r/\n/mg;
 7092: }
 7093: # ================================================================ Main Program
 7094: 
 7095: sub goodbye {
 7096:    &logthis("Starting Shut down");
 7097: #not converted to using infrastruture and probably shouldn't be
 7098:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7099: #converted
 7100: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7101:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7102: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7103: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7104: #1.1 only
 7105: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7106: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7107: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7108: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7109:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7110:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7111:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7112:    &flushcourselogs();
 7113:    &logthis("Shutting down");
 7114: }
 7115: 
 7116: BEGIN {
 7117: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7118:     unless ($readit) {
 7119: {
 7120:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 7121:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 7122: 
 7123:     while (my $configline=<$config>) {
 7124:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 7125: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 7126:            chomp($varvalue);
 7127:            $perlvar{$varname}=$varvalue;
 7128:         }
 7129:     }
 7130:     close($config);
 7131: }
 7132: {
 7133:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 7134: 
 7135:     while (my $configline=<$config>) {
 7136:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 7137: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 7138:            chomp($varvalue);
 7139:            $perlvar{$varname}=$varvalue;
 7140:         }
 7141:     }
 7142:     close($config);
 7143: }
 7144: 
 7145: # ------------------------------------------------------------ Read domain file
 7146: {
 7147:     %domaindescription = ();
 7148:     %domain_auth_def = ();
 7149:     %domain_auth_arg_def = ();
 7150:     my $fh;
 7151:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7152:        while (<$fh>) {
 7153:            next if (/^(\#|\s*$)/);
 7154: #           next if /^\#/;
 7155:            chomp;
 7156:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7157: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 7158: 	   $domain_auth_def{$domain}=$def_auth;
 7159:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7160: 	   $domaindescription{$domain}=$domain_description;
 7161: 	   $domain_lang_def{$domain}=$def_lang;
 7162: 	   $domain_city{$domain}=$city;
 7163: 	   $domain_longi{$domain}=$longi;
 7164: 	   $domain_lati{$domain}=$lati;
 7165:            $domain_primary{$domain}=$primary;
 7166: 
 7167:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7168: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7169: 	}
 7170:     }
 7171:     close ($fh);
 7172: }
 7173: 
 7174: 
 7175: # ------------------------------------------------------------- Read hosts file
 7176: {
 7177:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7178: 
 7179:     while (my $configline=<$config>) {
 7180:        next if ($configline =~ /^(\#|\s*$)/);
 7181:        chomp($configline);
 7182:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7183:        $name=~s/\s//g;
 7184:        if ($id && $domain && $role && $name) {
 7185: 	 $hostname{$id}=$name;
 7186: 	 $hostdom{$id}=$domain;
 7187: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7188:        }
 7189:     }
 7190:     close($config);
 7191:     # FIXME: dev server don't want this, production servers _do_ want this
 7192:     #&get_iphost();
 7193: }
 7194: 
 7195: sub get_iphost {
 7196:     if (%iphost) { return %iphost; }
 7197:     my %name_to_ip;
 7198:     foreach my $id (keys(%hostname)) {
 7199: 	my $name=$hostname{$id};
 7200: 	my $ip;
 7201: 	if (!exists($name_to_ip{$name})) {
 7202: 	    $ip = gethostbyname($name);
 7203: 	    if (!$ip || length($ip) ne 4) {
 7204: 		&logthis("Skipping host $id name $name no IP found\n");
 7205: 		next;
 7206: 	    }
 7207: 	    $ip=inet_ntoa($ip);
 7208: 	    $name_to_ip{$name} = $ip;
 7209: 	} else {
 7210: 	    $ip = $name_to_ip{$name};
 7211: 	}
 7212: 	push(@{$iphost{$ip}},$id);
 7213:     }
 7214:     return %iphost;
 7215: }
 7216: 
 7217: # ------------------------------------------------------ Read spare server file
 7218: {
 7219:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7220: 
 7221:     while (my $configline=<$config>) {
 7222:        chomp($configline);
 7223:        if ($configline) {
 7224:           $spareid{$configline}=1;
 7225:        }
 7226:     }
 7227:     close($config);
 7228: }
 7229: # ------------------------------------------------------------ Read permissions
 7230: {
 7231:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7232: 
 7233:     while (my $configline=<$config>) {
 7234: 	chomp($configline);
 7235: 	if ($configline) {
 7236: 	    my ($role,$perm)=split(/ /,$configline);
 7237: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7238: 	}
 7239:     }
 7240:     close($config);
 7241: }
 7242: 
 7243: # -------------------------------------------- Read plain texts for permissions
 7244: {
 7245:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7246: 
 7247:     while (my $configline=<$config>) {
 7248: 	chomp($configline);
 7249: 	if ($configline) {
 7250: 	    my ($short,@plain)=split(/:/,$configline);
 7251:             %{$prp{$short}} = ();
 7252: 	    if (@plain > 0) {
 7253:                 $prp{$short}{'std'} = $plain[0];
 7254:                 for (my $i=1; $i<@plain; $i++) {
 7255:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7256:                 }
 7257:             }
 7258: 	}
 7259:     }
 7260:     close($config);
 7261: }
 7262: 
 7263: # ---------------------------------------------------------- Read package table
 7264: {
 7265:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7266: 
 7267:     while (my $configline=<$config>) {
 7268: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7269: 	chomp($configline);
 7270: 	my ($short,$plain)=split(/:/,$configline);
 7271: 	my ($pack,$name)=split(/\&/,$short);
 7272: 	if ($plain ne '') {
 7273: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7274: 	    $packagetab{$short}=$plain; 
 7275: 	}
 7276:     }
 7277:     close($config);
 7278: }
 7279: 
 7280: # ------------- set up temporary directory
 7281: {
 7282:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7283: 
 7284: }
 7285: 
 7286: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 7287: 
 7288: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7289: $dumpcount=0;
 7290: 
 7291: &logtouch();
 7292: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7293: $readit=1;
 7294:     {
 7295: 	use integer;
 7296: 	my $test=(2**32)+1;
 7297: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7298: 	&logthis(" Detected 64bit platform ($_64bit)");
 7299:     }
 7300: }
 7301: }
 7302: 
 7303: 1;
 7304: __END__
 7305: 
 7306: =pod
 7307: 
 7308: =head1 NAME
 7309: 
 7310: Apache::lonnet - Subroutines to ask questions about things in the network.
 7311: 
 7312: =head1 SYNOPSIS
 7313: 
 7314: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7315: 
 7316:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7317: 
 7318: Common parameters:
 7319: 
 7320: =over 4
 7321: 
 7322: =item *
 7323: 
 7324: $uname : an internal username (if $cname expecting a course Id specifically)
 7325: 
 7326: =item *
 7327: 
 7328: $udom : a domain (if $cdom expecting a course's domain specifically)
 7329: 
 7330: =item *
 7331: 
 7332: $symb : a resource instance identifier
 7333: 
 7334: =item *
 7335: 
 7336: $namespace : the name of a .db file that contains the data needed or
 7337: being set.
 7338: 
 7339: =back
 7340: 
 7341: =head1 OVERVIEW
 7342: 
 7343: lonnet provides subroutines which interact with the
 7344: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7345: about classes, users, and resources.
 7346: 
 7347: For many of these objects you can also use this to store data about
 7348: them or modify them in various ways.
 7349: 
 7350: =head2 Symbs
 7351: 
 7352: To identify a specific instance of a resource, LON-CAPA uses symbols
 7353: or "symbs"X<symb>. These identifiers are built from the URL of the
 7354: map, the resource number of the resource in the map, and the URL of
 7355: the resource itself. The latter is somewhat redundant, but might help
 7356: if maps change.
 7357: 
 7358: An example is
 7359: 
 7360:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7361: 
 7362: The respective map entry is
 7363: 
 7364:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7365:   title="Problem 2">
 7366:  </resource>
 7367: 
 7368: Symbs are used by the random number generator, as well as to store and
 7369: restore data specific to a certain instance of for example a problem.
 7370: 
 7371: =head2 Storing And Retrieving Data
 7372: 
 7373: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7374: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7375: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7376: is is the non-critical message twin of cstore. These functions are for
 7377: handlers to store a perl hash to a user's permanent data space in an
 7378: easy manner, and to retrieve it again on another call. It is expected
 7379: that a handler would use this once at the beginning to retrieve data,
 7380: and then again once at the end to send only the new data back.
 7381: 
 7382: The data is stored in the user's data directory on the user's
 7383: homeserver under the ID of the course.
 7384: 
 7385: The hash that is returned by restore will have all of the previous
 7386: value for all of the elements of the hash.
 7387: 
 7388: Example:
 7389: 
 7390:  #creating a hash
 7391:  my %hash;
 7392:  $hash{'foo'}='bar';
 7393: 
 7394:  #storing it
 7395:  &Apache::lonnet::cstore(\%hash);
 7396: 
 7397:  #changing a value
 7398:  $hash{'foo'}='notbar';
 7399: 
 7400:  #adding a new value
 7401:  $hash{'bar'}='foo';
 7402:  &Apache::lonnet::cstore(\%hash);
 7403: 
 7404:  #retrieving the hash
 7405:  my %history=&Apache::lonnet::restore();
 7406: 
 7407:  #print the hash
 7408:  foreach my $key (sort(keys(%history))) {
 7409:    print("\%history{$key} = $history{$key}");
 7410:  }
 7411: 
 7412: Will print out:
 7413: 
 7414:  %history{1:foo} = bar
 7415:  %history{1:keys} = foo:timestamp
 7416:  %history{1:timestamp} = 990455579
 7417:  %history{2:bar} = foo
 7418:  %history{2:foo} = notbar
 7419:  %history{2:keys} = foo:bar:timestamp
 7420:  %history{2:timestamp} = 990455580
 7421:  %history{bar} = foo
 7422:  %history{foo} = notbar
 7423:  %history{timestamp} = 990455580
 7424:  %history{version} = 2
 7425: 
 7426: Note that the special hash entries C<keys>, C<version> and
 7427: C<timestamp> were added to the hash. C<version> will be equal to the
 7428: total number of versions of the data that have been stored. The
 7429: C<timestamp> attribute will be the UNIX time the hash was
 7430: stored. C<keys> is available in every historical section to list which
 7431: keys were added or changed at a specific historical revision of a
 7432: hash.
 7433: 
 7434: B<Warning>: do not store the hash that restore returns directly. This
 7435: will cause a mess since it will restore the historical keys as if the
 7436: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7437: 
 7438: Calling convention:
 7439: 
 7440:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7441:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7442: 
 7443: For more detailed information, see lonnet specific documentation.
 7444: 
 7445: =head1 RETURN MESSAGES
 7446: 
 7447: =over 4
 7448: 
 7449: =item * B<con_lost>: unable to contact remote host
 7450: 
 7451: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7452: when the connection is brought back up
 7453: 
 7454: =item * B<con_failed>: unable to contact remote host and unable to save message
 7455: for later delivery
 7456: 
 7457: =item * B<error:>: an error a occured, a description of the error follows the :
 7458: 
 7459: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7460: that was requested
 7461: 
 7462: =back
 7463: 
 7464: =head1 PUBLIC SUBROUTINES
 7465: 
 7466: =head2 Session Environment Functions
 7467: 
 7468: =over 4
 7469: 
 7470: =item * 
 7471: X<appenv()>
 7472: B<appenv(%hash)>: the value of %hash is written to
 7473: the user envirnoment file, and will be restored for each access this
 7474: user makes during this session, also modifies the %env for the current
 7475: process
 7476: 
 7477: =item *
 7478: X<delenv()>
 7479: B<delenv($regexp)>: removes all items from the session
 7480: environment file that matches the regular expression in $regexp. The
 7481: values are also delted from the current processes %env.
 7482: 
 7483: =back
 7484: 
 7485: =head2 User Information
 7486: 
 7487: =over 4
 7488: 
 7489: =item *
 7490: X<queryauthenticate()>
 7491: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7492: authentication scheme
 7493: 
 7494: =item *
 7495: X<authenticate()>
 7496: B<authenticate($uname,$upass,$udom)>: try to
 7497: authenticate user from domain's lib servers (first use the current
 7498: one). C<$upass> should be the users password.
 7499: 
 7500: =item *
 7501: X<homeserver()>
 7502: B<homeserver($uname,$udom)>: find the server which has
 7503: the user's directory and files (there must be only one), this caches
 7504: the answer, and also caches if there is a borken connection.
 7505: 
 7506: =item *
 7507: X<idget()>
 7508: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7509: (IDs are a unique resource in a domain, there must be only 1 ID per
 7510: username, and only 1 username per ID in a specific domain) (returns
 7511: hash: id=>name,id=>name)
 7512: 
 7513: =item *
 7514: X<idrget()>
 7515: B<idrget($udom,@unames)>: find the IDs behind a list of
 7516: usernames (returns hash: name=>id,name=>id)
 7517: 
 7518: =item *
 7519: X<idput()>
 7520: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7521: 
 7522: =item *
 7523: X<rolesinit()>
 7524: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7525: 
 7526: =item *
 7527: X<getsection()>
 7528: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7529: course $cname, return section name/number or '' for "not in course"
 7530: and '-1' for "no section"
 7531: 
 7532: =item *
 7533: X<userenvironment()>
 7534: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7535: passed in @what from the requested user's environment, returns a hash
 7536: 
 7537: =back
 7538: 
 7539: =head2 User Roles
 7540: 
 7541: =over 4
 7542: 
 7543: =item *
 7544: 
 7545: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7546: actions
 7547:  F: full access
 7548:  U,I,K: authentication modes (cxx only)
 7549:  '': forbidden
 7550:  1: user needs to choose course
 7551:  2: browse allowed
 7552:  A: passphrase authentication needed
 7553: 
 7554: =item *
 7555: 
 7556: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7557: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7558: and course level
 7559: 
 7560: =item *
 7561: 
 7562: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7563: explanation of a user role term
 7564: 
 7565: =back
 7566: 
 7567: =head2 User Modification
 7568: 
 7569: =over 4
 7570: 
 7571: =item *
 7572: 
 7573: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7574: user for the level given by URL.  Optional start and end dates (leave empty
 7575: string or zero for "no date")
 7576: 
 7577: =item *
 7578: 
 7579: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7580: change a users, password, possible return values are: ok,
 7581: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7582: refused
 7583: 
 7584: =item *
 7585: 
 7586: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7587: 
 7588: =item *
 7589: 
 7590: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7591: modify user
 7592: 
 7593: =item *
 7594: 
 7595: modifystudent
 7596: 
 7597: modify a students enrollment and identification information.
 7598: The course id is resolved based on the current users environment.  
 7599: This means the envoking user must be a course coordinator or otherwise
 7600: associated with a course.
 7601: 
 7602: This call is essentially a wrapper for lonnet::modifyuser and
 7603: lonnet::modify_student_enrollment
 7604: 
 7605: Inputs: 
 7606: 
 7607: =over 4
 7608: 
 7609: =item B<$udom> Students loncapa domain
 7610: 
 7611: =item B<$uname> Students loncapa login name
 7612: 
 7613: =item B<$uid> Students id/student number
 7614: 
 7615: =item B<$umode> Students authentication mode
 7616: 
 7617: =item B<$upass> Students password
 7618: 
 7619: =item B<$first> Students first name
 7620: 
 7621: =item B<$middle> Students middle name
 7622: 
 7623: =item B<$last> Students last name
 7624: 
 7625: =item B<$gene> Students generation
 7626: 
 7627: =item B<$usec> Students section in course
 7628: 
 7629: =item B<$end> Unix time of the roles expiration
 7630: 
 7631: =item B<$start> Unix time of the roles start date
 7632: 
 7633: =item B<$forceid> If defined, allow $uid to be changed
 7634: 
 7635: =item B<$desiredhome> server to use as home server for student
 7636: 
 7637: =back
 7638: 
 7639: =item *
 7640: 
 7641: modify_student_enrollment
 7642: 
 7643: Change a students enrollment status in a class.  The environment variable
 7644: 'role.request.course' must be defined for this function to proceed.
 7645: 
 7646: Inputs:
 7647: 
 7648: =over 4
 7649: 
 7650: =item $udom, students domain
 7651: 
 7652: =item $uname, students name
 7653: 
 7654: =item $uid, students user id
 7655: 
 7656: =item $first, students first name
 7657: 
 7658: =item $middle
 7659: 
 7660: =item $last
 7661: 
 7662: =item $gene
 7663: 
 7664: =item $usec
 7665: 
 7666: =item $end
 7667: 
 7668: =item $start
 7669: 
 7670: =back
 7671: 
 7672: 
 7673: =item *
 7674: 
 7675: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7676: custom role; give a custom role to a user for the level given by URL.  Specify
 7677: name and domain of role author, and role name
 7678: 
 7679: =item *
 7680: 
 7681: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7682: 
 7683: =item *
 7684: 
 7685: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7686: 
 7687: =back
 7688: 
 7689: =head2 Course Infomation
 7690: 
 7691: =over 4
 7692: 
 7693: =item *
 7694: 
 7695: coursedescription($courseid) : returns a hash of information about the
 7696: specified course id, including all environment settings for the
 7697: course, the description of the course will be in the hash under the
 7698: key 'description'
 7699: 
 7700: =item *
 7701: 
 7702: resdata($name,$domain,$type,@which) : request for current parameter
 7703: setting for a specific $type, where $type is either 'course' or 'user',
 7704: @what should be a list of parameters to ask about. This routine caches
 7705: answers for 5 minutes.
 7706: 
 7707: =back
 7708: 
 7709: =head2 Course Modification
 7710: 
 7711: =over 4
 7712: 
 7713: =item *
 7714: 
 7715: writecoursepref($courseid,%prefs) : write preferences (environment
 7716: database) for a course
 7717: 
 7718: =item *
 7719: 
 7720: createcourse($udom,$description,$url) : make/modify course
 7721: 
 7722: =back
 7723: 
 7724: =head2 Resource Subroutines
 7725: 
 7726: =over 4
 7727: 
 7728: =item *
 7729: 
 7730: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7731: 
 7732: =item *
 7733: 
 7734: repcopy($filename) : subscribes to the requested file, and attempts to
 7735: replicate from the owning library server, Might return
 7736: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7737: 'bad_request', also attempts to grab the metadata for the
 7738: resource. Expects the local filesystem pathname
 7739: (/home/httpd/html/res/....)
 7740: 
 7741: =back
 7742: 
 7743: =head2 Resource Information
 7744: 
 7745: =over 4
 7746: 
 7747: =item *
 7748: 
 7749: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7750: a vairety of different possible values, $varname should be a request
 7751: string, and the other parameters can be used to specify who and what
 7752: one is asking about.
 7753: 
 7754: Possible values for $varname are environment.lastname (or other item
 7755: from the envirnment hash), user.name (or someother aspect about the
 7756: user), resource.0.maxtries (or some other part and parameter of a
 7757: resource)
 7758: 
 7759: =item *
 7760: 
 7761: directcondval($number) : get current value of a condition; reads from a state
 7762: string
 7763: 
 7764: =item *
 7765: 
 7766: condval($condidx) : value of condition index based on state
 7767: 
 7768: =item *
 7769: 
 7770: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7771: resource's metadata, $what should be either a specific key, or either
 7772: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7773: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7774: 
 7775: this function automatically caches all requests
 7776: 
 7777: =item *
 7778: 
 7779: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7780: network of library servers; returns file handle of where SQL and regex results
 7781: will be stored for query
 7782: 
 7783: =item *
 7784: 
 7785: symbread($filename) : return symbolic list entry (filename argument optional);
 7786: returns the data handle
 7787: 
 7788: =item *
 7789: 
 7790: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7791: a possible symb for the URL in $thisfn, and if is an encryypted
 7792: resource that the user accessed using /enc/ returns a 1 on success, 0
 7793: on failure, user must be in a course, as it assumes the existance of
 7794: the course initial hash, and uses $env('request.course.id'}
 7795: 
 7796: 
 7797: =item *
 7798: 
 7799: symbclean($symb) : removes versions numbers from a symb, returns the
 7800: cleaned symb
 7801: 
 7802: =item *
 7803: 
 7804: is_on_map($uri) : checks if the $uri is somewhere on the current
 7805: course map, user must be in a course for it to work.
 7806: 
 7807: =item *
 7808: 
 7809: numval($salt) : return random seed value (addend for rndseed)
 7810: 
 7811: =item *
 7812: 
 7813: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7814: a random seed, all arguments are optional, if they aren't sent it uses the
 7815: environment to derive them. Note: if symb isn't sent and it can't get one
 7816: from &symbread it will use the current time as its return value
 7817: 
 7818: =item *
 7819: 
 7820: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7821: unfakeable, receipt
 7822: 
 7823: =item *
 7824: 
 7825: receipt() : API to ireceipt working off of env values; given out to users
 7826: 
 7827: =item *
 7828: 
 7829: countacc($url) : count the number of accesses to a given URL
 7830: 
 7831: =item *
 7832: 
 7833: 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
 7834: 
 7835: =item *
 7836: 
 7837: 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)
 7838: 
 7839: =item *
 7840: 
 7841: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7842: 
 7843: =item *
 7844: 
 7845: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7846: forcing spreadsheet to reevaluate the resource scores next time.
 7847: 
 7848: =back
 7849: 
 7850: =head2 Storing/Retreiving Data
 7851: 
 7852: =over 4
 7853: 
 7854: =item *
 7855: 
 7856: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7857: for this url; hashref needs to be given and should be a \%hashname; the
 7858: remaining args aren't required and if they aren't passed or are '' they will
 7859: be derived from the env
 7860: 
 7861: =item *
 7862: 
 7863: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7864: uses critical subroutine
 7865: 
 7866: =item *
 7867: 
 7868: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7869: all args are optional
 7870: 
 7871: =item *
 7872: 
 7873: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7874: dumps the complete (or key matching regexp) namespace into a hash
 7875: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7876: normally &store()ed into
 7877: 
 7878: $range should be either an integer '100' (give me the first 100
 7879:                                            matching records)
 7880:               or be  two integers sperated by a - with no spaces
 7881:                  '30-50' (give me the 30th through the 50th matching
 7882:                           records)
 7883: 
 7884: 
 7885: =item *
 7886: 
 7887: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7888: replaces a &store() version of data with a replacement set of data
 7889: for a particular resource in a namespace passed in the $storehash hash 
 7890: reference
 7891: 
 7892: =item *
 7893: 
 7894: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7895: works very similar to store/cstore, but all data is stored in a
 7896: temporary location and can be reset using tmpreset, $storehash should
 7897: be a hash reference, returns nothing on success
 7898: 
 7899: =item *
 7900: 
 7901: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7902: similar to restore, but all data is stored in a temporary location and
 7903: can be reset using tmpreset. Returns a hash of values on success,
 7904: error string otherwise.
 7905: 
 7906: =item *
 7907: 
 7908: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7909: deltes all keys for $symb form the temporary storage hash.
 7910: 
 7911: =item *
 7912: 
 7913: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7914: reference filled in from namesp ($udom and $uname are optional)
 7915: 
 7916: =item *
 7917: 
 7918: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7919: namesp ($udom and $uname are optional)
 7920: 
 7921: =item *
 7922: 
 7923: dump($namespace,$udom,$uname,$regexp,$range) : 
 7924: dumps the complete (or key matching regexp) namespace into a hash
 7925: ($udom, $uname, $regexp, $range are optional)
 7926: 
 7927: $range should be either an integer '100' (give me the first 100
 7928:                                            matching records)
 7929:               or be  two integers sperated by a - with no spaces
 7930:                  '30-50' (give me the 30th through the 50th matching
 7931:                           records)
 7932: =item *
 7933: 
 7934: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7935: $store can be a scalar, an array reference, or if the amount to be 
 7936: incremented is > 1, a hash reference.
 7937: 
 7938: ($udom and $uname are optional)
 7939: 
 7940: =item *
 7941: 
 7942: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7943: ($udom and $uname are optional)
 7944: 
 7945: =item *
 7946: 
 7947: cput($namespace,$storehash,$udom,$uname) : critical put
 7948: ($udom and $uname are optional)
 7949: 
 7950: =item *
 7951: 
 7952: newput($namespace,$storehash,$udom,$uname) :
 7953: 
 7954: Attempts to store the items in the $storehash, but only if they don't
 7955: currently exist, if this succeeds you can be certain that you have 
 7956: successfully created a new key value pair in the $namespace db.
 7957: 
 7958: 
 7959: Args:
 7960:  $namespace: name of database to store values to
 7961:  $storehash: hashref to store to the db
 7962:  $udom: (optional) domain of user containing the db
 7963:  $uname: (optional) name of user caontaining the db
 7964: 
 7965: Returns:
 7966:  'ok' -> succeeded in storing all keys of $storehash
 7967:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 7968:                         least <key> already existed in the db (other
 7969:                         requested keys may also already exist)
 7970:  'error: <msg>' -> unable to tie the DB or other erorr occured
 7971:  'con_lost' -> unable to contact request server
 7972:  'refused' -> action was not allowed by remote machine
 7973: 
 7974: 
 7975: =item *
 7976: 
 7977: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7978: reference filled in from namesp (encrypts the return communication)
 7979: ($udom and $uname are optional)
 7980: 
 7981: =item *
 7982: 
 7983: log($udom,$name,$home,$message) : write to permanent log for user; use
 7984: critical subroutine
 7985: 
 7986: =back
 7987: 
 7988: =head2 Network Status Functions
 7989: 
 7990: =over 4
 7991: 
 7992: =item *
 7993: 
 7994: dirlist($uri) : return directory list based on URI
 7995: 
 7996: =item *
 7997: 
 7998: spareserver() : find server with least workload from spare.tab
 7999: 
 8000: =back
 8001: 
 8002: =head2 Apache Request
 8003: 
 8004: =over 4
 8005: 
 8006: =item *
 8007: 
 8008: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8009: localhost, posts hash
 8010: 
 8011: =back
 8012: 
 8013: =head2 Data to String to Data
 8014: 
 8015: =over 4
 8016: 
 8017: =item *
 8018: 
 8019: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8020: and '&' separators, supports elements that are arrayrefs and hashrefs
 8021: 
 8022: =item *
 8023: 
 8024: hashref2str($hashref) : convert a hashref into a string complete with
 8025: escaping and '=' and '&' separators, supports elements that are
 8026: arrayrefs and hashrefs
 8027: 
 8028: =item *
 8029: 
 8030: arrayref2str($arrayref) : convert an arrayref into a string complete
 8031: with escaping and '&' separators, supports elements that are arrayrefs
 8032: and hashrefs
 8033: 
 8034: =item *
 8035: 
 8036: str2hash($string) : convert string to hash using unescaping and
 8037: splitting on '=' and '&', supports elements that are arrayrefs and
 8038: hashrefs
 8039: 
 8040: =item *
 8041: 
 8042: str2array($string) : convert string to hash using unescaping and
 8043: splitting on '&', supports elements that are arrayrefs and hashrefs
 8044: 
 8045: =back
 8046: 
 8047: =head2 Logging Routines
 8048: 
 8049: =over 4
 8050: 
 8051: These routines allow one to make log messages in the lonnet.log and
 8052: lonnet.perm logfiles.
 8053: 
 8054: =item *
 8055: 
 8056: logtouch() : make sure the logfile, lonnet.log, exists
 8057: 
 8058: =item *
 8059: 
 8060: logthis() : append message to the normal lonnet.log file, it gets
 8061: preiodically rolled over and deleted.
 8062: 
 8063: =item *
 8064: 
 8065: logperm() : append a permanent message to lonnet.perm.log, this log
 8066: file never gets deleted by any automated portion of the system, only
 8067: messages of critical importance should go in here.
 8068: 
 8069: =back
 8070: 
 8071: =head2 General File Helper Routines
 8072: 
 8073: =over 4
 8074: 
 8075: =item *
 8076: 
 8077: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8078: (a) files in /uploaded
 8079:   (i) If a local copy of the file exists - 
 8080:       compares modification date of local copy with last-modified date for 
 8081:       definitive version stored on home server for course. If local copy is 
 8082:       stale, requests a new version from the home server and stores it. 
 8083:       If the original has been removed from the home server, then local copy 
 8084:       is unlinked.
 8085:   (ii) If local copy does not exist -
 8086:       requests the file from the home server and stores it. 
 8087:   
 8088:   If $caller is 'uploadrep':  
 8089:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8090:     for request for files originally uploaded via DOCS. 
 8091:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8092:   
 8093:   Otherwise:
 8094:      This indicates a call from the content generation phase of the request.
 8095:      -  returns the entire contents of the file or -1.
 8096:      
 8097: (b) files in /res
 8098:    - returns the entire contents of a file or -1; 
 8099:    it properly subscribes to and replicates the file if neccessary.
 8100: 
 8101: 
 8102: =item *
 8103: 
 8104: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8105:                   reference
 8106: 
 8107: returns either a stat() list of data about the file or an empty list
 8108: if the file doesn't exist or couldn't find out about it (connection
 8109: problems or user unknown)
 8110: 
 8111: =item *
 8112: 
 8113: filelocation($dir,$file) : returns file system location of a file
 8114: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8115: directory that relative $file lookups are to looked in ($dir of /a/dir
 8116: and a file of ../bob will become /a/bob)
 8117: 
 8118: =item *
 8119: 
 8120: hreflocation($dir,$file) : returns file system location or a URL; same as
 8121: filelocation except for hrefs
 8122: 
 8123: =item *
 8124: 
 8125: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8126: 
 8127: =back
 8128: 
 8129: =head2 Usererfile file routines (/uploaded*)
 8130: 
 8131: =over 4
 8132: 
 8133: =item *
 8134: 
 8135: userfileupload(): main rotine for putting a file in a user or course's
 8136:                   filespace, arguments are,
 8137: 
 8138:  formname - required - this is the name of the element in $env where the
 8139:            filename, and the contents of the file to create/modifed exist
 8140:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8141:            contents of the file is located in $env{'form.'.$formname}
 8142:  coursedoc - if true, store the file in the course of the active role
 8143:              of the current user
 8144:  subdir - required - subdirectory to put the file in under ../userfiles/
 8145:          if undefined, it will be placed in "unknown"
 8146: 
 8147:  (This routine calls clean_filename() to remove any dangerous
 8148:  characters from the filename, and then calls finuserfileupload() to
 8149:  complete the transaction)
 8150: 
 8151:  returns either the url of the uploaded file (/uploaded/....) if successful
 8152:  and /adm/notfound.html if unsuccessful
 8153: 
 8154: =item *
 8155: 
 8156: clean_filename(): routine for cleaing a filename up for storage in
 8157:                  userfile space, argument is:
 8158: 
 8159:  filename - proposed filename
 8160: 
 8161: returns: the new clean filename
 8162: 
 8163: =item *
 8164: 
 8165: finishuserfileupload(): routine that creaes and sends the file to
 8166: userspace, probably shouldn't be called directly
 8167: 
 8168:   docuname: username or courseid of destination for the file
 8169:   docudom: domain of user/course of destination for the file
 8170:   formname: same as for userfileupload()
 8171:   fname: filename (inculding subdirectories) for the file
 8172: 
 8173:  returns either the url of the uploaded file (/uploaded/....) if successful
 8174:  and /adm/notfound.html if unsuccessful
 8175: 
 8176: =item *
 8177: 
 8178: renameuserfile(): renames an existing userfile to a new name
 8179: 
 8180:   Args:
 8181:    docuname: username or courseid of destination for the file
 8182:    docudom: domain of user/course of destination for the file
 8183:    old: current file name (including any subdirs under userfiles)
 8184:    new: desired file name (including any subdirs under userfiles)
 8185: 
 8186: =item *
 8187: 
 8188: mkdiruserfile(): creates a directory is a userfiles dir
 8189: 
 8190:   Args:
 8191:    docuname: username or courseid of destination for the file
 8192:    docudom: domain of user/course of destination for the file
 8193:    dir: dir to create (including any subdirs under userfiles)
 8194: 
 8195: =item *
 8196: 
 8197: removeuserfile(): removes a file that exists in userfiles
 8198: 
 8199:   Args:
 8200:    docuname: username or courseid of destination for the file
 8201:    docudom: domain of user/course of destination for the file
 8202:    fname: filname to delete (including any subdirs under userfiles)
 8203: 
 8204: =item *
 8205: 
 8206: removeuploadedurl(): convience function for removeuserfile()
 8207: 
 8208:   Args:
 8209:    url:  a full /uploaded/... url to delete
 8210: 
 8211: =item * 
 8212: 
 8213: get_portfile_permissions():
 8214:   Args:
 8215:     domain: domain of user or course contain the portfolio files
 8216:     user: name of user or num of course contain the portfolio files
 8217:   Returns:
 8218:     hashref of a dump of the proper file_permissions.db
 8219:    
 8220: 
 8221: =item * 
 8222: 
 8223: get_access_controls():
 8224: 
 8225: Args:
 8226:   current_permissions: the hash ref returned from get_portfile_permissions()
 8227:   group: (optional) the group you want the files associated with
 8228:   file: (optional) the file you want access info on
 8229: 
 8230: Returns:
 8231:     a hash (keys are file names) of hashes containing
 8232:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8233:         values are XML containing access control settings (see below) 
 8234: 
 8235: Internal notes:
 8236: 
 8237:  access controls are stored in file_permissions.db as key=value pairs.
 8238:     key -> path to file/file_name\0uniqueID:scope_end_start
 8239:         where scope -> public,guest,course,group,domains or users.
 8240:               end -> UNIX time for end of access (0 -> no end date)
 8241:               start -> UNIX time for start of access
 8242: 
 8243:     value -> XML description of access control
 8244:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8245:             <start></start>
 8246:             <end></end>
 8247: 
 8248:             <password></password>  for scope type = guest
 8249: 
 8250:             <domain></domain>     for scope type = course or group
 8251:             <number></number>
 8252:             <roles id="">
 8253:              <role></role>
 8254:              <access></access>
 8255:              <section></section>
 8256:              <group></group>
 8257:             </roles>
 8258: 
 8259:             <dom></dom>         for scope type = domains
 8260: 
 8261:             <users>             for scope type = users
 8262:              <user>
 8263:               <uname></uname>
 8264:               <udom></udom>
 8265:              </user>
 8266:             </users>
 8267:            </scope> 
 8268:               
 8269:  Access data is also aggregated for each file in an additional key=value pair:
 8270:  key -> path to file/file_name\0accesscontrol 
 8271:  value -> reference to hash
 8272:           hash contains key = value pairs
 8273:           where key = uniqueID:scope_end_start
 8274:                 value = UNIX time record was last updated
 8275: 
 8276:           Used to improve speed of look-ups of access controls for each file.  
 8277:  
 8278:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8279: 
 8280: modify_access_controls():
 8281: 
 8282: Modifies access controls for a portfolio file
 8283: Args
 8284: 1. file name
 8285: 2. reference to hash of required changes,
 8286: 3. domain
 8287: 4. username
 8288:   where domain,username are the domain of the portfolio owner 
 8289:   (either a user or a course) 
 8290: 
 8291: Returns:
 8292: 1. result of additions or updates ('ok' or 'error', with error message). 
 8293: 2. result of deletions ('ok' or 'error', with error message).
 8294: 3. reference to hash of any new or updated access controls.
 8295: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8296:    key = integer (inbound ID)
 8297:    value = uniqueID  
 8298: 
 8299: =back
 8300: 
 8301: =head2 HTTP Helper Routines
 8302: 
 8303: =over 4
 8304: 
 8305: =item *
 8306: 
 8307: escape() : unpack non-word characters into CGI-compatible hex codes
 8308: 
 8309: =item *
 8310: 
 8311: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8312: 
 8313: =back
 8314: 
 8315: =head1 PRIVATE SUBROUTINES
 8316: 
 8317: =head2 Underlying communication routines (Shouldn't call)
 8318: 
 8319: =over 4
 8320: 
 8321: =item *
 8322: 
 8323: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8324: 
 8325: =item *
 8326: 
 8327: reply() : uses subreply to send a message to remote machine, logs all failures
 8328: 
 8329: =item *
 8330: 
 8331: critical() : passes a critical message to another server; if cannot
 8332: get through then place message in connection buffer directory and
 8333: returns con_delayed, if incapable of saving message, returns
 8334: con_failed
 8335: 
 8336: =item *
 8337: 
 8338: reconlonc() : tries to reconnect lonc client processes.
 8339: 
 8340: =back
 8341: 
 8342: =head2 Resource Access Logging
 8343: 
 8344: =over 4
 8345: 
 8346: =item *
 8347: 
 8348: flushcourselogs() : flush (save) buffer logs and access logs
 8349: 
 8350: =item *
 8351: 
 8352: courselog($what) : save message for course in hash
 8353: 
 8354: =item *
 8355: 
 8356: courseacclog($what) : save message for course using &courselog().  Perform
 8357: special processing for specific resource types (problems, exams, quizzes, etc).
 8358: 
 8359: =item *
 8360: 
 8361: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8362: as a PerlChildExitHandler
 8363: 
 8364: =back
 8365: 
 8366: =head2 Other
 8367: 
 8368: =over 4
 8369: 
 8370: =item *
 8371: 
 8372: symblist($mapname,%newhash) : update symbolic storage links
 8373: 
 8374: =back
 8375: 
 8376: =cut

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