File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.786: download - view: text, annotated - select for diffs
Thu Sep 28 21:24:56 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- need to wait for lock on session env as there could be contention
- only do the conversion if it looks like its a text session env

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.786 2006/09/28 21:24:56 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: sub convert_and_load_session_env {
  296:     my ($lonidsdir,$handle)=@_;
  297:     my @profile;
  298:     {
  299: 	open(my $idf,"$lonidsdir/$handle.id");
  300: 	flock($idf,LOCK_SH);
  301: 	@profile=<$idf>;
  302: 	close($idf);
  303:     }
  304:     my %temp_env;
  305:     foreach my $line (@profile) {
  306: 	if ($line !~ m/=/) {
  307: 	    return 0;
  308: 	}
  309: 	chomp($line);
  310: 	my ($envname,$envvalue)=split(/=/,$line,2);
  311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  312:     }
  313:     unlink("$lonidsdir/$handle.id");
  314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  315: 	    0640)) {
  316: 	%disk_env = %temp_env;
  317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  318: 	untie(%disk_env);
  319:     }
  320:     return 1;
  321: }
  322: 
  323: # ------------------------------------------- Transfer profile into environment
  324: my $env_loaded;
  325: sub transfer_profile_to_env {
  326:     if ($env_loaded) { return; } 
  327: 
  328:     my ($lonidsdir,$handle)=@_;
  329:     if (!defined($lonidsdir)) {
  330: 	$lonidsdir = $perlvar{'lonIDsDir'};
  331:     }
  332:     if (!defined($handle)) {
  333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  334:     }
  335: 
  336:     my $convert;
  337:     {
  338:     	open(my $idf,"$lonidsdir/$handle.id");
  339: 	flock($idf,LOCK_SH);
  340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  341: 		&GDBM_READER(),0640)) {
  342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  343: 	    untie(%disk_env);
  344: 	} else {
  345: 	    $convert = 1;
  346: 	}
  347:     }
  348:     if ($convert) {
  349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  350: 	    &logthis("Failed to load session, or convert session.");
  351: 	}
  352:     }
  353: 
  354:     my %remove;
  355:     while ( my $envname = each(%env) ) {
  356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  357:             if ($time < time-300) {
  358:                 $remove{$key}++;
  359:             }
  360:         }
  361:     }
  362: 
  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  364:     $env_loaded=1;
  365:     foreach my $expired_key (keys(%remove)) {
  366:         &delenv($expired_key);
  367:     }
  368: }
  369: 
  370: # ---------------------------------------------------------- Append Environment
  371: 
  372: sub appenv {
  373:     my %newenv=@_;
  374:     foreach my $key (keys(%newenv)) {
  375: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  376:             &logthis("<font color=\"blue\">WARNING: ".
  377:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  378:                 .'</font>');
  379: 	    delete($newenv{$key});
  380:         } else {
  381:             $env{$key}=$newenv{$key};
  382:         }
  383:     }
  384:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
  385: 	    0640)) {
  386: 	while (my ($key,$value) = each(%newenv)) {
  387: 	    $disk_env{$key} = $value;
  388: 	}
  389: 	untie(%disk_env);
  390:     }
  391:     return 'ok';
  392: }
  393: # ----------------------------------------------------- Delete from Environment
  394: 
  395: sub delenv {
  396:     my $delthis=shift;
  397:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  398:         &logthis("<font color=\"blue\">WARNING: ".
  399:                 "Attempt to delete from environment ".$delthis);
  400:         return 'error';
  401:     }
  402:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
  403: 	    0640)) {
  404: 	foreach my $key (keys(%disk_env)) {
  405: 	    if ($key=~/^$delthis/) { 
  406:                 delete($env{$key});
  407:                 delete($disk_env{$key});
  408:             }
  409: 	}
  410: 	untie(%disk_env);
  411:     }
  412:     return 'ok';
  413: }
  414: 
  415: # ------------------------------------------ Find out current server userload
  416: # there is a copy in lond
  417: sub userload {
  418:     my $numusers=0;
  419:     {
  420: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  421: 	my $filename;
  422: 	my $curtime=time;
  423: 	while ($filename=readdir(LONIDS)) {
  424: 	    if ($filename eq '.' || $filename eq '..') {next;}
  425: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  426: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  427: 	}
  428: 	closedir(LONIDS);
  429:     }
  430:     my $userloadpercent=0;
  431:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  432:     if ($maxuserload) {
  433: 	$userloadpercent=100*$numusers/$maxuserload;
  434:     }
  435:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  436:     return $userloadpercent;
  437: }
  438: 
  439: # ------------------------------------------ Fight off request when overloaded
  440: 
  441: sub overloaderror {
  442:     my ($r,$checkserver)=@_;
  443:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  444:     my $loadavg;
  445:     if ($checkserver eq $perlvar{'lonHostID'}) {
  446:        open(my $loadfile,'/proc/loadavg');
  447:        $loadavg=<$loadfile>;
  448:        $loadavg =~ s/\s.*//g;
  449:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  450:        close($loadfile);
  451:     } else {
  452:        $loadavg=&reply('load',$checkserver);
  453:     }
  454:     my $overload=$loadavg-100;
  455:     if ($overload>0) {
  456: 	$r->err_headers_out->{'Retry-After'}=$overload;
  457:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  458:         return 413;
  459:     }    
  460:     return '';
  461: }
  462: 
  463: # ------------------------------ Find server with least workload from spare.tab
  464: 
  465: sub spareserver {
  466:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  467:     my $spare_server;
  468:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  469:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  470:                                                      :  $userloadpercent;
  471:     
  472:     foreach my $try_server (@{ $spareid{'primary'} }) {
  473: 	($spare_server, $lowest_load) =
  474: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  475:     }
  476: 
  477:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  478: 
  479:     if (!$found_server) {
  480: 	foreach my $try_server (@{ $spareid{'default'} }) {
  481: 	    ($spare_server, $lowest_load) =
  482: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  483: 	}
  484:     }
  485: 
  486:     if (!$want_server_name) {
  487: 	$spare_server="http://$hostname{$spare_server}";
  488:     }
  489:     return $spare_server;
  490: }
  491: 
  492: sub compare_server_load {
  493:     my ($try_server, $spare_server, $lowest_load) = @_;
  494: 
  495:     my $loadans     = &reply('load',    $try_server);
  496:     my $userloadans = &reply('userload',$try_server);
  497: 
  498:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  499: 	next; #didn't get a number from the server
  500:     }
  501: 
  502:     my $load;
  503:     if ($loadans =~ /\d/) {
  504: 	if ($userloadans =~ /\d/) {
  505: 	    #both are numbers, pick the bigger one
  506: 	    $load = ($loadans > $userloadans) ? $loadans 
  507: 		                              : $userloadans;
  508: 	} else {
  509: 	    $load = $loadans;
  510: 	}
  511:     } else {
  512: 	$load = $userloadans;
  513:     }
  514: 
  515:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  516: 	$spare_server = $try_server;
  517: 	$lowest_load  = $load;
  518:     }
  519:     return ($spare_server,$lowest_load);
  520: }
  521: # --------------------------------------------- Try to change a user's password
  522: 
  523: sub changepass {
  524:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  525:     $currentpass = &escape($currentpass);
  526:     $newpass     = &escape($newpass);
  527:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  528: 		       $server);
  529:     if (! $answer) {
  530: 	&logthis("No reply on password change request to $server ".
  531: 		 "by $uname in domain $udom.");
  532:     } elsif ($answer =~ "^ok") {
  533:         &logthis("$uname in $udom successfully changed their password ".
  534: 		 "on $server.");
  535:     } elsif ($answer =~ "^pwchange_failure") {
  536: 	&logthis("$uname in $udom was unable to change their password ".
  537: 		 "on $server.  The action was blocked by either lcpasswd ".
  538: 		 "or pwchange");
  539:     } elsif ($answer =~ "^non_authorized") {
  540:         &logthis("$uname in $udom did not get their password correct when ".
  541: 		 "attempting to change it on $server.");
  542:     } elsif ($answer =~ "^auth_mode_error") {
  543:         &logthis("$uname in $udom attempted to change their password despite ".
  544: 		 "not being locally or internally authenticated on $server.");
  545:     } elsif ($answer =~ "^unknown_user") {
  546:         &logthis("$uname in $udom attempted to change their password ".
  547: 		 "on $server but were unable to because $server is not ".
  548: 		 "their home server.");
  549:     } elsif ($answer =~ "^refused") {
  550: 	&logthis("$server refused to change $uname in $udom password because ".
  551: 		 "it was sent an unencrypted request to change the password.");
  552:     }
  553:     return $answer;
  554: }
  555: 
  556: # ----------------------- Try to determine user's current authentication scheme
  557: 
  558: sub queryauthenticate {
  559:     my ($uname,$udom)=@_;
  560:     my $uhome=&homeserver($uname,$udom);
  561:     if (!$uhome) {
  562: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  563: 	return 'no_host';
  564:     }
  565:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  566:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  567: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  568:     }
  569:     return $answer;
  570: }
  571: 
  572: # --------- Try to authenticate user from domain's lib servers (first this one)
  573: 
  574: sub authenticate {
  575:     my ($uname,$upass,$udom)=@_;
  576:     $upass=escape($upass);
  577:     $uname=~s/\W//g;
  578:     my $uhome=&homeserver($uname,$udom);
  579:     if (!$uhome) {
  580: 	&logthis("User $uname at $udom is unknown in authenticate");
  581: 	return 'no_host';
  582:     }
  583:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  584:     if ($answer eq 'authorized') {
  585: 	&logthis("User $uname at $udom authorized by $uhome"); 
  586: 	return $uhome; 
  587:     }
  588:     if ($answer eq 'non_authorized') {
  589: 	&logthis("User $uname at $udom rejected by $uhome");
  590: 	return 'no_host'; 
  591:     }
  592:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  593:     return 'no_host';
  594: }
  595: 
  596: # ---------------------- Find the homebase for a user from domain's lib servers
  597: 
  598: my %homecache;
  599: sub homeserver {
  600:     my ($uname,$udom,$ignoreBadCache)=@_;
  601:     my $index="$uname:$udom";
  602: 
  603:     if (exists($homecache{$index})) { return $homecache{$index}; }
  604:     my $tryserver;
  605:     foreach $tryserver (keys %libserv) {
  606:         next if ($ignoreBadCache ne 'true' && 
  607: 		 exists($badServerCache{$tryserver}));
  608: 	if ($hostdom{$tryserver} eq $udom) {
  609:            my $answer=reply("home:$udom:$uname",$tryserver);
  610:            if ($answer eq 'found') { 
  611: 	       return $homecache{$index}=$tryserver;
  612:            } elsif ($answer eq 'no_host') {
  613: 	       $badServerCache{$tryserver}=1;
  614:            }
  615:        }
  616:     }    
  617:     return 'no_host';
  618: }
  619: 
  620: # ------------------------------------- Find the usernames behind a list of IDs
  621: 
  622: sub idget {
  623:     my ($udom,@ids)=@_;
  624:     my %returnhash=();
  625:     
  626:     my $tryserver;
  627:     foreach $tryserver (keys %libserv) {
  628:        if ($hostdom{$tryserver} eq $udom) {
  629: 	  my $idlist=join('&',@ids);
  630:           $idlist=~tr/A-Z/a-z/; 
  631: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  632:           my @answer=();
  633:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  634: 	      @answer=split(/\&/,$reply);
  635:           }                    ;
  636:           my $i;
  637:           for ($i=0;$i<=$#ids;$i++) {
  638:               if ($answer[$i]) {
  639: 		  $returnhash{$ids[$i]}=$answer[$i];
  640:               } 
  641:           }
  642:        }
  643:     }    
  644:     return %returnhash;
  645: }
  646: 
  647: # ------------------------------------- Find the IDs behind a list of usernames
  648: 
  649: sub idrget {
  650:     my ($udom,@unames)=@_;
  651:     my %returnhash=();
  652:     foreach (@unames) {
  653:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  654:     }
  655:     return %returnhash;
  656: }
  657: 
  658: # ------------------------------- Store away a list of names and associated IDs
  659: 
  660: sub idput {
  661:     my ($udom,%ids)=@_;
  662:     my %servers=();
  663:     foreach (keys %ids) {
  664: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  665:         my $uhom=&homeserver($_,$udom);
  666:         if ($uhom ne 'no_host') {
  667:             my $id=&escape($ids{$_});
  668:             $id=~tr/A-Z/a-z/;
  669:             my $unam=&escape($_);
  670: 	    if ($servers{$uhom}) {
  671: 		$servers{$uhom}.='&'.$id.'='.$unam;
  672:             } else {
  673:                 $servers{$uhom}=$id.'='.$unam;
  674:             }
  675:         }
  676:     }
  677:     foreach (keys %servers) {
  678:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  679:     }
  680: }
  681: 
  682: # --------------------------------------------------- Assign a key to a student
  683: 
  684: sub assign_access_key {
  685: #
  686: # a valid key looks like uname:udom#comments
  687: # comments are being appended
  688: #
  689:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  690:     $kdom=
  691:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  692:     $knum=
  693:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  694:     $cdom=
  695:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  696:     $cnum=
  697:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  698:     $udom=$env{'user.name'} unless (defined($udom));
  699:     $uname=$env{'user.domain'} unless (defined($uname));
  700:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  701:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  702:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  703:                                                   # assigned to this person
  704:                                                   # - this should not happen,
  705:                                                   # unless something went wrong
  706:                                                   # the first time around
  707: # ready to assign
  708:         $logentry=$1.'; '.$logentry;
  709:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  710:                                                  $kdom,$knum) eq 'ok') {
  711: # key now belongs to user
  712: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  713:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  714:                 &appenv('environment.'.$envkey => $ckey);
  715:                 return 'ok';
  716:             } else {
  717:                 return 
  718:   'error: Count not permanently assign key, will need to be re-entered later.';
  719: 	    }
  720:         } else {
  721:             return 'error: Could not assign key, try again later.';
  722:         }
  723:     } elsif (!$existing{$ckey}) {
  724: # the key does not exist
  725: 	return 'error: The key does not exist';
  726:     } else {
  727: # the key is somebody else's
  728: 	return 'error: The key is already in use';
  729:     }
  730: }
  731: 
  732: # ------------------------------------------ put an additional comment on a key
  733: 
  734: sub comment_access_key {
  735: #
  736: # a valid key looks like uname:udom#comments
  737: # comments are being appended
  738: #
  739:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  740:     $cdom=
  741:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  742:     $cnum=
  743:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  744:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  745:     if ($existing{$ckey}) {
  746:         $existing{$ckey}.='; '.$logentry;
  747: # ready to assign
  748:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  749:                                                  $cdom,$cnum) eq 'ok') {
  750: 	    return 'ok';
  751:         } else {
  752: 	    return 'error: Count not store comment.';
  753:         }
  754:     } else {
  755: # the key does not exist
  756: 	return 'error: The key does not exist';
  757:     }
  758: }
  759: 
  760: # ------------------------------------------------------ Generate a set of keys
  761: 
  762: sub generate_access_keys {
  763:     my ($number,$cdom,$cnum,$logentry)=@_;
  764:     $cdom=
  765:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  766:     $cnum=
  767:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  768:     unless (&allowed('mky',$cdom)) { return 0; }
  769:     unless (($cdom) && ($cnum)) { return 0; }
  770:     if ($number>10000) { return 0; }
  771:     sleep(2); # make sure don't get same seed twice
  772:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  773:     my $total=0;
  774:     for (my $i=1;$i<=$number;$i++) {
  775:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  776:                   sprintf("%lx",int(100000*rand)).'-'.
  777:                   sprintf("%lx",int(100000*rand));
  778:        $newkey=~s/1/g/g; # folks mix up 1 and l
  779:        $newkey=~s/0/h/g; # and also 0 and O
  780:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  781:        if ($existing{$newkey}) {
  782:            $i--;
  783:        } else {
  784: 	  if (&put('accesskeys',
  785:               { $newkey => '# generated '.localtime().
  786:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  787:                            '; '.$logentry },
  788: 		   $cdom,$cnum) eq 'ok') {
  789:               $total++;
  790: 	  }
  791:        }
  792:     }
  793:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  794:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  795:     return $total;
  796: }
  797: 
  798: # ------------------------------------------------------- Validate an accesskey
  799: 
  800: sub validate_access_key {
  801:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  802:     $cdom=
  803:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  804:     $cnum=
  805:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  806:     $udom=$env{'user.domain'} unless (defined($udom));
  807:     $uname=$env{'user.name'} unless (defined($uname));
  808:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  809:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  810: }
  811: 
  812: # ------------------------------------- Find the section of student in a course
  813: sub devalidate_getsection_cache {
  814:     my ($udom,$unam,$courseid)=@_;
  815:     $courseid=~s/\_/\//g;
  816:     $courseid=~s/^(\w)/\/$1/;
  817:     my $hashid="$udom:$unam:$courseid";
  818:     &devalidate_cache_new('getsection',$hashid);
  819: }
  820: 
  821: sub getsection {
  822:     my ($udom,$unam,$courseid)=@_;
  823:     my $cachetime=1800;
  824:     $courseid=~s/\_/\//g;
  825:     $courseid=~s/^(\w)/\/$1/;
  826: 
  827:     my $hashid="$udom:$unam:$courseid";
  828:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  829:     if (defined($cached)) { return $result; }
  830: 
  831:     my %Pending; 
  832:     my %Expired;
  833:     #
  834:     # Each role can either have not started yet (pending), be active, 
  835:     #    or have expired.
  836:     #
  837:     # If there is an active role, we are done.
  838:     #
  839:     # If there is more than one role which has not started yet, 
  840:     #     choose the one which will start sooner
  841:     # If there is one role which has not started yet, return it.
  842:     #
  843:     # If there is more than one expired role, choose the one which ended last.
  844:     # If there is a role which has expired, return it.
  845:     #
  846:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  847:                         &homeserver($unam,$udom)))) {
  848:         my ($key,$value)=split(/\=/,$_);
  849:         $key=&unescape($key);
  850:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  851:         my $section=$1;
  852:         if ($key eq $courseid.'_st') { $section=''; }
  853:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  854:         my $now=time;
  855:         if (defined($end) && $end && ($now > $end)) {
  856:             $Expired{$end}=$section;
  857:             next;
  858:         }
  859:         if (defined($start) && $start && ($now < $start)) {
  860:             $Pending{$start}=$section;
  861:             next;
  862:         }
  863:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  864:     }
  865:     #
  866:     # Presumedly there will be few matching roles from the above
  867:     # loop and the sorting time will be negligible.
  868:     if (scalar(keys(%Pending))) {
  869:         my ($time) = sort {$a <=> $b} keys(%Pending);
  870:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  871:     } 
  872:     if (scalar(keys(%Expired))) {
  873:         my @sorted = sort {$a <=> $b} keys(%Expired);
  874:         my $time = pop(@sorted);
  875:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  876:     }
  877:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  878: }
  879: 
  880: sub save_cache {
  881:     &purge_remembered();
  882:     #&Apache::loncommon::validate_page();
  883:     undef(%env);
  884:     undef($env_loaded);
  885: }
  886: 
  887: my $to_remember=-1;
  888: my %remembered;
  889: my %accessed;
  890: my $kicks=0;
  891: my $hits=0;
  892: sub devalidate_cache_new {
  893:     my ($name,$id,$debug) = @_;
  894:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  895:     $id=&escape($name.':'.$id);
  896:     $memcache->delete($id);
  897:     delete($remembered{$id});
  898:     delete($accessed{$id});
  899: }
  900: 
  901: sub is_cached_new {
  902:     my ($name,$id,$debug) = @_;
  903:     $id=&escape($name.':'.$id);
  904:     if (exists($remembered{$id})) {
  905: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  906: 	$accessed{$id}=[&gettimeofday()];
  907: 	$hits++;
  908: 	return ($remembered{$id},1);
  909:     }
  910:     my $value = $memcache->get($id);
  911:     if (!(defined($value))) {
  912: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  913: 	return (undef,undef);
  914:     }
  915:     if ($value eq '__undef__') {
  916: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  917: 	$value=undef;
  918:     }
  919:     &make_room($id,$value,$debug);
  920:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  921:     return ($value,1);
  922: }
  923: 
  924: sub do_cache_new {
  925:     my ($name,$id,$value,$time,$debug) = @_;
  926:     $id=&escape($name.':'.$id);
  927:     my $setvalue=$value;
  928:     if (!defined($setvalue)) {
  929: 	$setvalue='__undef__';
  930:     }
  931:     if (!defined($time) ) {
  932: 	$time=600;
  933:     }
  934:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  935:     $memcache->set($id,$setvalue,$time);
  936:     # need to make a copy of $value
  937:     #&make_room($id,$value,$debug);
  938:     return $value;
  939: }
  940: 
  941: sub make_room {
  942:     my ($id,$value,$debug)=@_;
  943:     $remembered{$id}=$value;
  944:     if ($to_remember<0) { return; }
  945:     $accessed{$id}=[&gettimeofday()];
  946:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  947:     my $to_kick;
  948:     my $max_time=0;
  949:     foreach my $other (keys(%accessed)) {
  950: 	if (&tv_interval($accessed{$other}) > $max_time) {
  951: 	    $to_kick=$other;
  952: 	    $max_time=&tv_interval($accessed{$other});
  953: 	}
  954:     }
  955:     delete($remembered{$to_kick});
  956:     delete($accessed{$to_kick});
  957:     $kicks++;
  958:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  959:     return;
  960: }
  961: 
  962: sub purge_remembered {
  963:     #&logthis("Tossing ".scalar(keys(%remembered)));
  964:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  965:     undef(%remembered);
  966:     undef(%accessed);
  967: }
  968: # ------------------------------------- Read an entry from a user's environment
  969: 
  970: sub userenvironment {
  971:     my ($udom,$unam,@what)=@_;
  972:     my %returnhash=();
  973:     my @answer=split(/\&/,
  974:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  975:                       &homeserver($unam,$udom)));
  976:     my $i;
  977:     for ($i=0;$i<=$#what;$i++) {
  978: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  979:     }
  980:     return %returnhash;
  981: }
  982: 
  983: # ---------------------------------------------------------- Get a studentphoto
  984: sub studentphoto {
  985:     my ($udom,$unam,$ext) = @_;
  986:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  987:     if (defined($env{'request.course.id'})) {
  988:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
  989:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
  990:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
  991:             } else {
  992:                 my ($result,$perm_reqd)=
  993: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
  994:                 if ($result eq 'ok') {
  995:                     if (!($perm_reqd eq 'yes')) {
  996:                         return(&retrievestudentphoto($udom,$unam,$ext));
  997:                     }
  998:                 }
  999:             }
 1000:         }
 1001:     } else {
 1002:         my ($result,$perm_reqd) = 
 1003: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1004:         if ($result eq 'ok') {
 1005:             if (!($perm_reqd eq 'yes')) {
 1006:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1007:             }
 1008:         }
 1009:     }
 1010:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1011: }
 1012: 
 1013: sub retrievestudentphoto {
 1014:     my ($udom,$unam,$ext,$type) = @_;
 1015:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1016:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1017:     if ($ret eq 'ok') {
 1018:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1019:         if ($type eq 'thumbnail') {
 1020:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1021:         }
 1022:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1023:         return $tokenurl;
 1024:     } else {
 1025:         if ($type eq 'thumbnail') {
 1026:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1027:         } else { 
 1028:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1029:         }
 1030:     }
 1031: }
 1032: 
 1033: # -------------------------------------------------------------------- New chat
 1034: 
 1035: sub chatsend {
 1036:     my ($newentry,$anon,$group)=@_;
 1037:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1038:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1039:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1040:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1041: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1042: 		   &escape($newentry)).':'.$group,$chome);
 1043: }
 1044: 
 1045: # ------------------------------------------ Find current version of a resource
 1046: 
 1047: sub getversion {
 1048:     my $fname=&clutter(shift);
 1049:     unless ($fname=~/^\/res\//) { return -1; }
 1050:     return &currentversion(&filelocation('',$fname));
 1051: }
 1052: 
 1053: sub currentversion {
 1054:     my $fname=shift;
 1055:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1056:     if (defined($cached)) { return $result; }
 1057:     my $author=$fname;
 1058:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1059:     my ($udom,$uname)=split(/\//,$author);
 1060:     my $home=homeserver($uname,$udom);
 1061:     if ($home eq 'no_host') { 
 1062:         return -1; 
 1063:     }
 1064:     my $answer=reply("currentversion:$fname",$home);
 1065:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1066: 	return -1;
 1067:     }
 1068:     return &do_cache_new('resversion',$fname,$answer,600);
 1069: }
 1070: 
 1071: # ----------------------------- Subscribe to a resource, return URL if possible
 1072: 
 1073: sub subscribe {
 1074:     my $fname=shift;
 1075:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1076:     $fname=~s/[\n\r]//g;
 1077:     my $author=$fname;
 1078:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1079:     my ($udom,$uname)=split(/\//,$author);
 1080:     my $home=homeserver($uname,$udom);
 1081:     if ($home eq 'no_host') {
 1082:         return 'not_found';
 1083:     }
 1084:     my $answer=reply("sub:$fname",$home);
 1085:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1086: 	$answer.=' by '.$home;
 1087:     }
 1088:     return $answer;
 1089: }
 1090:     
 1091: # -------------------------------------------------------------- Replicate file
 1092: 
 1093: sub repcopy {
 1094:     my $filename=shift;
 1095:     $filename=~s/\/+/\//g;
 1096:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1097:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1098:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1099: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1100: 	return &repcopy_userfile($filename);
 1101:     }
 1102:     $filename=~s/[\n\r]//g;
 1103:     my $transname="$filename.in.transfer";
 1104:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1105:     my $remoteurl=subscribe($filename);
 1106:     if ($remoteurl =~ /^con_lost by/) {
 1107: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1108:            return 'unavailable';
 1109:     } elsif ($remoteurl eq 'not_found') {
 1110: 	   #&logthis("Subscribe returned not_found: $filename");
 1111: 	   return 'not_found';
 1112:     } elsif ($remoteurl =~ /^rejected by/) {
 1113: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1114:            return 'forbidden';
 1115:     } elsif ($remoteurl eq 'directory') {
 1116:            return 'ok';
 1117:     } else {
 1118:         my $author=$filename;
 1119:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1120:         my ($udom,$uname)=split(/\//,$author);
 1121:         my $home=homeserver($uname,$udom);
 1122:         unless ($home eq $perlvar{'lonHostID'}) {
 1123:            my @parts=split(/\//,$filename);
 1124:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1125:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1126:                &logthis("Malconfiguration for replication: $filename");
 1127: 	       return 'bad_request';
 1128:            }
 1129:            my $count;
 1130:            for ($count=5;$count<$#parts;$count++) {
 1131:                $path.="/$parts[$count]";
 1132:                if ((-e $path)!=1) {
 1133: 		   mkdir($path,0777);
 1134:                }
 1135:            }
 1136:            my $ua=new LWP::UserAgent;
 1137:            my $request=new HTTP::Request('GET',"$remoteurl");
 1138:            my $response=$ua->request($request,$transname);
 1139:            if ($response->is_error()) {
 1140: 	       unlink($transname);
 1141:                my $message=$response->status_line;
 1142:                &logthis("<font color=\"blue\">WARNING:"
 1143:                        ." LWP get: $message: $filename</font>");
 1144:                return 'unavailable';
 1145:            } else {
 1146: 	       if ($remoteurl!~/\.meta$/) {
 1147:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1148:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1149:                   if ($mresponse->is_error()) {
 1150: 		      unlink($filename.'.meta');
 1151:                       &logthis(
 1152:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1153:                   }
 1154: 	       }
 1155:                rename($transname,$filename);
 1156:                return 'ok';
 1157:            }
 1158:        }
 1159:     }
 1160: }
 1161: 
 1162: # ------------------------------------------------ Get server side include body
 1163: sub ssi_body {
 1164:     my ($filelink,%form)=@_;
 1165:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1166:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1167:     }
 1168:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1169:                                      &ssi($filelink,%form));
 1170:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1171:     $output=~s/^.*?\<body[^\>]*\>//si;
 1172:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1173:     return $output;
 1174: }
 1175: 
 1176: # --------------------------------------------------------- Server Side Include
 1177: 
 1178: sub absolute_url {
 1179:     my ($host_name) = @_;
 1180:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1181:     if ($host_name eq '') {
 1182: 	$host_name = $ENV{'SERVER_NAME'};
 1183:     }
 1184:     return $protocol.$host_name;
 1185: }
 1186: 
 1187: sub absolute_url {
 1188:     my ($host_name) = @_;
 1189:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1190:     if ($host_name eq '') {
 1191: 	$host_name = $ENV{'SERVER_NAME'};
 1192:     }
 1193:     return $protocol.$host_name;
 1194: }
 1195: 
 1196: sub ssi {
 1197: 
 1198:     my ($fn,%form)=@_;
 1199: 
 1200:     my $ua=new LWP::UserAgent;
 1201:     
 1202:     my $request;
 1203: 
 1204:     $form{'no_update_last_known'}=1;
 1205: 
 1206:     if (%form) {
 1207:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1208:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1209:     } else {
 1210:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1211:     }
 1212: 
 1213:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1214:     my $response=$ua->request($request);
 1215: 
 1216:     return $response->content;
 1217: }
 1218: 
 1219: sub externalssi {
 1220:     my ($url)=@_;
 1221:     my $ua=new LWP::UserAgent;
 1222:     my $request=new HTTP::Request('GET',$url);
 1223:     my $response=$ua->request($request);
 1224:     return $response->content;
 1225: }
 1226: 
 1227: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1228: 
 1229: sub allowuploaded {
 1230:     my ($srcurl,$url)=@_;
 1231:     $url=&clutter(&declutter($url));
 1232:     my $dir=$url;
 1233:     $dir=~s/\/[^\/]+$//;
 1234:     my %httpref=();
 1235:     my $httpurl=&hreflocation('',$url);
 1236:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1237:     &Apache::lonnet::appenv(%httpref);
 1238: }
 1239: 
 1240: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1241: # input: action, courseID, current domain, intended
 1242: #        path to file, source of file, instruction to parse file for objects,
 1243: #        ref to hash for embedded objects,
 1244: #        ref to hash for codebase of java objects.
 1245: #
 1246: # output: url to file (if action was uploaddoc), 
 1247: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1248: #
 1249: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1250: # course.
 1251: #
 1252: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1253: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1254: #          course's home server.
 1255: #
 1256: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1257: #          be copied from $source (current location) to 
 1258: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1259: #         and will then be copied to
 1260: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1261: #         course's home server.
 1262: #
 1263: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1264: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1265: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1266: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1267: #         in course's home server.
 1268: #
 1269: 
 1270: sub process_coursefile {
 1271:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1272:     my $fetchresult;
 1273:     my $home=&homeserver($docuname,$docudom);
 1274:     if ($action eq 'propagate') {
 1275:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1276: 			     $home);
 1277:     } else {
 1278:         my $fpath = '';
 1279:         my $fname = $file;
 1280:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1281:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1282:         my $filepath = &build_filepath($fpath);
 1283:         if ($action eq 'copy') {
 1284:             if ($source eq '') {
 1285:                 $fetchresult = 'no source file';
 1286:                 return $fetchresult;
 1287:             } else {
 1288:                 my $destination = $filepath.'/'.$fname;
 1289:                 rename($source,$destination);
 1290:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1291:                                  $home);
 1292:             }
 1293:         } elsif ($action eq 'uploaddoc') {
 1294:             open(my $fh,'>'.$filepath.'/'.$fname);
 1295:             print $fh $env{'form.'.$source};
 1296:             close($fh);
 1297:             if ($parser eq 'parse') {
 1298:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1299:                 unless ($parse_result eq 'ok') {
 1300:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1301:                 }
 1302:             }
 1303:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1304:                                  $home);
 1305:             if ($fetchresult eq 'ok') {
 1306:                 return '/uploaded/'.$fpath.'/'.$fname;
 1307:             } else {
 1308:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1309:                         ' to host '.$home.': '.$fetchresult);
 1310:                 return '/adm/notfound.html';
 1311:             }
 1312:         }
 1313:     }
 1314:     unless ( $fetchresult eq 'ok') {
 1315:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1316:              ' to host '.$home.': '.$fetchresult);
 1317:     }
 1318:     return $fetchresult;
 1319: }
 1320: 
 1321: sub build_filepath {
 1322:     my ($fpath) = @_;
 1323:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1324:     unless ($fpath eq '') {
 1325:         my @parts=split('/',$fpath);
 1326:         foreach my $part (@parts) {
 1327:             $filepath.= '/'.$part;
 1328:             if ((-e $filepath)!=1) {
 1329:                 mkdir($filepath,0777);
 1330:             }
 1331:         }
 1332:     }
 1333:     return $filepath;
 1334: }
 1335: 
 1336: sub store_edited_file {
 1337:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1338:     my $file = $primary_url;
 1339:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1340:     my $fpath = '';
 1341:     my $fname = $file;
 1342:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1343:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1344:     my $filepath = &build_filepath($fpath);
 1345:     open(my $fh,'>'.$filepath.'/'.$fname);
 1346:     print $fh $content;
 1347:     close($fh);
 1348:     my $home=&homeserver($docuname,$docudom);
 1349:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1350: 			  $home);
 1351:     if ($$fetchresult eq 'ok') {
 1352:         return '/uploaded/'.$fpath.'/'.$fname;
 1353:     } else {
 1354:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1355: 		 ' to host '.$home.': '.$$fetchresult);
 1356:         return '/adm/notfound.html';
 1357:     }
 1358: }
 1359: 
 1360: sub clean_filename {
 1361:     my ($fname)=@_;
 1362: # Replace Windows backslashes by forward slashes
 1363:     $fname=~s/\\/\//g;
 1364: # Get rid of everything but the actual filename
 1365:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1366: # Replace spaces by underscores
 1367:     $fname=~s/\s+/\_/g;
 1368: # Replace all other weird characters by nothing
 1369:     $fname=~s/[^\w\.\-]//g;
 1370: # Replace all .\d. sequences with _\d. so they no longer look like version
 1371: # numbers
 1372:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1373:     return $fname;
 1374: }
 1375: 
 1376: # --------------- Take an uploaded file and put it into the userfiles directory
 1377: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1378: #                    the desired filenam is in $env{"form.$formname.filename"}
 1379: #        $coursedoc - if true up to the current course
 1380: #                     if false
 1381: #        $subdir - directory in userfile to store the file into
 1382: #        $parser, $allfiles, $codebase - unknown
 1383: #
 1384: # output: url of file in userspace, or error: <message> 
 1385: #             or /adm/notfound.html if failure to upload occurse
 1386: 
 1387: 
 1388: sub userfileupload {
 1389:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1390:     if (!defined($subdir)) { $subdir='unknown'; }
 1391:     my $fname=$env{'form.'.$formname.'.filename'};
 1392:     $fname=&clean_filename($fname);
 1393: # See if there is anything left
 1394:     unless ($fname) { return 'error: no uploaded file'; }
 1395:     chop($env{'form.'.$formname});
 1396:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1397:         my $now = time;
 1398:         my $filepath = 'tmp/helprequests/'.$now;
 1399:         my @parts=split(/\//,$filepath);
 1400:         my $fullpath = $perlvar{'lonDaemons'};
 1401:         for (my $i=0;$i<@parts;$i++) {
 1402:             $fullpath .= '/'.$parts[$i];
 1403:             if ((-e $fullpath)!=1) {
 1404:                 mkdir($fullpath,0777);
 1405:             }
 1406:         }
 1407:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1408:         print $fh $env{'form.'.$formname};
 1409:         close($fh);
 1410:         return $fullpath.'/'.$fname;
 1411:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1412:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1413:                        '_'.$env{'user.domain'}.'/pending';
 1414:         my @parts=split(/\//,$filepath);
 1415:         my $fullpath = $perlvar{'lonDaemons'};
 1416:         for (my $i=0;$i<@parts;$i++) {
 1417:             $fullpath .= '/'.$parts[$i];
 1418:             if ((-e $fullpath)!=1) {
 1419:                 mkdir($fullpath,0777);
 1420:             }
 1421:         }
 1422:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1423:         print $fh $env{'form.'.$formname};
 1424:         close($fh);
 1425:         return $fullpath.'/'.$fname;
 1426:     }
 1427:     
 1428: # Create the directory if not present
 1429:     $fname="$subdir/$fname";
 1430:     if ($coursedoc) {
 1431: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1432: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1433:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1434:             return &finishuserfileupload($docuname,$docudom,
 1435: 					 $formname,$fname,$parser,$allfiles,
 1436: 					 $codebase);
 1437:         } else {
 1438:             $fname=$env{'form.folder'}.'/'.$fname;
 1439:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1440: 				       $fname,$formname,$parser,
 1441: 				       $allfiles,$codebase);
 1442:         }
 1443:     } elsif (defined($destuname)) {
 1444:         my $docuname=$destuname;
 1445:         my $docudom=$destudom;
 1446: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1447: 				     $fname,$parser,$allfiles,$codebase);
 1448:         
 1449:     } else {
 1450:         my $docuname=$env{'user.name'};
 1451:         my $docudom=$env{'user.domain'};
 1452:         if (exists($env{'form.group'})) {
 1453:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1454:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1455:         }
 1456: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1457: 				     $fname,$parser,$allfiles,$codebase);
 1458:     }
 1459: }
 1460: 
 1461: sub finishuserfileupload {
 1462:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1463:     my $path=$docudom.'/'.$docuname.'/';
 1464:     my $filepath=$perlvar{'lonDocRoot'};
 1465:     my ($fnamepath,$file);
 1466:     $file=$fname;
 1467:     if ($fname=~m|/|) {
 1468:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1469: 	$path.=$fnamepath.'/';
 1470:     }
 1471:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1472:     my $count;
 1473:     for ($count=4;$count<=$#parts;$count++) {
 1474:         $filepath.="/$parts[$count]";
 1475:         if ((-e $filepath)!=1) {
 1476: 	    mkdir($filepath,0777);
 1477:         }
 1478:     }
 1479: # Save the file
 1480:     {
 1481: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1482: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1483: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1484: 	    return '/adm/notfound.html';
 1485: 	}
 1486: 	if (!print FH ($env{'form.'.$formname})) {
 1487: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1488: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1489: 	    return '/adm/notfound.html';
 1490: 	}
 1491: 	close(FH);
 1492:     }
 1493:     if ($parser eq 'parse') {
 1494:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1495: 						   $codebase);
 1496:         unless ($parse_result eq 'ok') {
 1497:             &logthis('Failed to parse '.$filepath.$file.
 1498: 		     ' for embedded media: '.$parse_result); 
 1499:         }
 1500:     }
 1501: # Notify homeserver to grep it
 1502: #
 1503:     my $docuhome=&homeserver($docuname,$docudom);
 1504:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1505:     if ($fetchresult eq 'ok') {
 1506: #
 1507: # Return the URL to it
 1508:         return '/uploaded/'.$path.$file;
 1509:     } else {
 1510:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1511: 		 ': '.$fetchresult);
 1512:         return '/adm/notfound.html';
 1513:     }    
 1514: }
 1515: 
 1516: sub extract_embedded_items {
 1517:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1518:     my @state = ();
 1519:     my %javafiles = (
 1520:                       codebase => '',
 1521:                       code => '',
 1522:                       archive => ''
 1523:                     );
 1524:     my %mediafiles = (
 1525:                       src => '',
 1526:                       movie => '',
 1527:                      );
 1528:     my $p;
 1529:     if ($content) {
 1530:         $p = HTML::LCParser->new($content);
 1531:     } else {
 1532:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1533:     }
 1534:     while (my $t=$p->get_token()) {
 1535: 	if ($t->[0] eq 'S') {
 1536: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1537: 	    push (@state, $tagname);
 1538:             if (lc($tagname) eq 'allow') {
 1539:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1540:             }
 1541: 	    if (lc($tagname) eq 'img') {
 1542: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1543: 	    }
 1544:             if (lc($tagname) eq 'script') {
 1545:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1546:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1547:                 } else {
 1548:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1549:                 }
 1550:             }
 1551:             if (lc($tagname) eq 'link') {
 1552:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1553:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1554:                 }
 1555:             }
 1556: 	    if (lc($tagname) eq 'object' ||
 1557: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1558: 		foreach my $item (keys(%javafiles)) {
 1559: 		    $javafiles{$item} = '';
 1560: 		}
 1561: 	    }
 1562: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1563: 		my $name = lc($attr->{'name'});
 1564: 		foreach my $item (keys(%javafiles)) {
 1565: 		    if ($name eq $item) {
 1566: 			$javafiles{$item} = $attr->{'value'};
 1567: 			last;
 1568: 		    }
 1569: 		}
 1570: 		foreach my $item (keys(%mediafiles)) {
 1571: 		    if ($name eq $item) {
 1572: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1573: 			last;
 1574: 		    }
 1575: 		}
 1576: 	    }
 1577: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1578: 		foreach my $item (keys(%javafiles)) {
 1579: 		    if ($attr->{$item}) {
 1580: 			$javafiles{$item} = $attr->{$item};
 1581: 			last;
 1582: 		    }
 1583: 		}
 1584: 		foreach my $item (keys(%mediafiles)) {
 1585: 		    if ($attr->{$item}) {
 1586: 			&add_filetype($allfiles,$attr->{$item},$item);
 1587: 			last;
 1588: 		    }
 1589: 		}
 1590: 	    }
 1591: 	} elsif ($t->[0] eq 'E') {
 1592: 	    my ($tagname) = ($t->[1]);
 1593: 	    if ($javafiles{'codebase'} ne '') {
 1594: 		$javafiles{'codebase'} .= '/';
 1595: 	    }  
 1596: 	    if (lc($tagname) eq 'applet' ||
 1597: 		lc($tagname) eq 'object' ||
 1598: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1599: 		) {
 1600: 		foreach my $item (keys(%javafiles)) {
 1601: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1602: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1603: 			&add_filetype($allfiles,$file,$item);
 1604: 		    }
 1605: 		}
 1606: 	    } 
 1607: 	    pop @state;
 1608: 	}
 1609:     }
 1610:     return 'ok';
 1611: }
 1612: 
 1613: sub add_filetype {
 1614:     my ($allfiles,$file,$type)=@_;
 1615:     if (exists($allfiles->{$file})) {
 1616: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1617: 	    push(@{$allfiles->{$file}}, &escape($type));
 1618: 	}
 1619:     } else {
 1620: 	@{$allfiles->{$file}} = (&escape($type));
 1621:     }
 1622: }
 1623: 
 1624: sub removeuploadedurl {
 1625:     my ($url)=@_;
 1626:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1627:     return &removeuserfile($uname,$udom,$fname);
 1628: }
 1629: 
 1630: sub removeuserfile {
 1631:     my ($docuname,$docudom,$fname)=@_;
 1632:     my $home=&homeserver($docuname,$docudom);
 1633:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1634: }
 1635: 
 1636: sub mkdiruserfile {
 1637:     my ($docuname,$docudom,$dir)=@_;
 1638:     my $home=&homeserver($docuname,$docudom);
 1639:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1640: }
 1641: 
 1642: sub renameuserfile {
 1643:     my ($docuname,$docudom,$old,$new)=@_;
 1644:     my $home=&homeserver($docuname,$docudom);
 1645:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1646: 		  &escape("$new"),$home);
 1647: }
 1648: 
 1649: # ------------------------------------------------------------------------- Log
 1650: 
 1651: sub log {
 1652:     my ($dom,$nam,$hom,$what)=@_;
 1653:     return critical("log:$dom:$nam:$what",$hom);
 1654: }
 1655: 
 1656: # ------------------------------------------------------------------ Course Log
 1657: #
 1658: # This routine flushes several buffers of non-mission-critical nature
 1659: #
 1660: 
 1661: sub flushcourselogs {
 1662:     &logthis('Flushing log buffers');
 1663: #
 1664: # course logs
 1665: # This is a log of all transactions in a course, which can be used
 1666: # for data mining purposes
 1667: #
 1668: # It also collects the courseid database, which lists last transaction
 1669: # times and course titles for all courseids
 1670: #
 1671:     my %courseidbuffer=();
 1672:     foreach (keys %courselogs) {
 1673:         my $crsid=$_;
 1674:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1675: 		          &escape($courselogs{$crsid}),
 1676: 		          $coursehombuf{$crsid}) eq 'ok') {
 1677: 	    delete $courselogs{$crsid};
 1678:         } else {
 1679:             &logthis('Failed to flush log buffer for '.$crsid);
 1680:             if (length($courselogs{$crsid})>40000) {
 1681:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1682:                         " exceeded maximum size, deleting.</font>");
 1683:                delete $courselogs{$crsid};
 1684:             }
 1685:         }
 1686:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1687:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1688: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1689:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1690:         } else {
 1691:            $courseidbuffer{$coursehombuf{$crsid}}=
 1692: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1693:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1694:         }
 1695:     }
 1696: #
 1697: # Write course id database (reverse lookup) to homeserver of courses 
 1698: # Is used in pickcourse
 1699: #
 1700:     foreach (keys %courseidbuffer) {
 1701:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1702:     }
 1703: #
 1704: # File accesses
 1705: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1706: #
 1707:     foreach my $entry (keys(%accesshash)) {
 1708:         if ($entry =~ /___count$/) {
 1709:             my ($dom,$name);
 1710:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1711:             if (! defined($dom) || $dom eq '' || 
 1712:                 ! defined($name) || $name eq '') {
 1713:                 my $cid = $env{'request.course.id'};
 1714:                 $dom  = $env{'request.'.$cid.'.domain'};
 1715:                 $name = $env{'request.'.$cid.'.num'};
 1716:             }
 1717:             my $value = $accesshash{$entry};
 1718:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1719:             my %temphash=($url => $value);
 1720:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1721:             if ($result eq 'ok') {
 1722:                 delete $accesshash{$entry};
 1723:             } elsif ($result eq 'unknown_cmd') {
 1724:                 # Target server has old code running on it.
 1725:                 my %temphash=($entry => $value);
 1726:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1727:                     delete $accesshash{$entry};
 1728:                 }
 1729:             }
 1730:         } else {
 1731:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1732:             my %temphash=($entry => $accesshash{$entry});
 1733:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1734:                 delete $accesshash{$entry};
 1735:             }
 1736:         }
 1737:     }
 1738: #
 1739: # Roles
 1740: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1741: #
 1742:     foreach (keys %userrolehash) {
 1743:         my $entry=$_;
 1744:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1745: 	    split(/\:/,$entry);
 1746:         if (&Apache::lonnet::put('nohist_userroles',
 1747:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1748:                 $rudom,$runame) eq 'ok') {
 1749: 	    delete $userrolehash{$entry};
 1750:         }
 1751:     }
 1752: #
 1753: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1754: #
 1755:     my %domrolebuffer = ();
 1756:     foreach my $entry (keys %domainrolehash) {
 1757:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1758:         if ($domrolebuffer{$rudom}) {
 1759:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1760:                       '='.&escape($domainrolehash{$entry});
 1761:         } else {
 1762:             $domrolebuffer{$rudom}.=&escape($entry).
 1763:                       '='.&escape($domainrolehash{$entry});
 1764:         }
 1765:         delete $domainrolehash{$entry};
 1766:     }
 1767:     foreach my $dom (keys(%domrolebuffer)) {
 1768:         foreach my $tryserver (keys %libserv) {
 1769:             if ($hostdom{$tryserver} eq $dom) {
 1770:                 unless (&reply('domroleput:'.$dom.':'.
 1771:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1772:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1773:                 }
 1774:             }
 1775:         }
 1776:     }
 1777:     $dumpcount++;
 1778: }
 1779: 
 1780: sub courselog {
 1781:     my $what=shift;
 1782:     $what=time.':'.$what;
 1783:     unless ($env{'request.course.id'}) { return ''; }
 1784:     $coursedombuf{$env{'request.course.id'}}=
 1785:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1786:     $coursenumbuf{$env{'request.course.id'}}=
 1787:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1788:     $coursehombuf{$env{'request.course.id'}}=
 1789:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1790:     $coursedescrbuf{$env{'request.course.id'}}=
 1791:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1792:     $courseinstcodebuf{$env{'request.course.id'}}=
 1793:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1794:     $courseownerbuf{$env{'request.course.id'}}=
 1795:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1796:     $coursetypebuf{$env{'request.course.id'}}=
 1797:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1798:     if (defined $courselogs{$env{'request.course.id'}}) {
 1799: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1800:     } else {
 1801: 	$courselogs{$env{'request.course.id'}}.=$what;
 1802:     }
 1803:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1804: 	&flushcourselogs();
 1805:     }
 1806: }
 1807: 
 1808: sub courseacclog {
 1809:     my $fnsymb=shift;
 1810:     unless ($env{'request.course.id'}) { return ''; }
 1811:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1812:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1813:         $what.=':POST';
 1814:         # FIXME: Probably ought to escape things....
 1815: 	foreach (keys %env) {
 1816:             if ($_=~/^form\.(.*)/) {
 1817: 		$what.=':'.$1.'='.$env{$_};
 1818:             }
 1819:         }
 1820:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1821:         # FIXME: We should not be depending on a form parameter that someone
 1822:         # editing lonsearchcat.pm might change in the future.
 1823:         if ($env{'form.phase'} eq 'course_search') {
 1824:             $what.= ':POST';
 1825:             # FIXME: Probably ought to escape things....
 1826:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1827:                                  'crsdiscuss') {
 1828:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1829:             }
 1830:         }
 1831:     }
 1832:     &courselog($what);
 1833: }
 1834: 
 1835: sub countacc {
 1836:     my $url=&declutter(shift);
 1837:     return if (! defined($url) || $url eq '');
 1838:     unless ($env{'request.course.id'}) { return ''; }
 1839:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1840:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1841:     $accesshash{$key}++;
 1842: }
 1843: 
 1844: sub linklog {
 1845:     my ($from,$to)=@_;
 1846:     $from=&declutter($from);
 1847:     $to=&declutter($to);
 1848:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1849:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1850: }
 1851:   
 1852: sub userrolelog {
 1853:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1854:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1855:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1856:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1857:         ($trole=~/^ta/)) {
 1858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1859:        $userrolehash
 1860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1861:                     =$tend.':'.$tstart;
 1862:     }
 1863:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1864:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1865:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1866:         ($trole=~/^sc/)) {
 1867:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1868:        $domainrolehash
 1869:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1870:                     = $tend.':'.$tstart;
 1871:     }
 1872: }
 1873: 
 1874: sub get_course_adv_roles {
 1875:     my $cid=shift;
 1876:     $cid=$env{'request.course.id'} unless (defined($cid));
 1877:     my %coursehash=&coursedescription($cid);
 1878:     my %nothide=();
 1879:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1880: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1881:     }
 1882:     my %returnhash=();
 1883:     my %dumphash=
 1884:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1885:     my $now=time;
 1886:     foreach (keys %dumphash) {
 1887: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1888:         if (($tstart) && ($tstart<0)) { next; }
 1889:         if (($tend) && ($tend<$now)) { next; }
 1890:         if (($tstart) && ($now<$tstart)) { next; }
 1891:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1892: 	if ($username eq '' || $domain eq '') { next; }
 1893: 	if ((&privileged($username,$domain)) && 
 1894: 	    (!$nothide{$username.':'.$domain})) { next; }
 1895: 	if ($role eq 'cr') { next; }
 1896:         my $key=&plaintext($role);
 1897:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1898:         if ($returnhash{$key}) {
 1899: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1900:         } else {
 1901:             $returnhash{$key}=$username.':'.$domain;
 1902:         }
 1903:      }
 1904:     return %returnhash;
 1905: }
 1906: 
 1907: sub get_my_roles {
 1908:     my ($uname,$udom)=@_;
 1909:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1910:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1911:     my %dumphash=
 1912:             &dump('nohist_userroles',$udom,$uname);
 1913:     my %returnhash=();
 1914:     my $now=time;
 1915:     foreach (keys %dumphash) {
 1916: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1917:         if (($tstart) && ($tstart<0)) { next; }
 1918:         if (($tend) && ($tend<$now)) { next; }
 1919:         if (($tstart) && ($now<$tstart)) { next; }
 1920:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1921: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1922:      }
 1923:     return %returnhash;
 1924: }
 1925: 
 1926: # ----------------------------------------------------- Frontpage Announcements
 1927: #
 1928: #
 1929: 
 1930: sub postannounce {
 1931:     my ($server,$text)=@_;
 1932:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1933:     unless ($text=~/\w/) { $text=''; }
 1934:     return &reply('setannounce:'.&escape($text),$server);
 1935: }
 1936: 
 1937: sub getannounce {
 1938: 
 1939:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1940: 	my $announcement='';
 1941: 	while (<$fh>) { $announcement .=$_; }
 1942: 	close($fh);
 1943: 	if ($announcement=~/\w/) { 
 1944: 	    return 
 1945:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1946:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1947: 	} else {
 1948: 	    return '';
 1949: 	}
 1950:     } else {
 1951: 	return '';
 1952:     }
 1953: }
 1954: 
 1955: # ---------------------------------------------------------- Course ID routines
 1956: # Deal with domain's nohist_courseid.db files
 1957: #
 1958: 
 1959: sub courseidput {
 1960:     my ($domain,$what,$coursehome)=@_;
 1961:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1962: }
 1963: 
 1964: sub courseiddump {
 1965:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
 1966:     my %returnhash=();
 1967:     unless ($domfilter) { $domfilter=''; }
 1968:     foreach my $tryserver (keys %libserv) {
 1969:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1970: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1971: 	        foreach (
 1972:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1973: 			       $sincefilter.':'.&escape($descfilter).':'.
 1974:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
 1975:                                $tryserver))) {
 1976: 		    my ($key,$value)=split(/\=/,$_);
 1977:                     if (($key) && ($value)) {
 1978: 		        $returnhash{&unescape($key)}=$value;
 1979:                     }
 1980:                 }
 1981:             }
 1982:         }
 1983:     }
 1984:     return %returnhash;
 1985: }
 1986: 
 1987: # ---------------------------------------------------------- DC e-mail
 1988: 
 1989: sub dcmailput {
 1990:     my ($domain,$msgid,$message,$server)=@_;
 1991:     my $status = &Apache::lonnet::critical(
 1992:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 1993:        &escape($message),$server);
 1994:     return $status;
 1995: }
 1996: 
 1997: sub dcmaildump {
 1998:     my ($dom,$startdate,$enddate,$senders) = @_;
 1999:     my %returnhash=();
 2000:     if (exists($domain_primary{$dom})) {
 2001:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2002:                                                          &escape($enddate).':';
 2003: 	my @esc_senders=map { &escape($_)} @$senders;
 2004: 	$cmd.=&escape(join('&',@esc_senders));
 2005: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2006:             my ($key,$value) = split(/\=/,$_);
 2007:             if (($key) && ($value)) {
 2008:                 $returnhash{&unescape($key)} = &unescape($value);
 2009:             }
 2010:         }
 2011:     }
 2012:     return %returnhash;
 2013: }
 2014: # ---------------------------------------------------------- Domain roles
 2015: 
 2016: sub get_domain_roles {
 2017:     my ($dom,$roles,$startdate,$enddate)=@_;
 2018:     if (undef($startdate) || $startdate eq '') {
 2019:         $startdate = '.';
 2020:     }
 2021:     if (undef($enddate) || $enddate eq '') {
 2022:         $enddate = '.';
 2023:     }
 2024:     my $rolelist = join(':',@{$roles});
 2025:     my %personnel = ();
 2026:     foreach my $tryserver (keys(%libserv)) {
 2027:         if ($hostdom{$tryserver} eq $dom) {
 2028:             %{$personnel{$tryserver}}=();
 2029:             foreach (
 2030:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2031:                    &escape($startdate).':'.&escape($enddate).':'.
 2032:                    &escape($rolelist), $tryserver))) {
 2033:                 my($key,$value) = split(/\=/,$_);
 2034:                 if (($key) && ($value)) {
 2035:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2036:                 }
 2037:             }
 2038:         }
 2039:     }
 2040:     return %personnel;
 2041: }
 2042: 
 2043: # ----------------------------------------------------------- Check out an item
 2044: 
 2045: sub get_first_access {
 2046:     my ($type,$argsymb)=@_;
 2047:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2048:     if ($argsymb) { $symb=$argsymb; }
 2049:     my ($map,$id,$res)=&decode_symb($symb);
 2050:     if ($type eq 'map') {
 2051: 	$res=&symbread($map);
 2052:     } else {
 2053: 	$res=$symb;
 2054:     }
 2055:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2056:     return $times{"$courseid\0$res"};
 2057: }
 2058: 
 2059: sub set_first_access {
 2060:     my ($type)=@_;
 2061:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2062:     my ($map,$id,$res)=&decode_symb($symb);
 2063:     if ($type eq 'map') {
 2064: 	$res=&symbread($map);
 2065:     } else {
 2066: 	$res=$symb;
 2067:     }
 2068:     my $firstaccess=&get_first_access($type,$symb);
 2069:     if (!$firstaccess) {
 2070: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2071:     }
 2072:     return 'already_set';
 2073: }
 2074: 
 2075: sub checkout {
 2076:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2077:     my $now=time;
 2078:     my $lonhost=$perlvar{'lonHostID'};
 2079:     my $infostr=&escape(
 2080:                  'CHECKOUTTOKEN&'.
 2081:                  $tuname.'&'.
 2082:                  $tudom.'&'.
 2083:                  $tcrsid.'&'.
 2084:                  $symb.'&'.
 2085: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2086:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2087:     if ($token=~/^error\:/) { 
 2088:         &logthis("<font color=\"blue\">WARNING: ".
 2089:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2090:                  "</font>");
 2091:         return ''; 
 2092:     }
 2093: 
 2094:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2095:     $token=~tr/a-z/A-Z/;
 2096: 
 2097:     my %infohash=('resource.0.outtoken' => $token,
 2098:                   'resource.0.checkouttime' => $now,
 2099:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2100: 
 2101:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2102:        return '';
 2103:     } else {
 2104:         &logthis("<font color=\"blue\">WARNING: ".
 2105:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2106:                  "</font>");
 2107:     }    
 2108: 
 2109:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2110:                          &escape('Checkout '.$infostr.' - '.
 2111:                                                  $token)) ne 'ok') {
 2112: 	return '';
 2113:     } else {
 2114:         &logthis("<font color=\"blue\">WARNING: ".
 2115:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2116:                  "</font>");
 2117:     }
 2118:     return $token;
 2119: }
 2120: 
 2121: # ------------------------------------------------------------ Check in an item
 2122: 
 2123: sub checkin {
 2124:     my $token=shift;
 2125:     my $now=time;
 2126:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2127:     $lonhost=~tr/A-Z/a-z/;
 2128:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2129:     $dtoken=~s/\W/\_/g;
 2130:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2131:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2132: 
 2133:     unless (($tuname) && ($tudom)) {
 2134:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2135:         return '';
 2136:     }
 2137:     
 2138:     unless (&allowed('mgr',$tcrsid)) {
 2139:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2140:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2141:         return '';
 2142:     }
 2143: 
 2144:     my %infohash=('resource.0.intoken' => $token,
 2145:                   'resource.0.checkintime' => $now,
 2146:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2147: 
 2148:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2149:        return '';
 2150:     }    
 2151: 
 2152:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2153:                          &escape('Checkin - '.$token)) ne 'ok') {
 2154: 	return '';
 2155:     }
 2156: 
 2157:     return ($symb,$tuname,$tudom,$tcrsid);    
 2158: }
 2159: 
 2160: # --------------------------------------------- Set Expire Date for Spreadsheet
 2161: 
 2162: sub expirespread {
 2163:     my ($uname,$udom,$stype,$usymb)=@_;
 2164:     my $cid=$env{'request.course.id'}; 
 2165:     if ($cid) {
 2166:        my $now=time;
 2167:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2168:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2169:                             $env{'course.'.$cid.'.num'}.
 2170: 	        	    ':nohist_expirationdates:'.
 2171:                             &escape($key).'='.$now,
 2172:                             $env{'course.'.$cid.'.home'})
 2173:     }
 2174:     return 'ok';
 2175: }
 2176: 
 2177: # ----------------------------------------------------- Devalidate Spreadsheets
 2178: 
 2179: sub devalidate {
 2180:     my ($symb,$uname,$udom)=@_;
 2181:     my $cid=$env{'request.course.id'}; 
 2182:     if ($cid) {
 2183:         # delete the stored spreadsheets for
 2184:         # - the student level sheet of this user in course's homespace
 2185:         # - the assessment level sheet for this resource 
 2186:         #   for this user in user's homespace
 2187: 	# - current conditional state info
 2188: 	my $key=$uname.':'.$udom.':';
 2189:         my $status=
 2190: 	    &del('nohist_calculatedsheets',
 2191: 		 [$key.'studentcalc:'],
 2192: 		 $env{'course.'.$cid.'.domain'},
 2193: 		 $env{'course.'.$cid.'.num'})
 2194: 		.' '.
 2195: 	    &del('nohist_calculatedsheets_'.$cid,
 2196: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2197:         unless ($status eq 'ok ok') {
 2198:            &logthis('Could not devalidate spreadsheet '.
 2199:                     $uname.' at '.$udom.' for '.
 2200: 		    $symb.': '.$status);
 2201:         }
 2202: 	&delenv('user.state.'.$cid);
 2203:     }
 2204: }
 2205: 
 2206: sub get_scalar {
 2207:     my ($string,$end) = @_;
 2208:     my $value;
 2209:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2210: 	$value = $1;
 2211:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2212: 	$value = $1;
 2213:     }
 2214:     return &unescape($value);
 2215: }
 2216: 
 2217: sub array2str {
 2218:   my (@array) = @_;
 2219:   my $result=&arrayref2str(\@array);
 2220:   $result=~s/^__ARRAY_REF__//;
 2221:   $result=~s/__END_ARRAY_REF__$//;
 2222:   return $result;
 2223: }
 2224: 
 2225: sub arrayref2str {
 2226:   my ($arrayref) = @_;
 2227:   my $result='__ARRAY_REF__';
 2228:   foreach my $elem (@$arrayref) {
 2229:     if(ref($elem) eq 'ARRAY') {
 2230:       $result.=&arrayref2str($elem).'&';
 2231:     } elsif(ref($elem) eq 'HASH') {
 2232:       $result.=&hashref2str($elem).'&';
 2233:     } elsif(ref($elem)) {
 2234:       #print("Got a ref of ".(ref($elem))." skipping.");
 2235:     } else {
 2236:       $result.=&escape($elem).'&';
 2237:     }
 2238:   }
 2239:   $result=~s/\&$//;
 2240:   $result .= '__END_ARRAY_REF__';
 2241:   return $result;
 2242: }
 2243: 
 2244: sub hash2str {
 2245:   my (%hash) = @_;
 2246:   my $result=&hashref2str(\%hash);
 2247:   $result=~s/^__HASH_REF__//;
 2248:   $result=~s/__END_HASH_REF__$//;
 2249:   return $result;
 2250: }
 2251: 
 2252: sub hashref2str {
 2253:   my ($hashref)=@_;
 2254:   my $result='__HASH_REF__';
 2255:   foreach (sort(keys(%$hashref))) {
 2256:     if (ref($_) eq 'ARRAY') {
 2257:       $result.=&arrayref2str($_).'=';
 2258:     } elsif (ref($_) eq 'HASH') {
 2259:       $result.=&hashref2str($_).'=';
 2260:     } elsif (ref($_)) {
 2261:       $result.='=';
 2262:       #print("Got a ref of ".(ref($_))." skipping.");
 2263:     } else {
 2264: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2265:     }
 2266: 
 2267:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2268:       $result.=&arrayref2str($hashref->{$_}).'&';
 2269:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2270:       $result.=&hashref2str($hashref->{$_}).'&';
 2271:     } elsif(ref($hashref->{$_})) {
 2272:        $result.='&';
 2273:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2274:     } else {
 2275:       $result.=&escape($hashref->{$_}).'&';
 2276:     }
 2277:   }
 2278:   $result=~s/\&$//;
 2279:   $result .= '__END_HASH_REF__';
 2280:   return $result;
 2281: }
 2282: 
 2283: sub str2hash {
 2284:     my ($string)=@_;
 2285:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2286:     return %$hash;
 2287: }
 2288: 
 2289: sub str2hashref {
 2290:   my ($string) = @_;
 2291: 
 2292:   my %hash;
 2293: 
 2294:   if($string !~ /^__HASH_REF__/) {
 2295:       if (! ($string eq '' || !defined($string))) {
 2296: 	  $hash{'error'}='Not hash reference';
 2297:       }
 2298:       return (\%hash, $string);
 2299:   }
 2300: 
 2301:   $string =~ s/^__HASH_REF__//;
 2302: 
 2303:   while($string !~ /^__END_HASH_REF__/) {
 2304:       #key
 2305:       my $key='';
 2306:       if($string =~ /^__HASH_REF__/) {
 2307:           ($key, $string)=&str2hashref($string);
 2308:           if(defined($key->{'error'})) {
 2309:               $hash{'error'}='Bad data';
 2310:               return (\%hash, $string);
 2311:           }
 2312:       } elsif($string =~ /^__ARRAY_REF__/) {
 2313:           ($key, $string)=&str2arrayref($string);
 2314:           if($key->[0] eq 'Array reference error') {
 2315:               $hash{'error'}='Bad data';
 2316:               return (\%hash, $string);
 2317:           }
 2318:       } else {
 2319:           $string =~ s/^(.*?)=//;
 2320: 	  $key=&unescape($1);
 2321:       }
 2322:       $string =~ s/^=//;
 2323: 
 2324:       #value
 2325:       my $value='';
 2326:       if($string =~ /^__HASH_REF__/) {
 2327:           ($value, $string)=&str2hashref($string);
 2328:           if(defined($value->{'error'})) {
 2329:               $hash{'error'}='Bad data';
 2330:               return (\%hash, $string);
 2331:           }
 2332:       } elsif($string =~ /^__ARRAY_REF__/) {
 2333:           ($value, $string)=&str2arrayref($string);
 2334:           if($value->[0] eq 'Array reference error') {
 2335:               $hash{'error'}='Bad data';
 2336:               return (\%hash, $string);
 2337:           }
 2338:       } else {
 2339: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2340:       }
 2341:       $string =~ s/^&//;
 2342: 
 2343:       $hash{$key}=$value;
 2344:   }
 2345: 
 2346:   $string =~ s/^__END_HASH_REF__//;
 2347: 
 2348:   return (\%hash, $string);
 2349: }
 2350: 
 2351: sub str2array {
 2352:     my ($string)=@_;
 2353:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2354:     return @$array;
 2355: }
 2356: 
 2357: sub str2arrayref {
 2358:   my ($string) = @_;
 2359:   my @array;
 2360: 
 2361:   if($string !~ /^__ARRAY_REF__/) {
 2362:       if (! ($string eq '' || !defined($string))) {
 2363: 	  $array[0]='Array reference error';
 2364:       }
 2365:       return (\@array, $string);
 2366:   }
 2367: 
 2368:   $string =~ s/^__ARRAY_REF__//;
 2369: 
 2370:   while($string !~ /^__END_ARRAY_REF__/) {
 2371:       my $value='';
 2372:       if($string =~ /^__HASH_REF__/) {
 2373:           ($value, $string)=&str2hashref($string);
 2374:           if(defined($value->{'error'})) {
 2375:               $array[0] ='Array reference error';
 2376:               return (\@array, $string);
 2377:           }
 2378:       } elsif($string =~ /^__ARRAY_REF__/) {
 2379:           ($value, $string)=&str2arrayref($string);
 2380:           if($value->[0] eq 'Array reference error') {
 2381:               $array[0] ='Array reference error';
 2382:               return (\@array, $string);
 2383:           }
 2384:       } else {
 2385: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2386:       }
 2387:       $string =~ s/^&//;
 2388: 
 2389:       push(@array, $value);
 2390:   }
 2391: 
 2392:   $string =~ s/^__END_ARRAY_REF__//;
 2393: 
 2394:   return (\@array, $string);
 2395: }
 2396: 
 2397: # -------------------------------------------------------------------Temp Store
 2398: 
 2399: sub tmpreset {
 2400:   my ($symb,$namespace,$domain,$stuname) = @_;
 2401:   if (!$symb) {
 2402:     $symb=&symbread();
 2403:     if (!$symb) { $symb= $env{'request.url'}; }
 2404:   }
 2405:   $symb=escape($symb);
 2406: 
 2407:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2408:   $namespace=~s/\//\_/g;
 2409:   $namespace=~s/\W//g;
 2410: 
 2411:   if (!$domain) { $domain=$env{'user.domain'}; }
 2412:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2413:   if ($domain eq 'public' && $stuname eq 'public') {
 2414:       $stuname=$ENV{'REMOTE_ADDR'};
 2415:   }
 2416:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2417:   my %hash;
 2418:   if (tie(%hash,'GDBM_File',
 2419: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2420: 	  &GDBM_WRCREAT(),0640)) {
 2421:     foreach my $key (keys %hash) {
 2422:       if ($key=~ /:$symb/) {
 2423: 	delete($hash{$key});
 2424:       }
 2425:     }
 2426:   }
 2427: }
 2428: 
 2429: sub tmpstore {
 2430:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2431: 
 2432:   if (!$symb) {
 2433:     $symb=&symbread();
 2434:     if (!$symb) { $symb= $env{'request.url'}; }
 2435:   }
 2436:   $symb=escape($symb);
 2437: 
 2438:   if (!$namespace) {
 2439:     # I don't think we would ever want to store this for a course.
 2440:     # it seems this will only be used if we don't have a course.
 2441:     #$namespace=$env{'request.course.id'};
 2442:     #if (!$namespace) {
 2443:       $namespace=$env{'request.state'};
 2444:     #}
 2445:   }
 2446:   $namespace=~s/\//\_/g;
 2447:   $namespace=~s/\W//g;
 2448:   if (!$domain) { $domain=$env{'user.domain'}; }
 2449:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2450:   if ($domain eq 'public' && $stuname eq 'public') {
 2451:       $stuname=$ENV{'REMOTE_ADDR'};
 2452:   }
 2453:   my $now=time;
 2454:   my %hash;
 2455:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2456:   if (tie(%hash,'GDBM_File',
 2457: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2458: 	  &GDBM_WRCREAT(),0640)) {
 2459:     $hash{"version:$symb"}++;
 2460:     my $version=$hash{"version:$symb"};
 2461:     my $allkeys=''; 
 2462:     foreach my $key (keys(%$storehash)) {
 2463:       $allkeys.=$key.':';
 2464:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2465:     }
 2466:     $hash{"$version:$symb:timestamp"}=$now;
 2467:     $allkeys.='timestamp';
 2468:     $hash{"$version:keys:$symb"}=$allkeys;
 2469:     if (untie(%hash)) {
 2470:       return 'ok';
 2471:     } else {
 2472:       return "error:$!";
 2473:     }
 2474:   } else {
 2475:     return "error:$!";
 2476:   }
 2477: }
 2478: 
 2479: # -----------------------------------------------------------------Temp Restore
 2480: 
 2481: sub tmprestore {
 2482:   my ($symb,$namespace,$domain,$stuname) = @_;
 2483: 
 2484:   if (!$symb) {
 2485:     $symb=&symbread();
 2486:     if (!$symb) { $symb= $env{'request.url'}; }
 2487:   }
 2488:   $symb=escape($symb);
 2489: 
 2490:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2491: 
 2492:   if (!$domain) { $domain=$env{'user.domain'}; }
 2493:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2494:   if ($domain eq 'public' && $stuname eq 'public') {
 2495:       $stuname=$ENV{'REMOTE_ADDR'};
 2496:   }
 2497:   my %returnhash;
 2498:   $namespace=~s/\//\_/g;
 2499:   $namespace=~s/\W//g;
 2500:   my %hash;
 2501:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2502:   if (tie(%hash,'GDBM_File',
 2503: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2504: 	  &GDBM_READER(),0640)) {
 2505:     my $version=$hash{"version:$symb"};
 2506:     $returnhash{'version'}=$version;
 2507:     my $scope;
 2508:     for ($scope=1;$scope<=$version;$scope++) {
 2509:       my $vkeys=$hash{"$scope:keys:$symb"};
 2510:       my @keys=split(/:/,$vkeys);
 2511:       my $key;
 2512:       $returnhash{"$scope:keys"}=$vkeys;
 2513:       foreach $key (@keys) {
 2514: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2515: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2516:       }
 2517:     }
 2518:     if (!(untie(%hash))) {
 2519:       return "error:$!";
 2520:     }
 2521:   } else {
 2522:     return "error:$!";
 2523:   }
 2524:   return %returnhash;
 2525: }
 2526: 
 2527: # ----------------------------------------------------------------------- Store
 2528: 
 2529: sub store {
 2530:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2531:     my $home='';
 2532: 
 2533:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2534: 
 2535:     $symb=&symbclean($symb);
 2536:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2537: 
 2538:     if (!$domain) { $domain=$env{'user.domain'}; }
 2539:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2540: 
 2541:     &devalidate($symb,$stuname,$domain);
 2542: 
 2543:     $symb=escape($symb);
 2544:     if (!$namespace) { 
 2545:        unless ($namespace=$env{'request.course.id'}) { 
 2546:           return ''; 
 2547:        } 
 2548:     }
 2549:     if (!$home) { $home=$env{'user.home'}; }
 2550: 
 2551:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2552:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2553: 
 2554:     my $namevalue='';
 2555:     foreach (keys %$storehash) {
 2556:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2557:     }
 2558:     $namevalue=~s/\&$//;
 2559:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2560:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2561: }
 2562: 
 2563: # -------------------------------------------------------------- Critical Store
 2564: 
 2565: sub cstore {
 2566:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2567:     my $home='';
 2568: 
 2569:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2570: 
 2571:     $symb=&symbclean($symb);
 2572:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2573: 
 2574:     if (!$domain) { $domain=$env{'user.domain'}; }
 2575:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2576: 
 2577:     &devalidate($symb,$stuname,$domain);
 2578: 
 2579:     $symb=escape($symb);
 2580:     if (!$namespace) { 
 2581:        unless ($namespace=$env{'request.course.id'}) { 
 2582:           return ''; 
 2583:        } 
 2584:     }
 2585:     if (!$home) { $home=$env{'user.home'}; }
 2586: 
 2587:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2588:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2589: 
 2590:     my $namevalue='';
 2591:     foreach (keys %$storehash) {
 2592:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2593:     }
 2594:     $namevalue=~s/\&$//;
 2595:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2596:     return critical
 2597:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2598: }
 2599: 
 2600: # --------------------------------------------------------------------- Restore
 2601: 
 2602: sub restore {
 2603:     my ($symb,$namespace,$domain,$stuname) = @_;
 2604:     my $home='';
 2605: 
 2606:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2607: 
 2608:     if (!$symb) {
 2609:       unless ($symb=escape(&symbread())) { return ''; }
 2610:     } else {
 2611:       $symb=&escape(&symbclean($symb));
 2612:     }
 2613:     if (!$namespace) { 
 2614:        unless ($namespace=$env{'request.course.id'}) { 
 2615:           return ''; 
 2616:        } 
 2617:     }
 2618:     if (!$domain) { $domain=$env{'user.domain'}; }
 2619:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2620:     if (!$home) { $home=$env{'user.home'}; }
 2621:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2622: 
 2623:     my %returnhash=();
 2624:     foreach (split(/\&/,$answer)) {
 2625: 	my ($name,$value)=split(/\=/,$_);
 2626:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2627:     }
 2628:     my $version;
 2629:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2630:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2631:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2632:        }
 2633:     }
 2634:     return %returnhash;
 2635: }
 2636: 
 2637: # ---------------------------------------------------------- Course Description
 2638: 
 2639: sub coursedescription {
 2640:     my ($courseid,$args)=@_;
 2641:     $courseid=~s/^\///;
 2642:     $courseid=~s/\_/\//g;
 2643:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2644:     my $chome=&homeserver($cnum,$cdomain);
 2645:     my $normalid=$cdomain.'_'.$cnum;
 2646:     # need to always cache even if we get errors otherwise we keep 
 2647:     # trying and trying and trying to get the course description.
 2648:     my %envhash=();
 2649:     my %returnhash=();
 2650:     
 2651:     my $expiretime=600;
 2652:     if ($env{'request.course.id'} eq $normalid) {
 2653: 	$expiretime=120;
 2654:     }
 2655: 
 2656:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2657:     if (!$args->{'freshen_cache'}
 2658: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2659: 	foreach my $key (keys(%env)) {
 2660: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2661: 	    my ($setting) = $1;
 2662: 	    $returnhash{$setting} = $env{$key};
 2663: 	}
 2664: 	return %returnhash;
 2665:     }
 2666: 
 2667:     # get the data agin
 2668:     if (!$args->{'one_time'}) {
 2669: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2670:     }
 2671:     if ($chome ne 'no_host') {
 2672:        %returnhash=&dump('environment',$cdomain,$cnum);
 2673:        if (!exists($returnhash{'con_lost'})) {
 2674:            $returnhash{'home'}= $chome;
 2675: 	   $returnhash{'domain'} = $cdomain;
 2676: 	   $returnhash{'num'} = $cnum;
 2677:            if (!defined($returnhash{'type'})) {
 2678:                $returnhash{'type'} = 'Course';
 2679:            }
 2680:            while (my ($name,$value) = each %returnhash) {
 2681:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2682:            }
 2683:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2684:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2685: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2686:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2687:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2688:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2689:        }
 2690:     }
 2691:     if (!$args->{'one_time'}) {
 2692: 	&appenv(%envhash);
 2693:     }
 2694:     return %returnhash;
 2695: }
 2696: 
 2697: # -------------------------------------------------See if a user is privileged
 2698: 
 2699: sub privileged {
 2700:     my ($username,$domain)=@_;
 2701:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2702: 			&homeserver($username,$domain));
 2703:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2704:     my $now=time;
 2705:     if ($rolesdump ne '') {
 2706:         foreach (split(/&/,$rolesdump)) {
 2707: 	    if ($_!~/^rolesdef_/) {
 2708: 		my ($area,$role)=split(/=/,$_);
 2709: 		$area=~s/\_\w\w$//;
 2710: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2711: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2712: 		    my $active=1;
 2713: 		    if ($tend) {
 2714: 			if ($tend<$now) { $active=0; }
 2715: 		    }
 2716: 		    if ($tstart) {
 2717: 			if ($tstart>$now) { $active=0; }
 2718: 		    }
 2719: 		    if ($active) { return 1; }
 2720: 		}
 2721: 	    }
 2722: 	}
 2723:     }
 2724:     return 0;
 2725: }
 2726: 
 2727: # -------------------------------------------------------- Get user privileges
 2728: 
 2729: sub rolesinit {
 2730:     my ($domain,$username,$authhost)=@_;
 2731:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2732:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2733:     my %allroles=();
 2734:     my %allgroups=();   
 2735:     my $now=time;
 2736:     my %userroles = ('user.login.time' => $now);
 2737:     my $group_privs;
 2738: 
 2739:     if ($rolesdump ne '') {
 2740:         foreach (split(/&/,$rolesdump)) {
 2741: 	  if ($_!~/^rolesdef_/) {
 2742:             my ($area,$role)=split(/=/,$_);
 2743: 	    $area=~s/\_\w\w$//;
 2744:             my ($trole,$tend,$tstart,$group_privs);
 2745: 	    if ($role=~/^cr/) { 
 2746: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2747: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2748: 		    ($tend,$tstart)=split('_',$trest);
 2749: 		} else {
 2750: 		    $trole=$role;
 2751: 		}
 2752:             } elsif ($role =~ m|^gr/|) {
 2753:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2754:                 ($trole,$group_privs) = split(/\//,$trole);
 2755:                 $group_privs = &unescape($group_privs);
 2756: 	    } else {
 2757: 		($trole,$tend,$tstart)=split(/_/,$role);
 2758: 	    }
 2759: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2760: 					 $username);
 2761: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2762:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2763:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2764:             if (($area ne '') && ($trole ne '')) {
 2765: 		my $spec=$trole.'.'.$area;
 2766: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2767: 		if ($trole =~ /^cr\//) {
 2768:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2769:                 } elsif ($trole eq 'gr') {
 2770:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2771: 		} else {
 2772:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2773: 		}
 2774:             }
 2775:           }
 2776:         }
 2777:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2778:         $userroles{'user.adv'}    = $adv;
 2779: 	$userroles{'user.author'} = $author;
 2780:         $env{'user.adv'}=$adv;
 2781:     }
 2782:     return \%userroles;  
 2783: }
 2784: 
 2785: sub set_arearole {
 2786:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2787: # log the associated role with the area
 2788:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2789:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2790: }
 2791: 
 2792: sub custom_roleprivs {
 2793:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2794:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2795:     my $homsvr=homeserver($rauthor,$rdomain);
 2796:     if ($hostname{$homsvr} ne '') {
 2797:         my ($rdummy,$roledef)=
 2798:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2799:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2800:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2801:             if (defined($syspriv)) {
 2802:                 $$allroles{'cm./'}.=':'.$syspriv;
 2803:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2804:             }
 2805:             if ($tdomain ne '') {
 2806:                 if (defined($dompriv)) {
 2807:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2808:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2809:                 }
 2810:                 if (($trest ne '') && (defined($coursepriv))) {
 2811:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2812:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2813:                 }
 2814:             }
 2815:         }
 2816:     }
 2817: }
 2818: 
 2819: sub group_roleprivs {
 2820:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2821:     my $access = 1;
 2822:     my $now = time;
 2823:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2824:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2825:     if ($access) {
 2826:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2827:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2828:     }
 2829: }
 2830: 
 2831: sub standard_roleprivs {
 2832:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2833:     if (defined($pr{$trole.':s'})) {
 2834:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2835:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2836:     }
 2837:     if ($tdomain ne '') {
 2838:         if (defined($pr{$trole.':d'})) {
 2839:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2840:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2841:         }
 2842:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2843:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2844:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2845:         }
 2846:     }
 2847: }
 2848: 
 2849: sub set_userprivs {
 2850:     my ($userroles,$allroles,$allgroups) = @_; 
 2851:     my $author=0;
 2852:     my $adv=0;
 2853:     my %grouproles = ();
 2854:     if (keys(%{$allgroups}) > 0) {
 2855:         foreach my $role (keys %{$allroles}) {
 2856:             my ($trole,$area,$sec,$extendedarea);
 2857:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
 2858:                 $trole = $1;
 2859:                 $area = $2;
 2860:                 $sec = $3;
 2861:                 $extendedarea = $area.$sec;
 2862:                 if (exists($$allgroups{$area})) {
 2863:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2864:                         my $spec = $trole.'.'.$extendedarea;
 2865:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2866:                                                 $$allgroups{$area}{$group};
 2867:                     }
 2868:                 }
 2869:             }
 2870:         }
 2871:     }
 2872:     foreach (keys(%grouproles)) {
 2873:         $$allroles{$_} = $grouproles{$_};
 2874:     }
 2875:     foreach (keys %{$allroles}) {
 2876:         my %thesepriv=();
 2877:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2878:         foreach (split(/:/,$$allroles{$_})) {
 2879:             if ($_ ne '') {
 2880:                 my ($privilege,$restrictions)=split(/&/,$_);
 2881:                 if ($restrictions eq '') {
 2882:                     $thesepriv{$privilege}='F';
 2883:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2884:                     $thesepriv{$privilege}.=$restrictions;
 2885:                 }
 2886:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2887:             }
 2888:         }
 2889:         my $thesestr='';
 2890:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2891:         $userroles->{'user.priv.'.$_} = $thesestr;
 2892:     }
 2893:     return ($author,$adv);
 2894: }
 2895: 
 2896: # --------------------------------------------------------------- get interface
 2897: 
 2898: sub get {
 2899:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2900:    my $items='';
 2901:    foreach (@$storearr) {
 2902:        $items.=escape($_).'&';
 2903:    }
 2904:    $items=~s/\&$//;
 2905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2906:    if (!$uname) { $uname=$env{'user.name'}; }
 2907:    my $uhome=&homeserver($uname,$udomain);
 2908: 
 2909:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2910:    my @pairs=split(/\&/,$rep);
 2911:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2912:      return @pairs;
 2913:    }
 2914:    my %returnhash=();
 2915:    my $i=0;
 2916:    foreach (@$storearr) {
 2917:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2918:       $i++;
 2919:    }
 2920:    return %returnhash;
 2921: }
 2922: 
 2923: # --------------------------------------------------------------- del interface
 2924: 
 2925: sub del {
 2926:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2927:    my $items='';
 2928:    foreach (@$storearr) {
 2929:        $items.=escape($_).'&';
 2930:    }
 2931:    $items=~s/\&$//;
 2932:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2933:    if (!$uname) { $uname=$env{'user.name'}; }
 2934:    my $uhome=&homeserver($uname,$udomain);
 2935: 
 2936:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2937: }
 2938: 
 2939: # -------------------------------------------------------------- dump interface
 2940: 
 2941: sub dump {
 2942:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2943:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2944:     if (!$uname) { $uname=$env{'user.name'}; }
 2945:     my $uhome=&homeserver($uname,$udomain);
 2946:     if ($regexp) {
 2947: 	$regexp=&escape($regexp);
 2948:     } else {
 2949: 	$regexp='.';
 2950:     }
 2951:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2952:     my @pairs=split(/\&/,$rep);
 2953:     my %returnhash=();
 2954:     foreach my $item (@pairs) {
 2955: 	my ($key,$value)=split(/=/,$item,2);
 2956: 	$key = &unescape($key);
 2957: 	next if ($key =~ /^error: 2 /);
 2958: 	$returnhash{$key}=&thaw_unescape($value);
 2959:     }
 2960:     return %returnhash;
 2961: }
 2962: 
 2963: # --------------------------------------------------------- dumpstore interface
 2964: 
 2965: sub dumpstore {
 2966:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2967:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2968: }
 2969: 
 2970: # -------------------------------------------------------------- keys interface
 2971: 
 2972: sub getkeys {
 2973:    my ($namespace,$udomain,$uname)=@_;
 2974:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2975:    if (!$uname) { $uname=$env{'user.name'}; }
 2976:    my $uhome=&homeserver($uname,$udomain);
 2977:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2978:    my @keyarray=();
 2979:    foreach (split(/\&/,$rep)) {
 2980:       push (@keyarray,&unescape($_));
 2981:    }
 2982:    return @keyarray;
 2983: }
 2984: 
 2985: # --------------------------------------------------------------- currentdump
 2986: sub currentdump {
 2987:    my ($courseid,$sdom,$sname)=@_;
 2988:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2989:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2990:    $sname    = $env{'user.name'}         if (! defined($sname));
 2991:    my $uhome = &homeserver($sname,$sdom);
 2992:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2993:    return if ($rep =~ /^(error:|no_such_host)/);
 2994:    #
 2995:    my %returnhash=();
 2996:    #
 2997:    if ($rep eq "unknown_cmd") { 
 2998:        # an old lond will not know currentdump
 2999:        # Do a dump and make it look like a currentdump
 3000:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 3001:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3002:        my %hash = @tmp;
 3003:        @tmp=();
 3004:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3005:    } else {
 3006:        my @pairs=split(/\&/,$rep);
 3007:        foreach (@pairs) {
 3008:            my ($key,$value)=split(/=/,$_);
 3009:            my ($symb,$param) = split(/:/,$key);
 3010:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3011:                                                         &thaw_unescape($value);
 3012:        }
 3013:    }
 3014:    return %returnhash;
 3015: }
 3016: 
 3017: sub convert_dump_to_currentdump{
 3018:     my %hash = %{shift()};
 3019:     my %returnhash;
 3020:     # Code ripped from lond, essentially.  The only difference
 3021:     # here is the unescaping done by lonnet::dump().  Conceivably
 3022:     # we might run in to problems with parameter names =~ /^v\./
 3023:     while (my ($key,$value) = each(%hash)) {
 3024:         my ($v,$symb,$param) = split(/:/,$key);
 3025:         next if ($v eq 'version' || $symb eq 'keys');
 3026:         next if (exists($returnhash{$symb}) &&
 3027:                  exists($returnhash{$symb}->{$param}) &&
 3028:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3029:         $returnhash{$symb}->{$param}=$value;
 3030:         $returnhash{$symb}->{'v.'.$param}=$v;
 3031:     }
 3032:     #
 3033:     # Remove all of the keys in the hashes which keep track of
 3034:     # the version of the parameter.
 3035:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3036:         # use a foreach because we are going to delete from the hash.
 3037:         foreach my $key (keys(%$param_hash)) {
 3038:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3039:         }
 3040:     }
 3041:     return \%returnhash;
 3042: }
 3043: 
 3044: # ------------------------------------------------------ critical inc interface
 3045: 
 3046: sub cinc {
 3047:     return &inc(@_,'critical');
 3048: }
 3049: 
 3050: # --------------------------------------------------------------- inc interface
 3051: 
 3052: sub inc {
 3053:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3054:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3055:     if (!$uname) { $uname=$env{'user.name'}; }
 3056:     my $uhome=&homeserver($uname,$udomain);
 3057:     my $items='';
 3058:     if (! ref($store)) {
 3059:         # got a single value, so use that instead
 3060:         $items = &escape($store).'=&';
 3061:     } elsif (ref($store) eq 'SCALAR') {
 3062:         $items = &escape($$store).'=&';        
 3063:     } elsif (ref($store) eq 'ARRAY') {
 3064:         $items = join('=&',map {&escape($_);} @{$store});
 3065:     } elsif (ref($store) eq 'HASH') {
 3066:         while (my($key,$value) = each(%{$store})) {
 3067:             $items.= &escape($key).'='.&escape($value).'&';
 3068:         }
 3069:     }
 3070:     $items=~s/\&$//;
 3071:     if ($critical) {
 3072: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3073:     } else {
 3074: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3075:     }
 3076: }
 3077: 
 3078: # --------------------------------------------------------------- put interface
 3079: 
 3080: sub put {
 3081:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3082:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3083:    if (!$uname) { $uname=$env{'user.name'}; }
 3084:    my $uhome=&homeserver($uname,$udomain);
 3085:    my $items='';
 3086:    foreach (keys %$storehash) {
 3087:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3088:    }
 3089:    $items=~s/\&$//;
 3090:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3091: }
 3092: 
 3093: # ------------------------------------------------------------ newput interface
 3094: 
 3095: sub newput {
 3096:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3098:    if (!$uname) { $uname=$env{'user.name'}; }
 3099:    my $uhome=&homeserver($uname,$udomain);
 3100:    my $items='';
 3101:    foreach my $key (keys(%$storehash)) {
 3102:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3103:    }
 3104:    $items=~s/\&$//;
 3105:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3106: }
 3107: 
 3108: # ---------------------------------------------------------  putstore interface
 3109: 
 3110: sub putstore {
 3111:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3113:    if (!$uname) { $uname=$env{'user.name'}; }
 3114:    my $uhome=&homeserver($uname,$udomain);
 3115:    my $items='';
 3116:    foreach my $key (keys(%$storehash)) {
 3117:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3118:    }
 3119:    $items=~s/\&$//;
 3120:    my $esc_symb=&escape($symb);
 3121:    my $esc_v=&escape($version);
 3122:    my $reply =
 3123:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3124: 	      $uhome);
 3125:    if ($reply eq 'unknown_cmd') {
 3126:        # gfall back to way things use to be done
 3127:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3128: 			    $uname);
 3129:    }
 3130:    return $reply;
 3131: }
 3132: 
 3133: sub old_putstore {
 3134:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3135:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3136:     if (!$uname) { $uname=$env{'user.name'}; }
 3137:     my $uhome=&homeserver($uname,$udomain);
 3138:     my %newstorehash;
 3139:     foreach (keys %$storehash) {
 3140: 	my $key = $version.':'.&escape($symb).':'.$_;
 3141: 	$newstorehash{$key} = $storehash->{$_};
 3142:     }
 3143:     my $items='';
 3144:     my %allitems = ();
 3145:     foreach (keys %newstorehash) {
 3146: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3147: 	    my $key = $1.':keys:'.$2;
 3148: 	    $allitems{$key} .= $3.':';
 3149: 	}
 3150: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3151:     }
 3152:     foreach (keys %allitems) {
 3153: 	$allitems{$_} =~ s/\:$//;
 3154: 	$items.= $_.'='.$allitems{$_}.'&';
 3155:     }
 3156:     $items=~s/\&$//;
 3157:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3158: }
 3159: 
 3160: # ------------------------------------------------------ critical put interface
 3161: 
 3162: sub cput {
 3163:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3165:    if (!$uname) { $uname=$env{'user.name'}; }
 3166:    my $uhome=&homeserver($uname,$udomain);
 3167:    my $items='';
 3168:    foreach (keys %$storehash) {
 3169:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3170:    }
 3171:    $items=~s/\&$//;
 3172:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3173: }
 3174: 
 3175: # -------------------------------------------------------------- eget interface
 3176: 
 3177: sub eget {
 3178:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3179:    my $items='';
 3180:    foreach (@$storearr) {
 3181:        $items.=escape($_).'&';
 3182:    }
 3183:    $items=~s/\&$//;
 3184:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3185:    if (!$uname) { $uname=$env{'user.name'}; }
 3186:    my $uhome=&homeserver($uname,$udomain);
 3187:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3188:    my @pairs=split(/\&/,$rep);
 3189:    my %returnhash=();
 3190:    my $i=0;
 3191:    foreach (@$storearr) {
 3192:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3193:       $i++;
 3194:    }
 3195:    return %returnhash;
 3196: }
 3197: 
 3198: # ------------------------------------------------------------ tmpput interface
 3199: sub tmpput {
 3200:     my ($storehash,$server)=@_;
 3201:     my $items='';
 3202:     foreach (keys(%$storehash)) {
 3203: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3204:     }
 3205:     $items=~s/\&$//;
 3206:     return &reply("tmpput:$items",$server);
 3207: }
 3208: 
 3209: # ------------------------------------------------------------ tmpget interface
 3210: sub tmpget {
 3211:     my ($token,$server)=@_;
 3212:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3213:     my $rep=&reply("tmpget:$token",$server);
 3214:     my %returnhash;
 3215:     foreach my $item (split(/\&/,$rep)) {
 3216: 	my ($key,$value)=split(/=/,$item);
 3217: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3218:     }
 3219:     return %returnhash;
 3220: }
 3221: 
 3222: # ------------------------------------------------------------ tmpget interface
 3223: sub tmpdel {
 3224:     my ($token,$server)=@_;
 3225:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3226:     return &reply("tmpdel:$token",$server);
 3227: }
 3228: 
 3229: # -------------------------------------------------- portfolio access checking
 3230: 
 3231: sub portfolio_access {
 3232:     my ($requrl) = @_;
 3233:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3234:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3235:     if ($result eq 'ok') {
 3236:        return 'F';
 3237:     } elsif ($result =~ /^[^:]+:guest_/) {
 3238:        return 'A';
 3239:     }
 3240:     return '';
 3241: }
 3242: 
 3243: sub get_portfolio_access {
 3244:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3245: 
 3246:     if (!ref($access_hash)) {
 3247: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3248: 	my %access_controls = &get_access_controls($current_perms,$group,
 3249: 						   $file_name);
 3250: 	$access_hash = $access_controls{$file_name};
 3251:     }
 3252: 
 3253:     my ($public,$guest,@domains,@users,@courses,@groups);
 3254:     my $now = time;
 3255:     if (ref($access_hash) eq 'HASH') {
 3256:         foreach my $key (keys(%{$access_hash})) {
 3257:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3258:             if ($start > $now) {
 3259:                 next;
 3260:             }
 3261:             if ($end && $end<$now) {
 3262:                 next;
 3263:             }
 3264:             if ($scope eq 'public') {
 3265:                 $public = $key;
 3266:                 last;
 3267:             } elsif ($scope eq 'guest') {
 3268:                 $guest = $key;
 3269:             } elsif ($scope eq 'domains') {
 3270:                 push(@domains,$key);
 3271:             } elsif ($scope eq 'users') {
 3272:                 push(@users,$key);
 3273:             } elsif ($scope eq 'course') {
 3274:                 push(@courses,$key);
 3275:             } elsif ($scope eq 'group') {
 3276:                 push(@groups,$key);
 3277:             }
 3278:         }
 3279:         if ($public) {
 3280:             return 'ok';
 3281:         }
 3282:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3283:             if ($guest) {
 3284:                 return $guest;
 3285:             }
 3286:         } else {
 3287:             if (@domains > 0) {
 3288:                 foreach my $domkey (@domains) {
 3289:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3290:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3291:                             return 'ok';
 3292:                         }
 3293:                     }
 3294:                 }
 3295:             }
 3296:             if (@users > 0) {
 3297:                 foreach my $userkey (@users) {
 3298:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3299:                         return 'ok';
 3300:                     }
 3301:                 }
 3302:             }
 3303:             my %roleshash;
 3304:             my @courses_and_groups = @courses;
 3305:             push(@courses_and_groups,@groups); 
 3306:             if (@courses_and_groups > 0) {
 3307:                 my (%allgroups,%allroles); 
 3308:                 my ($start,$end,$role,$sec,$group);
 3309:                 foreach my $envkey (%env) {
 3310:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
 3311:                         my $cid = $2.'_'.$3; 
 3312:                         if ($1 eq 'gr') {
 3313:                             $group = $4;
 3314:                             $allgroups{$cid}{$group} = $env{$envkey};
 3315:                         } else {
 3316:                             if ($4 eq '') {
 3317:                                 $sec = 'none';
 3318:                             } else {
 3319:                                 $sec = $4;
 3320:                             }
 3321:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3322:                         }
 3323:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
 3324:                         my $cid = $2.'_'.$3;
 3325:                         if ($4 eq '') {
 3326:                             $sec = 'none';
 3327:                         } else {
 3328:                             $sec = $4;
 3329:                         }
 3330:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3331:                     }
 3332:                 }
 3333:                 if (keys(%allroles) == 0) {
 3334:                     return;
 3335:                 }
 3336:                 foreach my $key (@courses_and_groups) {
 3337:                     my %content = %{$$access_hash{$key}};
 3338:                     my $cnum = $content{'number'};
 3339:                     my $cdom = $content{'domain'};
 3340:                     my $cid = $cdom.'_'.$cnum;
 3341:                     if (!exists($allroles{$cid})) {
 3342:                         next;
 3343:                     }    
 3344:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3345:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3346:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3347:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3348:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3349:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3350:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3351:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3352:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3353:                                         if (grep/^all$/,@sections) {
 3354:                                             return 'ok';
 3355:                                         } else {
 3356:                                             if (grep/^$sec$/,@sections) {
 3357:                                                 return 'ok';
 3358:                                             }
 3359:                                         }
 3360:                                     }
 3361:                                 }
 3362:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3363:                                     if (grep/^none$/,@groups) {
 3364:                                         return 'ok';
 3365:                                     }
 3366:                                 } else {
 3367:                                     if (grep/^all$/,@groups) {
 3368:                                         return 'ok';
 3369:                                     } 
 3370:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3371:                                         if (grep/^$group$/,@groups) {
 3372:                                             return 'ok';
 3373:                                         }
 3374:                                     }
 3375:                                 } 
 3376:                             }
 3377:                         }
 3378:                     }
 3379:                 }
 3380:             }
 3381:             if ($guest) {
 3382:                 return $guest;
 3383:             }
 3384:         }
 3385:     }
 3386:     return;
 3387: }
 3388: 
 3389: sub course_group_datechecker {
 3390:     my ($dates,$now,$status) = @_;
 3391:     my ($start,$end) = split(/\./,$dates);
 3392:     if (!$start && !$end) {
 3393:         return 'ok';
 3394:     }
 3395:     if (grep/^active$/,@{$status}) {
 3396:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3397:             return 'ok';
 3398:         }
 3399:     }
 3400:     if (grep/^previous$/,@{$status}) {
 3401:         if ($end > $now ) {
 3402:             return 'ok';
 3403:         }
 3404:     }
 3405:     if (grep/^future$/,@{$status}) {
 3406:         if ($start > $now) {
 3407:             return 'ok';
 3408:         }
 3409:     }
 3410:     return; 
 3411: }
 3412: 
 3413: sub parse_portfolio_url {
 3414:     my ($url) = @_;
 3415: 
 3416:     my ($type,$udom,$unum,$group,$file_name);
 3417:     
 3418:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
 3419: 	$type = 1;
 3420:         $udom = $1;
 3421:         $unum = $2;
 3422:         $file_name = $3;
 3423:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
 3424: 	$type = 2;
 3425:         $udom = $1;
 3426:         $unum = $2;
 3427:         $group = $3;
 3428:         $file_name = $3.'/'.$4;
 3429:     }
 3430:     if (wantarray) {
 3431: 	return ($type,$udom,$unum,$file_name,$group);
 3432:     }
 3433:     return $type;
 3434: }
 3435: 
 3436: sub is_portfolio_url {
 3437:     my ($url) = @_;
 3438:     return scalar(&parse_portfolio_url($url));
 3439: }
 3440: 
 3441: # ---------------------------------------------- Custom access rule evaluation
 3442: 
 3443: sub customaccess {
 3444:     my ($priv,$uri)=@_;
 3445:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3446:     $urealm=~s/^\W//;
 3447:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3448:     my $access=0;
 3449:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3450: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3451:         if ($role) {
 3452: 	   if ($role ne $urole) { next; }
 3453:         }
 3454:         foreach (split(/\s*\,\s*/,$realm)) {
 3455:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3456:             if ($tdom) {
 3457: 		if ($tdom ne $udom) { next; }
 3458:             }
 3459:             if ($tcrs) {
 3460: 		if ($tcrs ne $ucrs) { next; }
 3461:             }
 3462:             if ($tsec) {
 3463: 		if ($tsec ne $usec) { next; }
 3464:             }
 3465:             $access=($effect eq 'allow');
 3466:             last;
 3467:         }
 3468: 	if ($realm eq '' && $role eq '') {
 3469:             $access=($effect eq 'allow');
 3470: 	}
 3471:     }
 3472:     return $access;
 3473: }
 3474: 
 3475: # ------------------------------------------------- Check for a user privilege
 3476: 
 3477: sub allowed {
 3478:     my ($priv,$uri,$symb)=@_;
 3479:     my $ver_orguri=$uri;
 3480:     $uri=&deversion($uri);
 3481:     my $orguri=$uri;
 3482:     $uri=&declutter($uri);
 3483:     
 3484:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3485: # Free bre access to adm and meta resources
 3486:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3487: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3488: 	&& ($priv eq 'bre')) {
 3489: 	return 'F';
 3490:     }
 3491: 
 3492: # Free bre access to user's own portfolio contents
 3493:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3494:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3495: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3496:         return 'F';
 3497:     }
 3498: 
 3499: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3500:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3501:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3502:         if (exists($env{'request.course.id'})) {
 3503:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3504:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3505:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3506:                 my $courseprivid=$env{'request.course.id'};
 3507:                 $courseprivid=~s/\_/\//;
 3508:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3509:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3510:                     return $1; 
 3511:                 } else {
 3512:                     if ($env{'request.course.sec'}) {
 3513:                         $courseprivid.='/'.$env{'request.course.sec'};
 3514:                     }
 3515:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3516:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3517:                         return $2;
 3518:                     }
 3519:                 }
 3520:             }
 3521:         }
 3522:     }
 3523: 
 3524: # Free bre to public access
 3525: 
 3526:     if ($priv eq 'bre') {
 3527:         my $copyright=&metadata($uri,'copyright');
 3528: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3529:            return 'F'; 
 3530:         }
 3531:         if ($copyright eq 'priv') {
 3532:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3533: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3534: 		return '';
 3535:             }
 3536:         }
 3537:         if ($copyright eq 'domain') {
 3538:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3539: 	    unless (($env{'user.domain'} eq $1) ||
 3540:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3541: 		return '';
 3542:             }
 3543:         }
 3544:         if ($env{'request.role'}=~ /li\.\//) {
 3545:             # Library role, so allow browsing of resources in this domain.
 3546:             return 'F';
 3547:         }
 3548:         if ($copyright eq 'custom') {
 3549: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3550:         }
 3551:     }
 3552:     # Domain coordinator is trying to create a course
 3553:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3554:         # uri is the requested domain in this case.
 3555:         # comparison to 'request.role.domain' shows if the user has selected
 3556:         # a role of dc for the domain in question.
 3557:         return 'F' if ($uri eq $env{'request.role.domain'});
 3558:     }
 3559: 
 3560:     my $thisallowed='';
 3561:     my $statecond=0;
 3562:     my $courseprivid='';
 3563: 
 3564: # Course
 3565: 
 3566:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3567:        $thisallowed.=$1;
 3568:     }
 3569: 
 3570: # Domain
 3571: 
 3572:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3573:        =~/\Q$priv\E\&([^\:]*)/) {
 3574:        $thisallowed.=$1;
 3575:     }
 3576: 
 3577: # Course: uri itself is a course
 3578:     my $courseuri=$uri;
 3579:     $courseuri=~s/\_(\d)/\/$1/;
 3580:     $courseuri=~s/^([^\/])/\/$1/;
 3581: 
 3582:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3583:        =~/\Q$priv\E\&([^\:]*)/) {
 3584:        $thisallowed.=$1;
 3585:     }
 3586: 
 3587: # URI is an uploaded document for this course, default permissions don't matter
 3588: # not allowing 'edit' access (editupload) to uploaded course docs
 3589:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3590: 	$thisallowed='';
 3591:         my ($match)=&is_on_map($uri);
 3592:         if ($match) {
 3593:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3594:                   =~/\Q$priv\E\&([^\:]*)/) {
 3595:                 $thisallowed.=$1;
 3596:             }
 3597:         } else {
 3598:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3599:             if ($refuri) {
 3600:                 if ($refuri =~ m|^/adm/|) {
 3601:                     $thisallowed='F';
 3602:                 } else {
 3603:                     $refuri=&declutter($refuri);
 3604:                     my ($match) = &is_on_map($refuri);
 3605:                     if ($match) {
 3606:                         $thisallowed='F';
 3607:                     }
 3608:                 }
 3609:             }
 3610:         }
 3611:     }
 3612: 
 3613:     if ($priv eq 'bre'
 3614: 	&& $thisallowed ne 'F' 
 3615: 	&& $thisallowed ne '2'
 3616: 	&& &is_portfolio_url($uri)) {
 3617: 	$thisallowed = &portfolio_access($uri);
 3618:     }
 3619:     
 3620: # Full access at system, domain or course-wide level? Exit.
 3621: 
 3622:     if ($thisallowed=~/F/) {
 3623: 	return 'F';
 3624:     }
 3625: 
 3626: # If this is generating or modifying users, exit with special codes
 3627: 
 3628:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3629: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3630: 	    my ($audom,$auname)=split('/',$uri);
 3631: # no author name given, so this just checks on the general right to make a co-author in this domain
 3632: 	    unless ($auname) { return $thisallowed; }
 3633: # an author name is given, so we are about to actually make a co-author for a certain account
 3634: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3635: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3636: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3637: 	}
 3638: 	return $thisallowed;
 3639:     }
 3640: #
 3641: # Gathered so far: system, domain and course wide privileges
 3642: #
 3643: # Course: See if uri or referer is an individual resource that is part of 
 3644: # the course
 3645: 
 3646:     if ($env{'request.course.id'}) {
 3647: 
 3648:        $courseprivid=$env{'request.course.id'};
 3649:        if ($env{'request.course.sec'}) {
 3650:           $courseprivid.='/'.$env{'request.course.sec'};
 3651:        }
 3652:        $courseprivid=~s/\_/\//;
 3653:        my $checkreferer=1;
 3654:        my ($match,$cond)=&is_on_map($uri);
 3655:        if ($match) {
 3656:            $statecond=$cond;
 3657:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3658:                =~/\Q$priv\E\&([^\:]*)/) {
 3659:                $thisallowed.=$1;
 3660:                $checkreferer=0;
 3661:            }
 3662:        }
 3663:        
 3664:        if ($checkreferer) {
 3665: 	  my $refuri=$env{'httpref.'.$orguri};
 3666:             unless ($refuri) {
 3667:                 foreach (keys %env) {
 3668: 		    if ($_=~/^httpref\..*\*/) {
 3669: 			my $pattern=$_;
 3670:                         $pattern=~s/^httpref\.\/res\///;
 3671:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3672:                         $pattern=~s/\//\\\//g;
 3673:                         if ($orguri=~/$pattern/) {
 3674: 			    $refuri=$env{$_};
 3675:                         }
 3676:                     }
 3677:                 }
 3678:             }
 3679: 
 3680:          if ($refuri) { 
 3681: 	  $refuri=&declutter($refuri);
 3682:           my ($match,$cond)=&is_on_map($refuri);
 3683:             if ($match) {
 3684:               my $refstatecond=$cond;
 3685:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3686:                   =~/\Q$priv\E\&([^\:]*)/) {
 3687:                   $thisallowed.=$1;
 3688:                   $uri=$refuri;
 3689:                   $statecond=$refstatecond;
 3690:               }
 3691:           }
 3692:         }
 3693:        }
 3694:    }
 3695: 
 3696: #
 3697: # Gathered now: all privileges that could apply, and condition number
 3698: # 
 3699: #
 3700: # Full or no access?
 3701: #
 3702: 
 3703:     if ($thisallowed=~/F/) {
 3704: 	return 'F';
 3705:     }
 3706: 
 3707:     unless ($thisallowed) {
 3708:         return '';
 3709:     }
 3710: 
 3711: # Restrictions exist, deal with them
 3712: #
 3713: #   C:according to course preferences
 3714: #   R:according to resource settings
 3715: #   L:unless locked
 3716: #   X:according to user session state
 3717: #
 3718: 
 3719: # Possibly locked functionality, check all courses
 3720: # Locks might take effect only after 10 minutes cache expiration for other
 3721: # courses, and 2 minutes for current course
 3722: 
 3723:     my $envkey;
 3724:     if ($thisallowed=~/L/) {
 3725:         foreach $envkey (keys %env) {
 3726:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3727:                my $courseid=$2;
 3728:                my $roleid=$1.'.'.$2;
 3729:                $courseid=~s/^\///;
 3730:                my $expiretime=600;
 3731:                if ($env{'request.role'} eq $roleid) {
 3732: 		  $expiretime=120;
 3733:                }
 3734: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3735:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3736:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3737: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3738:                }
 3739:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3740:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3741: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3742:                        &log($env{'user.domain'},$env{'user.name'},
 3743:                             $env{'user.home'},
 3744:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3745:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3746:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3747: 		       return '';
 3748:                    }
 3749:                }
 3750:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3751:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3752: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3753:                        &log($env{'user.domain'},$env{'user.name'},
 3754:                             $env{'user.home'},
 3755:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3756:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3757:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3758: 		       return '';
 3759:                    }
 3760:                }
 3761: 	   }
 3762:        }
 3763:     }
 3764:    
 3765: #
 3766: # Rest of the restrictions depend on selected course
 3767: #
 3768: 
 3769:     unless ($env{'request.course.id'}) {
 3770: 	if ($thisallowed eq 'A') {
 3771: 	    return 'A';
 3772: 	} else {
 3773: 	    return '1';
 3774: 	}
 3775:     }
 3776: 
 3777: #
 3778: # Now user is definitely in a course
 3779: #
 3780: 
 3781: 
 3782: # Course preferences
 3783: 
 3784:    if ($thisallowed=~/C/) {
 3785:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3786:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3787:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3788: 	   =~/\Q$rolecode\E/) {
 3789: 	   if ($priv ne 'pch') { 
 3790: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3791: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3792: 			$env{'request.course.id'});
 3793: 	   }
 3794:            return '';
 3795:        }
 3796: 
 3797:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3798: 	   =~/\Q$unamedom\E/) {
 3799: 	   if ($priv ne 'pch') { 
 3800: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3801: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3802: 			$env{'request.course.id'});
 3803: 	   }
 3804:            return '';
 3805:        }
 3806:    }
 3807: 
 3808: # Resource preferences
 3809: 
 3810:    if ($thisallowed=~/R/) {
 3811:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3812:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3813: 	   if ($priv ne 'pch') { 
 3814: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3815: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3816: 	   }
 3817: 	   return '';
 3818:        }
 3819:    }
 3820: 
 3821: # Restricted by state or randomout?
 3822: 
 3823:    if ($thisallowed=~/X/) {
 3824:       if ($env{'acc.randomout'}) {
 3825: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3826:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3827:             return ''; 
 3828:          }
 3829:       }
 3830:       if (&condval($statecond)) {
 3831: 	 return '2';
 3832:       } else {
 3833:          return '';
 3834:       }
 3835:    }
 3836: 
 3837:     if ($thisallowed eq 'A') {
 3838: 	return 'A';
 3839:     }
 3840:    return 'F';
 3841: }
 3842: 
 3843: sub split_uri_for_cond {
 3844:     my $uri=&deversion(&declutter(shift));
 3845:     my @uriparts=split(/\//,$uri);
 3846:     my $filename=pop(@uriparts);
 3847:     my $pathname=join('/',@uriparts);
 3848:     return ($pathname,$filename);
 3849: }
 3850: # --------------------------------------------------- Is a resource on the map?
 3851: 
 3852: sub is_on_map {
 3853:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3854:     #Trying to find the conditional for the file
 3855:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3856: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3857:     if ($match) {
 3858: 	return (1,$1);
 3859:     } else {
 3860: 	return (0,0);
 3861:     }
 3862: }
 3863: 
 3864: # --------------------------------------------------------- Get symb from alias
 3865: 
 3866: sub get_symb_from_alias {
 3867:     my $symb=shift;
 3868:     my ($map,$resid,$url)=&decode_symb($symb);
 3869: # Already is a symb
 3870:     if ($url) { return $symb; }
 3871: # Must be an alias
 3872:     my $aliassymb='';
 3873:     my %bighash;
 3874:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3875:                             &GDBM_READER(),0640)) {
 3876:         my $rid=$bighash{'mapalias_'.$symb};
 3877: 	if ($rid) {
 3878: 	    my ($mapid,$resid)=split(/\./,$rid);
 3879: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3880: 				    $resid,$bighash{'src_'.$rid});
 3881: 	}
 3882:         untie %bighash;
 3883:     }
 3884:     return $aliassymb;
 3885: }
 3886: 
 3887: # ----------------------------------------------------------------- Define Role
 3888: 
 3889: sub definerole {
 3890:   if (allowed('mcr','/')) {
 3891:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3892:     foreach (split(':',$sysrole)) {
 3893: 	my ($crole,$cqual)=split(/\&/,$_);
 3894:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3895:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3896: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3897:                return "refused:s:$crole&$cqual"; 
 3898:             }
 3899:         }
 3900:     }
 3901:     foreach (split(':',$domrole)) {
 3902: 	my ($crole,$cqual)=split(/\&/,$_);
 3903:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3904:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3905: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3906:                return "refused:d:$crole&$cqual"; 
 3907:             }
 3908:         }
 3909:     }
 3910:     foreach (split(':',$courole)) {
 3911: 	my ($crole,$cqual)=split(/\&/,$_);
 3912:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3913:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3914: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3915:                return "refused:c:$crole&$cqual"; 
 3916:             }
 3917:         }
 3918:     }
 3919:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3920:                 "$env{'user.domain'}:$env{'user.name'}:".
 3921: 	        "rolesdef_$rolename=".
 3922:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3923:     return reply($command,$env{'user.home'});
 3924:   } else {
 3925:     return 'refused';
 3926:   }
 3927: }
 3928: 
 3929: # ---------------- Make a metadata query against the network of library servers
 3930: 
 3931: sub metadata_query {
 3932:     my ($query,$custom,$customshow,$server_array)=@_;
 3933:     my %rhash;
 3934:     my @server_list = (defined($server_array) ? @$server_array
 3935:                                               : keys(%libserv) );
 3936:     for my $server (@server_list) {
 3937: 	unless ($custom or $customshow) {
 3938: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3939: 	    $rhash{$server}=$reply;
 3940: 	}
 3941: 	else {
 3942: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3943: 			     &escape($custom).':'.&escape($customshow),
 3944: 			     $server);
 3945: 	    $rhash{$server}=$reply;
 3946: 	}
 3947:     }
 3948:     return \%rhash;
 3949: }
 3950: 
 3951: # ----------------------------------------- Send log queries and wait for reply
 3952: 
 3953: sub log_query {
 3954:     my ($uname,$udom,$query,%filters)=@_;
 3955:     my $uhome=&homeserver($uname,$udom);
 3956:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3957:     my $uhost=$hostname{$uhome};
 3958:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3959:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3960:                        $uhome);
 3961:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3962:     return get_query_reply($queryid);
 3963: }
 3964: 
 3965: # ------- Request retrieval of institutional classlists for course(s)
 3966: 
 3967: sub fetch_enrollment_query {
 3968:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3969:     my $homeserver;
 3970:     my $maxtries = 1;
 3971:     if ($context eq 'automated') {
 3972:         $homeserver = $perlvar{'lonHostID'};
 3973:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3974:     } else {
 3975:         $homeserver = &homeserver($cnum,$dom);
 3976:     }
 3977:     my $host=$hostname{$homeserver};
 3978:     my $cmd = '';
 3979:     foreach (keys %{$affiliatesref}) {
 3980:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3981:     }
 3982:     $cmd =~ s/%%$//;
 3983:     $cmd = &escape($cmd);
 3984:     my $query = 'fetchenrollment';
 3985:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3986:     unless ($queryid=~/^\Q$host\E\_/) { 
 3987:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3988:         return 'error: '.$queryid;
 3989:     }
 3990:     my $reply = &get_query_reply($queryid);
 3991:     my $tries = 1;
 3992:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3993:         $reply = &get_query_reply($queryid);
 3994:         $tries ++;
 3995:     }
 3996:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3997:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3998:     } else {
 3999:         my @responses = split/:/,$reply;
 4000:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4001:             foreach (@responses) {
 4002:                 my ($key,$value) = split/=/,$_;
 4003:                 $$replyref{$key} = $value;
 4004:             }
 4005:         } else {
 4006:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4007:             foreach (@responses) {
 4008:                 my ($key,$value) = split/=/,$_;
 4009:                 $$replyref{$key} = $value;
 4010:                 if ($value > 0) {
 4011:                     foreach (@{$$affiliatesref{$key}}) {
 4012:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 4013:                         my $destname = $pathname.'/'.$filename;
 4014:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4015:                         if ($xml_classlist =~ /^error/) {
 4016:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4017:                         } else {
 4018:                             if ( open(FILE,">$destname") ) {
 4019:                                 print FILE &unescape($xml_classlist);
 4020:                                 close(FILE);
 4021:                             } else {
 4022:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4023:                             }
 4024:                         }
 4025:                     }
 4026:                 }
 4027:             }
 4028:         }
 4029:         return 'ok';
 4030:     }
 4031:     return 'error';
 4032: }
 4033: 
 4034: sub get_query_reply {
 4035:     my $queryid=shift;
 4036:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4037:     my $reply='';
 4038:     for (1..100) {
 4039: 	sleep 2;
 4040:         if (-e $replyfile.'.end') {
 4041: 	    if (open(my $fh,$replyfile)) {
 4042:                $reply.=<$fh>;
 4043:                close($fh);
 4044: 	   } else { return 'error: reply_file_error'; }
 4045:            return &unescape($reply);
 4046: 	}
 4047:     }
 4048:     return 'timeout:'.$queryid;
 4049: }
 4050: 
 4051: sub courselog_query {
 4052: #
 4053: # possible filters:
 4054: # url: url or symb
 4055: # username
 4056: # domain
 4057: # action: view, submit, grade
 4058: # start: timestamp
 4059: # end: timestamp
 4060: #
 4061:     my (%filters)=@_;
 4062:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4063:     if ($filters{'url'}) {
 4064: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4065:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4066:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4067:     }
 4068:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4069:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4070:     return &log_query($cname,$cdom,'courselog',%filters);
 4071: }
 4072: 
 4073: sub userlog_query {
 4074:     my ($uname,$udom,%filters)=@_;
 4075:     return &log_query($uname,$udom,'userlog',%filters);
 4076: }
 4077: 
 4078: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4079: 
 4080: sub auto_run {
 4081:     my ($cnum,$cdom) = @_;
 4082:     my $homeserver = &homeserver($cnum,$cdom);
 4083:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4084:     return $response;
 4085: }
 4086: 
 4087: sub auto_get_sections {
 4088:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4089:     my $homeserver = &homeserver($cnum,$cdom);
 4090:     my @secs = ();
 4091:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4092:     unless ($response eq 'refused') {
 4093:         @secs = split/:/,$response;
 4094:     }
 4095:     return @secs;
 4096: }
 4097: 
 4098: sub auto_new_course {
 4099:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4100:     my $homeserver = &homeserver($cnum,$cdom);
 4101:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4102:     return $response;
 4103: }
 4104: 
 4105: sub auto_validate_courseID {
 4106:     my ($cnum,$cdom,$inst_course_id) = @_;
 4107:     my $homeserver = &homeserver($cnum,$cdom);
 4108:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4109:     return $response;
 4110: }
 4111: 
 4112: sub auto_create_password {
 4113:     my ($cnum,$cdom,$authparam) = @_;
 4114:     my $homeserver = &homeserver($cnum,$cdom); 
 4115:     my $create_passwd = 0;
 4116:     my $authchk = '';
 4117:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4118:     if ($response eq 'refused') {
 4119:         $authchk = 'refused';
 4120:     } else {
 4121:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4122:     }
 4123:     return ($authparam,$create_passwd,$authchk);
 4124: }
 4125: 
 4126: sub auto_photo_permission {
 4127:     my ($cnum,$cdom,$students) = @_;
 4128:     my $homeserver = &homeserver($cnum,$cdom);
 4129:     my ($outcome,$perm_reqd,$conditions) = 
 4130: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4131:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4132: 	return (undef,undef);
 4133:     }
 4134:     return ($outcome,$perm_reqd,$conditions);
 4135: }
 4136: 
 4137: sub auto_checkphotos {
 4138:     my ($uname,$udom,$pid) = @_;
 4139:     my $homeserver = &homeserver($uname,$udom);
 4140:     my ($result,$resulttype);
 4141:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4142: 				   &escape($uname).':'.&escape($pid),
 4143: 				   $homeserver));
 4144:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4145: 	return (undef,undef);
 4146:     }
 4147:     if ($outcome) {
 4148:         ($result,$resulttype) = split(/:/,$outcome);
 4149:     } 
 4150:     return ($result,$resulttype);
 4151: }
 4152: 
 4153: sub auto_photochoice {
 4154:     my ($cnum,$cdom) = @_;
 4155:     my $homeserver = &homeserver($cnum,$cdom);
 4156:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4157: 						       &escape($cdom),
 4158: 						       $homeserver)));
 4159:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4160: 	return (undef,undef);
 4161:     }
 4162:     return ($update,$comment);
 4163: }
 4164: 
 4165: sub auto_photoupdate {
 4166:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4167:     my $homeserver = &homeserver($cnum,$dom);
 4168:     my $host=$hostname{$homeserver};
 4169:     my $cmd = '';
 4170:     my $maxtries = 1;
 4171:     foreach (keys %{$affiliatesref}) {
 4172:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 4173:     }
 4174:     $cmd =~ s/%%$//;
 4175:     $cmd = &escape($cmd);
 4176:     my $query = 'institutionalphotos';
 4177:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4178:     unless ($queryid=~/^\Q$host\E\_/) {
 4179:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4180:         return 'error: '.$queryid;
 4181:     }
 4182:     my $reply = &get_query_reply($queryid);
 4183:     my $tries = 1;
 4184:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4185:         $reply = &get_query_reply($queryid);
 4186:         $tries ++;
 4187:     }
 4188:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4189:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4190:     } else {
 4191:         my @responses = split(/:/,$reply);
 4192:         my $outcome = shift(@responses); 
 4193:         foreach my $item (@responses) {
 4194:             my ($key,$value) = split(/=/,$item);
 4195:             $$photo{$key} = $value;
 4196:         }
 4197:         return $outcome;
 4198:     }
 4199:     return 'error';
 4200: }
 4201: 
 4202: sub auto_instcode_format {
 4203:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 4204:     my $courses = '';
 4205:     my @homeservers;
 4206:     if ($caller eq 'global') {
 4207:         foreach my $tryserver (keys %libserv) {
 4208:             if ($hostdom{$tryserver} eq $codedom) {
 4209:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
 4210:                     push(@homeservers,$tryserver);
 4211:                 }
 4212:             }
 4213:         }
 4214:     } else {
 4215:         push(@homeservers,&homeserver($caller,$codedom));
 4216:     }
 4217:     foreach (keys %{$instcodes}) {
 4218:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 4219:     }
 4220:     chop($courses);
 4221:     my $ok_response = 0;
 4222:     my $response;
 4223:     while (@homeservers > 0 && $ok_response == 0) {
 4224:         my $server = shift(@homeservers); 
 4225:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4226:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4227:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4228:                                                             split/:/,$response;
 4229:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4230:             push(@{$codetitles},&str2array($codetitles_str));
 4231:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4232:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4233:             $ok_response = 1;
 4234:         }
 4235:     }
 4236:     if ($ok_response) {
 4237:         return 'ok';
 4238:     } else {
 4239:         return $response;
 4240:     }
 4241: }
 4242: 
 4243: sub auto_validate_class_sec {
 4244:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4245:     my $homeserver = &homeserver($cnum,$cdom);
 4246:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4247:                         &escape($owner).':'.$cdom,$homeserver);
 4248:     return $response;
 4249: }
 4250: 
 4251: # ------------------------------------------------------- Course Group routines
 4252: 
 4253: sub get_coursegroups {
 4254:     my ($cdom,$cnum,$group) = @_;
 4255:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4256: }
 4257: 
 4258: sub modify_coursegroup {
 4259:     my ($cdom,$cnum,$groupsettings) = @_;
 4260:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4261: }
 4262: 
 4263: sub modify_group_roles {
 4264:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4265:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4266:     my $role = 'gr/'.&escape($userprivs);
 4267:     my ($uname,$udom) = split(/:/,$user);
 4268:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4269:     if ($result eq 'ok') {
 4270:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4271:     }
 4272:     return $result;
 4273: }
 4274: 
 4275: sub modify_coursegroup_membership {
 4276:     my ($cdom,$cnum,$membership) = @_;
 4277:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4278:     return $result;
 4279: }
 4280: 
 4281: sub get_active_groups {
 4282:     my ($udom,$uname,$cdom,$cnum) = @_;
 4283:     my $now = time;
 4284:     my %groups = ();
 4285:     foreach my $key (keys(%env)) {
 4286:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4287:             my ($start,$end) = split(/\./,$env{$key});
 4288:             if (($end!=0) && ($end<$now)) { next; }
 4289:             if (($start!=0) && ($start>$now)) { next; }
 4290:             if ($1 eq $cdom && $2 eq $cnum) {
 4291:                 $groups{$3} = $env{$key} ;
 4292:             }
 4293:         }
 4294:     }
 4295:     return %groups;
 4296: }
 4297: 
 4298: sub get_group_membership {
 4299:     my ($cdom,$cnum,$group) = @_;
 4300:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4301: }
 4302: 
 4303: sub get_users_groups {
 4304:     my ($udom,$uname,$courseid) = @_;
 4305:     my @usersgroups;
 4306:     my $cachetime=1800;
 4307:     $courseid=~s/\_/\//g;
 4308:     $courseid=~s/^(\w)/\/$1/;
 4309: 
 4310:     my $hashid="$udom:$uname:$courseid";
 4311:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4312:     if (defined($cached)) {
 4313:         @usersgroups = split(/:/,$grouplist);
 4314:     } else {  
 4315:         $grouplist = '';
 4316:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4317:         my ($tmp) = keys(%roleshash);
 4318:         if ($tmp=~/^error:/) {
 4319:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4320:         } else {
 4321:             my $access_end = $env{'course.'.$courseid.
 4322:                                   '.default_enrollment_end_date'};
 4323:             my $now = time;
 4324:             foreach my $key (keys(%roleshash)) {
 4325:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4326:                     my $group = $1;
 4327:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4328:                         my $start = $2;
 4329:                         my $end = $1;
 4330:                         if ($start == -1) { next; } # deleted from group
 4331:                         if (($start!=0) && ($start>$now)) { next; }
 4332:                         if (($end!=0) && ($end<$now)) {
 4333:                             if ($access_end && $access_end < $now) {
 4334:                                 if ($access_end - $end < 86400) {
 4335:                                     push(@usersgroups,$group);
 4336:                                 }
 4337:                             }
 4338:                             next;
 4339:                         }
 4340:                         push(@usersgroups,$group);
 4341:                     }
 4342:                 }
 4343:             }
 4344:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4345:             $grouplist = join(':',@usersgroups);
 4346:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4347:         }
 4348:     }
 4349:     return @usersgroups;
 4350: }
 4351: 
 4352: sub devalidate_getgroups_cache {
 4353:     my ($udom,$uname,$cdom,$cnum)=@_;
 4354:     my $courseid = $cdom.'_'.$cnum;
 4355:     $courseid=~s/\_/\//g;
 4356:     $courseid=~s/^(\w)/\/$1/;
 4357:     my $hashid="$udom:$uname:$courseid";
 4358:     &devalidate_cache_new('getgroups',$hashid);
 4359: }
 4360: 
 4361: # ------------------------------------------------------------------ Plain Text
 4362: 
 4363: sub plaintext {
 4364:     my ($short,$type,$cid) = @_;
 4365:     if ($short =~ /^cr/) {
 4366: 	return (split('/',$short))[-1];
 4367:     }
 4368:     if (!defined($cid)) {
 4369:         $cid = $env{'request.course.id'};
 4370:     }
 4371:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4372:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4373:                                           '.plaintext'});
 4374:     }
 4375:     my %rolenames = (
 4376:                       Course => 'std',
 4377:                       Group => 'alt1',
 4378:                     );
 4379:     if (defined($type) && 
 4380:          defined($rolenames{$type}) && 
 4381:          defined($prp{$short}{$rolenames{$type}})) {
 4382:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4383:     } else {
 4384:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4385:     }
 4386: }
 4387: 
 4388: # ----------------------------------------------------------------- Assign Role
 4389: 
 4390: sub assignrole {
 4391:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4392:     my $mrole;
 4393:     if ($role =~ /^cr\//) {
 4394:         my $cwosec=$url;
 4395:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4396: 	unless (&allowed('ccr',$cwosec)) {
 4397:            &logthis('Refused custom assignrole: '.
 4398:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4399: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4400:            return 'refused'; 
 4401:         }
 4402:         $mrole='cr';
 4403:     } elsif ($role =~ /^gr\//) {
 4404:         my $cwogrp=$url;
 4405:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4406:         unless (&allowed('mdg',$cwogrp)) {
 4407:             &logthis('Refused group assignrole: '.
 4408:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4409:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4410:             return 'refused';
 4411:         }
 4412:         $mrole='gr';
 4413:     } else {
 4414:         my $cwosec=$url;
 4415:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4416:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4417:            &logthis('Refused assignrole: '.
 4418:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4419: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4420:            return 'refused'; 
 4421:         }
 4422:         $mrole=$role;
 4423:     }
 4424:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4425:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4426:     if ($end) { $command.='_'.$end; }
 4427:     if ($start) {
 4428: 	if ($end) { 
 4429:            $command.='_'.$start; 
 4430:         } else {
 4431:            $command.='_0_'.$start;
 4432:         }
 4433:     }
 4434:     my $origstart = $start;
 4435:     my $origend = $end;
 4436: # actually delete
 4437:     if ($deleteflag) {
 4438: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4439: # modify command to delete the role
 4440:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4441:                 "$udom:$uname:$url".'_'."$mrole";
 4442: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4443: # set start and finish to negative values for userrolelog
 4444:            $start=-1;
 4445:            $end=-1;
 4446:         }
 4447:     }
 4448: # send command
 4449:     my $answer=&reply($command,&homeserver($uname,$udom));
 4450: # log new user role if status is ok
 4451:     if ($answer eq 'ok') {
 4452: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4453: # for course roles, perform group memberships changes triggered by role change.
 4454:         unless ($role =~ /^gr/) {
 4455:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4456:                                              $origstart);
 4457:         }
 4458:     }
 4459:     return $answer;
 4460: }
 4461: 
 4462: # -------------------------------------------------- Modify user authentication
 4463: # Overrides without validation
 4464: 
 4465: sub modifyuserauth {
 4466:     my ($udom,$uname,$umode,$upass)=@_;
 4467:     my $uhome=&homeserver($uname,$udom);
 4468:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4469:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4470:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4471:              ' in domain '.$env{'request.role.domain'});  
 4472:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4473: 		     &escape($upass),$uhome);
 4474:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4475:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4476:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4477:     &log($udom,,$uname,$uhome,
 4478:         'Authentication changed by '.$env{'user.domain'}.', '.
 4479:                                      $env{'user.name'}.', '.$umode.
 4480:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4481:     unless ($reply eq 'ok') {
 4482:         &logthis('Authentication mode error: '.$reply);
 4483: 	return 'error: '.$reply;
 4484:     }   
 4485:     return 'ok';
 4486: }
 4487: 
 4488: # --------------------------------------------------------------- Modify a user
 4489: 
 4490: sub modifyuser {
 4491:     my ($udom,    $uname, $uid,
 4492:         $umode,   $upass, $first,
 4493:         $middle,  $last,  $gene,
 4494:         $forceid, $desiredhome, $email)=@_;
 4495:     $udom=~s/\W//g;
 4496:     $uname=~s/\W//g;
 4497:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4498:              $umode.', '.$first.', '.$middle.', '.
 4499: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4500:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4501:                                      ' desiredhome not specified'). 
 4502:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4503:              ' in domain '.$env{'request.role.domain'});
 4504:     my $uhome=&homeserver($uname,$udom,'true');
 4505: # ----------------------------------------------------------------- Create User
 4506:     if (($uhome eq 'no_host') && 
 4507: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4508:         my $unhome='';
 4509:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4510:             $unhome = $desiredhome;
 4511: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4512: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4513:         } else { # load balancing routine for determining $unhome
 4514:             my $tryserver;
 4515:             my $loadm=10000000;
 4516:             foreach $tryserver (keys %libserv) {
 4517: 	       if ($hostdom{$tryserver} eq $udom) {
 4518:                   my $answer=reply('load',$tryserver);
 4519:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4520: 		      $loadm=$answer;
 4521:                       $unhome=$tryserver;
 4522:                   }
 4523: 	       }
 4524: 	    }
 4525:         }
 4526:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4527: 	    return 'error: unable to find a home server for '.$uname.
 4528:                    ' in domain '.$udom;
 4529:         }
 4530:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4531:                          &escape($upass),$unhome);
 4532: 	unless ($reply eq 'ok') {
 4533:             return 'error: '.$reply;
 4534:         }   
 4535:         $uhome=&homeserver($uname,$udom,'true');
 4536:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4537: 	    return 'error: unable verify users home machine.';
 4538:         }
 4539:     }   # End of creation of new user
 4540: # ---------------------------------------------------------------------- Add ID
 4541:     if ($uid) {
 4542:        $uid=~tr/A-Z/a-z/;
 4543:        my %uidhash=&idrget($udom,$uname);
 4544:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4545:          && (!$forceid)) {
 4546: 	  unless ($uid eq $uidhash{$uname}) {
 4547: 	      return 'error: user id "'.$uid.'" does not match '.
 4548:                   'current user id "'.$uidhash{$uname}.'".';
 4549:           }
 4550:        } else {
 4551: 	  &idput($udom,($uname => $uid));
 4552:        }
 4553:     }
 4554: # -------------------------------------------------------------- Add names, etc
 4555:     my @tmp=&get('environment',
 4556: 		   ['firstname','middlename','lastname','generation'],
 4557: 		   $udom,$uname);
 4558:     my %names;
 4559:     if ($tmp[0] =~ m/^error:.*/) { 
 4560:         %names=(); 
 4561:     } else {
 4562:         %names = @tmp;
 4563:     }
 4564: #
 4565: # Make sure to not trash student environment if instructor does not bother
 4566: # to supply name and email information
 4567: #
 4568:     if ($first)  { $names{'firstname'}  = $first; }
 4569:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4570:     if ($last)   { $names{'lastname'}   = $last; }
 4571:     if (defined($gene))   { $names{'generation'} = $gene; }
 4572:     if ($email) {
 4573:        $email=~s/[^\w\@\.\-\,]//gs;
 4574:        if ($email=~/\@/) { $names{'notification'} = $email;
 4575: 			   $names{'critnotification'} = $email;
 4576: 			   $names{'permanentemail'} = $email; }
 4577:     }
 4578:     my $reply = &put('environment', \%names, $udom,$uname);
 4579:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4580:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4581:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4582:              $umode.', '.$first.', '.$middle.', '.
 4583: 	     $last.', '.$gene.' by '.
 4584:              $env{'user.name'}.' at '.$env{'user.domain'});
 4585:     return 'ok';
 4586: }
 4587: 
 4588: # -------------------------------------------------------------- Modify student
 4589: 
 4590: sub modifystudent {
 4591:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4592:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4593:     if (!$cid) {
 4594: 	unless ($cid=$env{'request.course.id'}) {
 4595: 	    return 'not_in_class';
 4596: 	}
 4597:     }
 4598: # --------------------------------------------------------------- Make the user
 4599:     my $reply=&modifyuser
 4600: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4601:          $desiredhome,$email);
 4602:     unless ($reply eq 'ok') { return $reply; }
 4603:     # This will cause &modify_student_enrollment to get the uid from the
 4604:     # students environment
 4605:     $uid = undef if (!$forceid);
 4606:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4607: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4608:     return $reply;
 4609: }
 4610: 
 4611: sub modify_student_enrollment {
 4612:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4613:     my ($cdom,$cnum,$chome);
 4614:     if (!$cid) {
 4615: 	unless ($cid=$env{'request.course.id'}) {
 4616: 	    return 'not_in_class';
 4617: 	}
 4618: 	$cdom=$env{'course.'.$cid.'.domain'};
 4619: 	$cnum=$env{'course.'.$cid.'.num'};
 4620:     } else {
 4621: 	($cdom,$cnum)=split(/_/,$cid);
 4622:     }
 4623:     $chome=$env{'course.'.$cid.'.home'};
 4624:     if (!$chome) {
 4625: 	$chome=&homeserver($cnum,$cdom);
 4626:     }
 4627:     if (!$chome) { return 'unknown_course'; }
 4628:     # Make sure the user exists
 4629:     my $uhome=&homeserver($uname,$udom);
 4630:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4631: 	return 'error: no such user';
 4632:     }
 4633:     # Get student data if we were not given enough information
 4634:     if (!defined($first)  || $first  eq '' || 
 4635:         !defined($last)   || $last   eq '' || 
 4636:         !defined($uid)    || $uid    eq '' || 
 4637:         !defined($middle) || $middle eq '' || 
 4638:         !defined($gene)   || $gene   eq '') {
 4639:         # They did not supply us with enough data to enroll the student, so
 4640:         # we need to pick up more information.
 4641:         my %tmp = &get('environment',
 4642:                        ['firstname','middlename','lastname', 'generation','id']
 4643:                        ,$udom,$uname);
 4644: 
 4645:         #foreach (keys(%tmp)) {
 4646:         #    &logthis("key $_ = ".$tmp{$_});
 4647:         #}
 4648:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4649:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4650:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4651:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4652:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4653:     }
 4654:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4655:     my $reply=cput('classlist',
 4656: 		   {"$uname:$udom" => 
 4657: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4658: 		   $cdom,$cnum);
 4659:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4660: 	return 'error: '.$reply;
 4661:     } else {
 4662: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4663:     }
 4664:     # Add student role to user
 4665:     my $uurl='/'.$cid;
 4666:     $uurl=~s/\_/\//g;
 4667:     if ($usec) {
 4668: 	$uurl.='/'.$usec;
 4669:     }
 4670:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4671: }
 4672: 
 4673: sub format_name {
 4674:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4675:     my $name;
 4676:     if ($first ne 'lastname') {
 4677: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4678:     } else {
 4679: 	if ($lastname=~/\S/) {
 4680: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4681: 	    $name=~s/\s+,/,/;
 4682: 	} else {
 4683: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4684: 	}
 4685:     }
 4686:     $name=~s/^\s+//;
 4687:     $name=~s/\s+$//;
 4688:     $name=~s/\s+/ /g;
 4689:     return $name;
 4690: }
 4691: 
 4692: # ------------------------------------------------- Write to course preferences
 4693: 
 4694: sub writecoursepref {
 4695:     my ($courseid,%prefs)=@_;
 4696:     $courseid=~s/^\///;
 4697:     $courseid=~s/\_/\//g;
 4698:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4699:     my $chome=homeserver($cnum,$cdomain);
 4700:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4701: 	return 'error: no such course';
 4702:     }
 4703:     my $cstring='';
 4704:     foreach (keys %prefs) {
 4705: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4706:     }
 4707:     $cstring=~s/\&$//;
 4708:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4709: }
 4710: 
 4711: # ---------------------------------------------------------- Make/modify course
 4712: 
 4713: sub createcourse {
 4714:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4715:         $course_owner,$crstype)=@_;
 4716:     $url=&declutter($url);
 4717:     my $cid='';
 4718:     unless (&allowed('ccc',$udom)) {
 4719:         return 'refused';
 4720:     }
 4721: # ------------------------------------------------------------------- Create ID
 4722:    my $uname=int(1+rand(9)).
 4723:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4724:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4725:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4726: # ----------------------------------------------- Make sure that does not exist
 4727:    my $uhome=&homeserver($uname,$udom,'true');
 4728:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4729:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4730:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4731:        $uhome=&homeserver($uname,$udom,'true');       
 4732:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4733:            return 'error: unable to generate unique course-ID';
 4734:        } 
 4735:    }
 4736: # ------------------------------------------------ Check supplied server name
 4737:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4738:     if (! exists($libserv{$course_server})) {
 4739:         return 'error:bad server name '.$course_server;
 4740:     }
 4741: # ------------------------------------------------------------- Make the course
 4742:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4743:                       $course_server);
 4744:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4745:     $uhome=&homeserver($uname,$udom,'true');
 4746:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4747: 	return 'error: no such course';
 4748:     }
 4749: # ----------------------------------------------------------------- Course made
 4750: # log existence
 4751:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4752:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4753:                   &escape($crstype),$uhome);
 4754:     &flushcourselogs();
 4755: # set toplevel url
 4756:     my $topurl=$url;
 4757:     unless ($nonstandard) {
 4758: # ------------------------------------------ For standard courses, make top url
 4759:         my $mapurl=&clutter($url);
 4760:         if ($mapurl eq '/res/') { $mapurl=''; }
 4761:         $env{'form.initmap'}=(<<ENDINITMAP);
 4762: <map>
 4763: <resource id="1" type="start"></resource>
 4764: <resource id="2" src="$mapurl"></resource>
 4765: <resource id="3" type="finish"></resource>
 4766: <link index="1" from="1" to="2"></link>
 4767: <link index="2" from="2" to="3"></link>
 4768: </map>
 4769: ENDINITMAP
 4770:         $topurl=&declutter(
 4771:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4772:                           );
 4773:     }
 4774: # ----------------------------------------------------------- Write preferences
 4775:     &writecoursepref($udom.'_'.$uname,
 4776:                      ('description' => $description,
 4777:                       'url'         => $topurl));
 4778:     return '/'.$udom.'/'.$uname;
 4779: }
 4780: 
 4781: # ---------------------------------------------------------- Assign Custom Role
 4782: 
 4783: sub assigncustomrole {
 4784:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4785:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4786:                        $end,$start,$deleteflag);
 4787: }
 4788: 
 4789: # ----------------------------------------------------------------- Revoke Role
 4790: 
 4791: sub revokerole {
 4792:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4793:     my $now=time;
 4794:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4795: }
 4796: 
 4797: # ---------------------------------------------------------- Revoke Custom Role
 4798: 
 4799: sub revokecustomrole {
 4800:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4801:     my $now=time;
 4802:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4803:            $deleteflag);
 4804: }
 4805: 
 4806: # ------------------------------------------------------------ Disk usage
 4807: sub diskusage {
 4808:     my ($udom,$uname,$directoryRoot)=@_;
 4809:     $directoryRoot =~ s/\/$//;
 4810:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4811:     return $listing;
 4812: }
 4813: 
 4814: sub is_locked {
 4815:     my ($file_name, $domain, $user) = @_;
 4816:     my @check;
 4817:     my $is_locked;
 4818:     push @check, $file_name;
 4819:     my %locked = &get('file_permissions',\@check,
 4820: 		      $env{'user.domain'},$env{'user.name'});
 4821:     my ($tmp)=keys(%locked);
 4822:     if ($tmp=~/^error:/) { undef(%locked); }
 4823:     
 4824:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4825:         $is_locked = 'false';
 4826:         foreach my $entry (@{$locked{$file_name}}) {
 4827:            if (ref($entry) eq 'ARRAY') { 
 4828:                $is_locked = 'true';
 4829:                last;
 4830:            }
 4831:        }
 4832:     } else {
 4833:         $is_locked = 'false';
 4834:     }
 4835: }
 4836: 
 4837: sub declutter_portfile {
 4838:     my ($file) = @_;
 4839:     &logthis("got $file");
 4840:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 4841:     &logthis("ret $file");
 4842:     return $file;
 4843: }
 4844: 
 4845: # ------------------------------------------------------------- Mark as Read Only
 4846: 
 4847: sub mark_as_readonly {
 4848:     my ($domain,$user,$files,$what) = @_;
 4849:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4850:     my ($tmp)=keys(%current_permissions);
 4851:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4852:     foreach my $file (@{$files}) {
 4853: 	$file = &declutter_portfile($file);
 4854:         push(@{$current_permissions{$file}},$what);
 4855:     }
 4856:     &put('file_permissions',\%current_permissions,$domain,$user);
 4857:     return;
 4858: }
 4859: 
 4860: # ------------------------------------------------------------Save Selected Files
 4861: 
 4862: sub save_selected_files {
 4863:     my ($user, $path, @files) = @_;
 4864:     my $filename = $user."savedfiles";
 4865:     my @other_files = &files_not_in_path($user, $path);
 4866:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4867:     foreach my $file (@files) {
 4868:         print (OUT $env{'form.currentpath'}.$file."\n");
 4869:     }
 4870:     foreach my $file (@other_files) {
 4871:         print (OUT $file."\n");
 4872:     }
 4873:     close (OUT);
 4874:     return 'ok';
 4875: }
 4876: 
 4877: sub clear_selected_files {
 4878:     my ($user) = @_;
 4879:     my $filename = $user."savedfiles";
 4880:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4881:     print (OUT undef);
 4882:     close (OUT);
 4883:     return ("ok");    
 4884: }
 4885: 
 4886: sub files_in_path {
 4887:     my ($user, $path) = @_;
 4888:     my $filename = $user."savedfiles";
 4889:     my %return_files;
 4890:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4891:     while (my $line_in = <IN>) {
 4892:         chomp ($line_in);
 4893:         my @paths_and_file = split (m!/!, $line_in);
 4894:         my $file_part = pop (@paths_and_file);
 4895:         my $path_part = join ('/', @paths_and_file);
 4896:         $path_part.='/';
 4897:         my $path_and_file = $path_part.$file_part;
 4898:         if ($path_part eq $path) {
 4899:             $return_files{$file_part}= 'selected';
 4900:         }
 4901:     }
 4902:     close (IN);
 4903:     return (\%return_files);
 4904: }
 4905: 
 4906: # called in portfolio select mode, to show files selected NOT in current directory
 4907: sub files_not_in_path {
 4908:     my ($user, $path) = @_;
 4909:     my $filename = $user."savedfiles";
 4910:     my @return_files;
 4911:     my $path_part;
 4912:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4913:     while (<IN>) {
 4914:         #ok, I know it's clunky, but I want it to work
 4915:         my @paths_and_file = split m!/!, $_;
 4916:         my $file_part = pop (@paths_and_file);
 4917:         chomp ($file_part);
 4918:         my $path_part = join ('/', @paths_and_file);
 4919:         $path_part .= '/';
 4920:         my $path_and_file = $path_part.$file_part;
 4921:         if ($path_part ne $path) {
 4922:             push (@return_files, ($path_and_file));
 4923:         }
 4924:     }
 4925:     close (OUT);
 4926:     return (@return_files);
 4927: }
 4928: 
 4929: #----------------------------------------------Get portfolio file permissions
 4930: 
 4931: sub get_portfile_permissions {
 4932:     my ($domain,$user) = @_;
 4933:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4934:     my ($tmp)=keys(%current_permissions);
 4935:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4936:     return \%current_permissions;
 4937: }
 4938: 
 4939: #---------------------------------------------Get portfolio file access controls
 4940: 
 4941: sub get_access_controls {
 4942:     my ($current_permissions,$group,$file) = @_;
 4943:     my %access;
 4944:     my $real_file = $file;
 4945:     $file =~ s/\.meta$//;
 4946:     if (defined($file)) {
 4947:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 4948:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 4949:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 4950:             }
 4951:         }
 4952:     } else {
 4953:         foreach my $key (keys(%{$current_permissions})) {
 4954:             if ($key =~ /\0accesscontrol$/) {
 4955:                 if (defined($group)) {
 4956:                     if ($key !~ m-^\Q$group\E/-) {
 4957:                         next;
 4958:                     }
 4959:                 }
 4960:                 my ($fullpath) = split(/\0/,$key);
 4961:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 4962:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 4963:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 4964:                     }
 4965:                 }
 4966:             }
 4967:         }
 4968:     }
 4969:     return %access;
 4970: }
 4971: 
 4972: sub modify_access_controls {
 4973:     my ($file_name,$changes,$domain,$user)=@_;
 4974:     my ($outcome,$deloutcome);
 4975:     my %store_permissions;
 4976:     my %new_values;
 4977:     my %new_control;
 4978:     my %translation;
 4979:     my @deletions = ();
 4980:     my $now = time;
 4981:     if (exists($$changes{'activate'})) {
 4982:         if (ref($$changes{'activate'}) eq 'HASH') {
 4983:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 4984:             my $numnew = scalar(@newitems);
 4985:             for (my $i=0; $i<$numnew; $i++) {
 4986:                 my $newkey = $newitems[$i];
 4987:                 my $newid = &Apache::loncommon::get_cgi_id();
 4988:                 $newkey =~ s/^(\d+)/$newid/;
 4989:                 $translation{$1} = $newid;
 4990:                 $new_values{$file_name."\0".$newkey} = 
 4991:                                           $$changes{'activate'}{$newitems[$i]};
 4992:                 $new_control{$newkey} = $now;
 4993:             }
 4994:         }
 4995:     }
 4996:     my %todelete;
 4997:     my %changed_items;
 4998:     foreach my $action ('delete','update') {
 4999:         if (exists($$changes{$action})) {
 5000:             if (ref($$changes{$action}) eq 'HASH') {
 5001:                 foreach my $key (keys(%{$$changes{$action}})) {
 5002:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5003:                     if ($action eq 'delete') { 
 5004:                         $todelete{$itemnum} = 1;
 5005:                     } else {
 5006:                         $changed_items{$itemnum} = $key;
 5007:                     }
 5008:                 }
 5009:             }
 5010:         }
 5011:     }
 5012:     # get lock on access controls for file.
 5013:     my $lockhash = {
 5014:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5015:                                                        ':'.$env{'user.domain'},
 5016:                    }; 
 5017:     my $tries = 0;
 5018:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5019:    
 5020:     while (($gotlock ne 'ok') && $tries <3) {
 5021:         $tries ++;
 5022:         sleep 1;
 5023:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5024:     }
 5025:     if ($gotlock eq 'ok') {
 5026:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5027:         my ($tmp)=keys(%curr_permissions);
 5028:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5029:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5030:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5031:             if (ref($curr_controls) eq 'HASH') {
 5032:                 foreach my $control_item (keys(%{$curr_controls})) {
 5033:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5034:                     if (defined($todelete{$itemnum})) {
 5035:                         push(@deletions,$file_name."\0".$control_item);
 5036:                     } else {
 5037:                         if (defined($changed_items{$itemnum})) {
 5038:                             $new_control{$changed_items{$itemnum}} = $now;
 5039:                             push(@deletions,$file_name."\0".$control_item);
 5040:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5041:                         } else {
 5042:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5043:                         }
 5044:                     }
 5045:                 }
 5046:             }
 5047:         }
 5048:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5049:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5050:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5051:         #  remove lock
 5052:         my @del_lock = ($file_name."\0".'locked_access_records');
 5053:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5054:     } else {
 5055:         $outcome = "error: could not obtain lockfile\n";  
 5056:     }
 5057:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5058: }
 5059: 
 5060: #------------------------------------------------------Get Marked as Read Only
 5061: 
 5062: sub get_marked_as_readonly {
 5063:     my ($domain,$user,$what,$group) = @_;
 5064:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5065:     my @readonly_files;
 5066:     my $cmp1=$what;
 5067:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5068:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5069:         if (defined($group)) {
 5070:             if ($file_name !~ m-^\Q$group\E/-) {
 5071:                 next;
 5072:             }
 5073:         }
 5074:         if (ref($value) eq "ARRAY"){
 5075:             foreach my $stored_what (@{$value}) {
 5076:                 my $cmp2=$stored_what;
 5077:                 if (ref($stored_what) eq 'ARRAY') {
 5078:                     $cmp2=join('',@{$stored_what});
 5079:                 }
 5080:                 if ($cmp1 eq $cmp2) {
 5081:                     push(@readonly_files, $file_name);
 5082:                     last;
 5083:                 } elsif (!defined($what)) {
 5084:                     push(@readonly_files, $file_name);
 5085:                     last;
 5086:                 }
 5087:             }
 5088:         }
 5089:     }
 5090:     return @readonly_files;
 5091: }
 5092: #-----------------------------------------------------------Get Marked as Read Only Hash
 5093: 
 5094: sub get_marked_as_readonly_hash {
 5095:     my ($current_permissions,$group,$what) = @_;
 5096:     my %readonly_files;
 5097:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5098:         if (defined($group)) {
 5099:             if ($file_name !~ m-^\Q$group\E/-) {
 5100:                 next;
 5101:             }
 5102:         }
 5103:         if (ref($value) eq "ARRAY"){
 5104:             foreach my $stored_what (@{$value}) {
 5105:                 if (ref($stored_what) eq 'ARRAY') {
 5106:                     foreach my $lock_descriptor(@{$stored_what}) {
 5107:                         if ($lock_descriptor eq 'graded') {
 5108:                             $readonly_files{$file_name} = 'graded';
 5109:                         } elsif ($lock_descriptor eq 'handback') {
 5110:                             $readonly_files{$file_name} = 'handback';
 5111:                         } else {
 5112:                             if (!exists($readonly_files{$file_name})) {
 5113:                                 $readonly_files{$file_name} = 'locked';
 5114:                             }
 5115:                         }
 5116:                     }
 5117:                 } 
 5118:             }
 5119:         } 
 5120:     }
 5121:     return %readonly_files;
 5122: }
 5123: # ------------------------------------------------------------ Unmark as Read Only
 5124: 
 5125: sub unmark_as_readonly {
 5126:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5127:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5128:     my ($domain,$user,$what,$file_name,$group) = @_;
 5129:     $file_name = &declutter_portfile($file_name);
 5130:     my $symb_crs = $what;
 5131:     if (ref($what)) { $symb_crs=join('',@$what); }
 5132:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5133:     my ($tmp)=keys(%current_permissions);
 5134:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5135:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5136:     foreach my $file (@readonly_files) {
 5137: 	my $clean_file = &declutter_portfile($file);
 5138: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5139: 	my $current_locks = $current_permissions{$file};
 5140:         my @new_locks;
 5141:         my @del_keys;
 5142:         if (ref($current_locks) eq "ARRAY"){
 5143:             foreach my $locker (@{$current_locks}) {
 5144:                 my $compare=$locker;
 5145:                 if (ref($locker) eq 'ARRAY') {
 5146:                     $compare=join('',@{$locker});
 5147:                     if ($compare ne $symb_crs) {
 5148:                         push(@new_locks, $locker);
 5149:                     }
 5150:                 }
 5151:             }
 5152:             if (scalar(@new_locks) > 0) {
 5153:                 $current_permissions{$file} = \@new_locks;
 5154:             } else {
 5155:                 push(@del_keys, $file);
 5156:                 &del('file_permissions',\@del_keys, $domain, $user);
 5157:                 delete($current_permissions{$file});
 5158:             }
 5159:         }
 5160:     }
 5161:     &put('file_permissions',\%current_permissions,$domain,$user);
 5162:     return;
 5163: }
 5164: 
 5165: # ------------------------------------------------------------ Directory lister
 5166: 
 5167: sub dirlist {
 5168:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5169: 
 5170:     $uri=~s/^\///;
 5171:     $uri=~s/\/$//;
 5172:     my ($udom, $uname);
 5173:     (undef,$udom,$uname)=split(/\//,$uri);
 5174:     if(defined($userdomain)) {
 5175:         $udom = $userdomain;
 5176:     }
 5177:     if(defined($username)) {
 5178:         $uname = $username;
 5179:     }
 5180: 
 5181:     my $dirRoot = $perlvar{'lonDocRoot'};
 5182:     if(defined($alternateDirectoryRoot)) {
 5183:         $dirRoot = $alternateDirectoryRoot;
 5184:         $dirRoot =~ s/\/$//;
 5185:     }
 5186: 
 5187:     if($udom) {
 5188:         if($uname) {
 5189:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 5190:                               homeserver($uname,$udom));
 5191:             my @listing_results;
 5192:             if ($listing eq 'unknown_cmd') {
 5193:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 5194:                                homeserver($uname,$udom));
 5195:                 @listing_results = split(/:/,$listing);
 5196:             } else {
 5197:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5198:             }
 5199:             return @listing_results;
 5200:         } elsif(!defined($alternateDirectoryRoot)) {
 5201:             my $tryserver;
 5202:             my %allusers=();
 5203:             foreach $tryserver (keys %libserv) {
 5204:                 if($hostdom{$tryserver} eq $udom) {
 5205:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5206:                                       $udom, $tryserver);
 5207:                     my @listing_results;
 5208:                     if ($listing eq 'unknown_cmd') {
 5209:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5210:                                        $udom, $tryserver);
 5211:                         @listing_results = split(/:/,$listing);
 5212:                     } else {
 5213:                         @listing_results =
 5214:                             map { &unescape($_); } split(/:/,$listing);
 5215:                     }
 5216:                     if ($listing_results[0] ne 'no_such_dir' && 
 5217:                         $listing_results[0] ne 'empty'       &&
 5218:                         $listing_results[0] ne 'con_lost') {
 5219:                         foreach (@listing_results) {
 5220:                             my ($entry,@stat)=split(/&/,$_);
 5221:                             $allusers{$entry}=1;
 5222:                         }
 5223:                     }
 5224:                 }
 5225:             }
 5226:             my $alluserstr='';
 5227:             foreach (sort keys %allusers) {
 5228:                 $alluserstr.=$_.'&user:';
 5229:             }
 5230:             $alluserstr=~s/:$//;
 5231:             return split(/:/,$alluserstr);
 5232:         } else {
 5233:             my @emptyResults = ();
 5234:             push(@emptyResults, 'missing user name');
 5235:             return split(':',@emptyResults);
 5236:         }
 5237:     } elsif(!defined($alternateDirectoryRoot)) {
 5238:         my $tryserver;
 5239:         my %alldom=();
 5240:         foreach $tryserver (keys %libserv) {
 5241:             $alldom{$hostdom{$tryserver}}=1;
 5242:         }
 5243:         my $alldomstr='';
 5244:         foreach (sort keys %alldom) {
 5245:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 5246:         }
 5247:         $alldomstr=~s/:$//;
 5248:         return split(/:/,$alldomstr);       
 5249:     } else {
 5250:         my @emptyResults = ();
 5251:         push(@emptyResults, 'missing domain');
 5252:         return split(':',@emptyResults);
 5253:     }
 5254: }
 5255: 
 5256: # --------------------------------------------- GetFileTimestamp
 5257: # This function utilizes dirlist and returns the date stamp for
 5258: # when it was last modified.  It will also return an error of -1
 5259: # if an error occurs
 5260: 
 5261: ##
 5262: ## FIXME: This subroutine assumes its caller knows something about the
 5263: ## directory structure of the home server for the student ($root).
 5264: ## Not a good assumption to make.  Since this is for looking up files
 5265: ## in user directories, the full path should be constructed by lond, not
 5266: ## whatever machine we request data from.
 5267: ##
 5268: sub GetFileTimestamp {
 5269:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5270:     $studentDomain=~s/\W//g;
 5271:     $studentName=~s/\W//g;
 5272:     my $subdir=$studentName.'__';
 5273:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5274:     my $proname="$studentDomain/$subdir/$studentName";
 5275:     $proname .= '/'.$filename;
 5276:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5277:                                               $studentName, $root);
 5278:     my @stats = split('&', $fileStat);
 5279:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5280:         # @stats contains first the filename, then the stat output
 5281:         return $stats[10]; # so this is 10 instead of 9.
 5282:     } else {
 5283:         return -1;
 5284:     }
 5285: }
 5286: 
 5287: sub stat_file {
 5288:     my ($uri) = @_;
 5289:     $uri = &clutter($uri);
 5290: 
 5291:     # we want just the url part without the unneeded accessor url bits
 5292:     if ($uri =~ m-^/adm/-) {
 5293: 	$uri=~s-^/adm/wrapper/-/-;
 5294: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 5295:     }
 5296:     my ($udom,$uname,$file,$dir);
 5297:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5298: 	($udom,$uname,$file) =
 5299: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5300: 	$file = 'userfiles/'.$file;
 5301: 	$dir = &propath($udom,$uname);
 5302:     }
 5303:     if ($uri =~ m-^/res/-) {
 5304: 	($udom,$uname) = 
 5305: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5306: 	$file = $uri;
 5307:     }
 5308: 
 5309:     if (!$udom || !$uname || !$file) {
 5310: 	# unable to handle the uri
 5311: 	return ();
 5312:     }
 5313: 
 5314:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5315:     my @stats = split('&', $result);
 5316:     
 5317:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5318: 	shift(@stats); #filename is first
 5319: 	return @stats;
 5320:     }
 5321:     return ();
 5322: }
 5323: 
 5324: # -------------------------------------------------------- Value of a Condition
 5325: 
 5326: # gets the value of a specific preevaluated condition
 5327: #    stored in the string  $env{user.state.<cid>}
 5328: # or looks up a condition reference in the bighash and if if hasn't
 5329: # already been evaluated recurses into docondval to get the value of
 5330: # the condition, then memoizing it to 
 5331: #   $env{user.state.<cid>.<condition>}
 5332: sub directcondval {
 5333:     my $number=shift;
 5334:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5335: 	&Apache::lonuserstate::evalstate();
 5336:     }
 5337:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5338: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5339:     } elsif ($number =~ /^_/) {
 5340: 	my $sub_condition;
 5341: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5342: 		&GDBM_READER(),0640)) {
 5343: 	    $sub_condition=$bighash{'conditions'.$number};
 5344: 	    untie(%bighash);
 5345: 	}
 5346: 	my $value = &docondval($sub_condition);
 5347: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5348: 	return $value;
 5349:     }
 5350:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5351:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5352:     } else {
 5353:        return 2;
 5354:     }
 5355: }
 5356: 
 5357: # get the collection of conditions for this resource
 5358: sub condval {
 5359:     my $condidx=shift;
 5360:     my $allpathcond='';
 5361:     foreach my $cond (split(/\|/,$condidx)) {
 5362: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5363: 	    $allpathcond.=
 5364: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5365: 	}
 5366:     }
 5367:     $allpathcond=~s/\|$//;
 5368:     return &docondval($allpathcond);
 5369: }
 5370: 
 5371: #evaluates an expression of conditions
 5372: sub docondval {
 5373:     my ($allpathcond) = @_;
 5374:     my $result=0;
 5375:     if ($env{'request.course.id'}
 5376: 	&& defined($allpathcond)) {
 5377: 	my $operand='|';
 5378: 	my @stack;
 5379: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5380: 	    if ($chunk eq '(') {
 5381: 		push @stack,($operand,$result);
 5382: 	    } elsif ($chunk eq ')') {
 5383: 		my $before=pop @stack;
 5384: 		if (pop @stack eq '&') {
 5385: 		    $result=$result>$before?$before:$result;
 5386: 		} else {
 5387: 		    $result=$result>$before?$result:$before;
 5388: 		}
 5389: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5390: 		$operand=$chunk;
 5391: 	    } else {
 5392: 		my $new=directcondval($chunk);
 5393: 		if ($operand eq '&') {
 5394: 		    $result=$result>$new?$new:$result;
 5395: 		} else {
 5396: 		    $result=$result>$new?$result:$new;
 5397: 		}
 5398: 	    }
 5399: 	}
 5400:     }
 5401:     return $result;
 5402: }
 5403: 
 5404: # ---------------------------------------------------- Devalidate courseresdata
 5405: 
 5406: sub devalidatecourseresdata {
 5407:     my ($coursenum,$coursedomain)=@_;
 5408:     my $hashid=$coursenum.':'.$coursedomain;
 5409:     &devalidate_cache_new('courseres',$hashid);
 5410: }
 5411: 
 5412: 
 5413: # --------------------------------------------------- Course Resourcedata Query
 5414: 
 5415: sub get_courseresdata {
 5416:     my ($coursenum,$coursedomain)=@_;
 5417:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5418:     my $hashid=$coursenum.':'.$coursedomain;
 5419:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5420:     my %dumpreply;
 5421:     unless (defined($cached)) {
 5422: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5423: 	$result=\%dumpreply;
 5424: 	my ($tmp) = keys(%dumpreply);
 5425: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5426: 	    &do_cache_new('courseres',$hashid,$result,600);
 5427: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5428: 	    return $tmp;
 5429: 	} elsif ($tmp =~ /^(error)/) {
 5430: 	    $result=undef;
 5431: 	    &do_cache_new('courseres',$hashid,$result,600);
 5432: 	}
 5433:     }
 5434:     return $result;
 5435: }
 5436: 
 5437: sub devalidateuserresdata {
 5438:     my ($uname,$udom)=@_;
 5439:     my $hashid="$udom:$uname";
 5440:     &devalidate_cache_new('userres',$hashid);
 5441: }
 5442: 
 5443: sub get_userresdata {
 5444:     my ($uname,$udom)=@_;
 5445:     #most student don\'t have any data set, check if there is some data
 5446:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5447: 
 5448:     my $hashid="$udom:$uname";
 5449:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5450:     if (!defined($cached)) {
 5451: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5452: 	$result=\%resourcedata;
 5453: 	&do_cache_new('userres',$hashid,$result,600);
 5454:     }
 5455:     my ($tmp)=keys(%$result);
 5456:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5457: 	return $result;
 5458:     }
 5459:     #error 2 occurs when the .db doesn't exist
 5460:     if ($tmp!~/error: 2 /) {
 5461: 	&logthis("<font color=\"blue\">WARNING:".
 5462: 		 " Trying to get resource data for ".
 5463: 		 $uname." at ".$udom.": ".
 5464: 		 $tmp."</font>");
 5465:     } elsif ($tmp=~/error: 2 /) {
 5466: 	#&EXT_cache_set($udom,$uname);
 5467: 	&do_cache_new('userres',$hashid,undef,600);
 5468: 	undef($tmp); # not really an error so don't send it back
 5469:     }
 5470:     return $tmp;
 5471: }
 5472: 
 5473: sub resdata {
 5474:     my ($name,$domain,$type,@which)=@_;
 5475:     my $result;
 5476:     if ($type eq 'course') {
 5477: 	$result=&get_courseresdata($name,$domain);
 5478:     } elsif ($type eq 'user') {
 5479: 	$result=&get_userresdata($name,$domain);
 5480:     }
 5481:     if (!ref($result)) { return $result; }    
 5482:     foreach my $item (@which) {
 5483: 	if (defined($result->{$item})) {
 5484: 	    return $result->{$item};
 5485: 	}
 5486:     }
 5487:     return undef;
 5488: }
 5489: 
 5490: #
 5491: # EXT resource caching routines
 5492: #
 5493: 
 5494: sub clear_EXT_cache_status {
 5495:     &delenv('cache.EXT.');
 5496: }
 5497: 
 5498: sub EXT_cache_status {
 5499:     my ($target_domain,$target_user) = @_;
 5500:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5501:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5502:         # We know already the user has no data
 5503:         return 1;
 5504:     } else {
 5505:         return 0;
 5506:     }
 5507: }
 5508: 
 5509: sub EXT_cache_set {
 5510:     my ($target_domain,$target_user) = @_;
 5511:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5512:     #&appenv($cachename => time);
 5513: }
 5514: 
 5515: # --------------------------------------------------------- Value of a Variable
 5516: sub EXT {
 5517: 
 5518:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5519:     unless ($varname) { return ''; }
 5520:     #get real user name/domain, courseid and symb
 5521:     my $courseid;
 5522:     my $publicuser;
 5523:     if ($symbparm) {
 5524: 	$symbparm=&get_symb_from_alias($symbparm);
 5525:     }
 5526:     if (!($uname && $udom)) {
 5527:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5528: 	  &Apache::lonxml::whichuser($symbparm);
 5529:       if (!$symbparm) {	$symbparm=$cursymb; }
 5530:     } else {
 5531: 	$courseid=$env{'request.course.id'};
 5532:     }
 5533:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5534:     my $rest;
 5535:     if (defined($therest[0])) {
 5536:        $rest=join('.',@therest);
 5537:     } else {
 5538:        $rest='';
 5539:     }
 5540: 
 5541:     my $qualifierrest=$qualifier;
 5542:     if ($rest) { $qualifierrest.='.'.$rest; }
 5543:     my $spacequalifierrest=$space;
 5544:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5545:     if ($realm eq 'user') {
 5546: # --------------------------------------------------------------- user.resource
 5547: 	if ($space eq 'resource') {
 5548: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5549: 		  || defined($Apache::lonhomework::parsing_a_task))
 5550: 		 &&
 5551: 		 ($symbparm eq &symbread()) ) {	
 5552: 		# if we are in the middle of processing the resource the
 5553: 		# get the value we are planning on committing
 5554:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5555:                     return $Apache::lonhomework::results{$qualifierrest};
 5556:                 } else {
 5557:                     return $Apache::lonhomework::history{$qualifierrest};
 5558:                 }
 5559: 	    } else {
 5560: 		my %restored;
 5561: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5562: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5563: 		} else {
 5564: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5565: 		}
 5566: 		return $restored{$qualifierrest};
 5567: 	    }
 5568: # ----------------------------------------------------------------- user.access
 5569:         } elsif ($space eq 'access') {
 5570: 	    # FIXME - not supporting calls for a specific user
 5571:             return &allowed($qualifier,$rest);
 5572: # ------------------------------------------ user.preferences, user.environment
 5573:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5574: 	    if (($uname eq $env{'user.name'}) &&
 5575: 		($udom eq $env{'user.domain'})) {
 5576: 		return $env{join('.',('environment',$qualifierrest))};
 5577: 	    } else {
 5578: 		my %returnhash;
 5579: 		if (!$publicuser) {
 5580: 		    %returnhash=&userenvironment($udom,$uname,
 5581: 						 $qualifierrest);
 5582: 		}
 5583: 		return $returnhash{$qualifierrest};
 5584: 	    }
 5585: # ----------------------------------------------------------------- user.course
 5586:         } elsif ($space eq 'course') {
 5587: 	    # FIXME - not supporting calls for a specific user
 5588:             return $env{join('.',('request.course',$qualifier))};
 5589: # ------------------------------------------------------------------- user.role
 5590:         } elsif ($space eq 'role') {
 5591: 	    # FIXME - not supporting calls for a specific user
 5592:             my ($role,$where)=split(/\./,$env{'request.role'});
 5593:             if ($qualifier eq 'value') {
 5594: 		return $role;
 5595:             } elsif ($qualifier eq 'extent') {
 5596:                 return $where;
 5597:             }
 5598: # ----------------------------------------------------------------- user.domain
 5599:         } elsif ($space eq 'domain') {
 5600:             return $udom;
 5601: # ------------------------------------------------------------------- user.name
 5602:         } elsif ($space eq 'name') {
 5603:             return $uname;
 5604: # ---------------------------------------------------- Any other user namespace
 5605:         } else {
 5606: 	    my %reply;
 5607: 	    if (!$publicuser) {
 5608: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5609: 	    }
 5610: 	    return $reply{$qualifierrest};
 5611:         }
 5612:     } elsif ($realm eq 'query') {
 5613: # ---------------------------------------------- pull stuff out of query string
 5614:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5615: 						[$spacequalifierrest]);
 5616: 	return $env{'form.'.$spacequalifierrest}; 
 5617:    } elsif ($realm eq 'request') {
 5618: # ------------------------------------------------------------- request.browser
 5619:         if ($space eq 'browser') {
 5620: 	    if ($qualifier eq 'textremote') {
 5621: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5622: 		    return 1;
 5623: 		} else {
 5624: 		    return 0;
 5625: 		}
 5626: 	    } else {
 5627: 		return $env{'browser.'.$qualifier};
 5628: 	    }
 5629: # ------------------------------------------------------------ request.filename
 5630:         } else {
 5631:             return $env{'request.'.$spacequalifierrest};
 5632:         }
 5633:     } elsif ($realm eq 'course') {
 5634: # ---------------------------------------------------------- course.description
 5635:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5636:     } elsif ($realm eq 'resource') {
 5637: 
 5638: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5639: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5640: 	}
 5641: 
 5642: 	if ($space eq 'title') {
 5643: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5644: 	    return &gettitle($symbparm);
 5645: 	}
 5646: 	
 5647: 	if ($space eq 'map') {
 5648: 	    my ($map) = &decode_symb($symbparm);
 5649: 	    return &symbread($map);
 5650: 	}
 5651: 
 5652: 	my ($section, $group, @groups);
 5653: 	my ($courselevelm,$courselevel);
 5654: 	if ($symbparm && defined($courseid) && 
 5655: 	    $courseid eq $env{'request.course.id'}) {
 5656: 
 5657: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5658: 
 5659: # ----------------------------------------------------- Cascading lookup scheme
 5660: 	    my $symbp=$symbparm;
 5661: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5662: 
 5663: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5664: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5665: 
 5666: 	    if (($env{'user.name'} eq $uname) &&
 5667: 		($env{'user.domain'} eq $udom)) {
 5668: 		$section=$env{'request.course.sec'};
 5669:                 @groups = split(/:/,$env{'request.course.groups'});  
 5670:                 @groups=&sort_course_groups($courseid,@groups); 
 5671: 	    } else {
 5672: 		if (! defined($usection)) {
 5673: 		    $section=&getsection($udom,$uname,$courseid);
 5674: 		} else {
 5675: 		    $section = $usection;
 5676: 		}
 5677:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5678: 	    }
 5679: 
 5680: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5681: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5682: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5683: 
 5684: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5685: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5686: 	    $courselevelm=$courseid.'.'.$mapparm;
 5687: 
 5688: # ----------------------------------------------------------- first, check user
 5689: 
 5690: 	    my $userreply=&resdata($uname,$udom,'user',
 5691: 				       ($courselevelr,$courselevelm,
 5692: 					$courselevel));
 5693: 	    if (defined($userreply)) { return $userreply; }
 5694: 
 5695: # ------------------------------------------------ second, check some of course
 5696:             my $coursereply;
 5697:             if (@groups > 0) {
 5698:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5699:                                        $mapparm,$spacequalifierrest);
 5700:                 if (defined($coursereply)) { return $coursereply; }
 5701:             }
 5702: 
 5703: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5704: 				     $env{'course.'.$courseid.'.domain'},
 5705: 				     'course',
 5706: 				     ($seclevelr,$seclevelm,$seclevel,
 5707: 				      $courselevelr));
 5708: 	    if (defined($coursereply)) { return $coursereply; }
 5709: 
 5710: # ------------------------------------------------------ third, check map parms
 5711: 	    my %parmhash=();
 5712: 	    my $thisparm='';
 5713: 	    if (tie(%parmhash,'GDBM_File',
 5714: 		    $env{'request.course.fn'}.'_parms.db',
 5715: 		    &GDBM_READER(),0640)) {
 5716: 		$thisparm=$parmhash{$symbparm};
 5717: 		untie(%parmhash);
 5718: 	    }
 5719: 	    if ($thisparm) { return $thisparm; }
 5720: 	}
 5721: # ------------------------------------------ fourth, look in resource metadata
 5722: 
 5723: 	$spacequalifierrest=~s/\./\_/;
 5724: 	my $filename;
 5725: 	if (!$symbparm) { $symbparm=&symbread(); }
 5726: 	if ($symbparm) {
 5727: 	    $filename=(&decode_symb($symbparm))[2];
 5728: 	} else {
 5729: 	    $filename=$env{'request.filename'};
 5730: 	}
 5731: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5732: 	if (defined($metadata)) { return $metadata; }
 5733: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5734: 	if (defined($metadata)) { return $metadata; }
 5735: 
 5736: # ---------------------------------------------- fourth, look in rest pf course
 5737: 	if ($symbparm && defined($courseid) && 
 5738: 	    $courseid eq $env{'request.course.id'}) {
 5739: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5740: 				     $env{'course.'.$courseid.'.domain'},
 5741: 				     'course',
 5742: 				     ($courselevelm,$courselevel));
 5743: 	    if (defined($coursereply)) { return $coursereply; }
 5744: 	}
 5745: # ------------------------------------------------------------------ Cascade up
 5746: 	unless ($space eq '0') {
 5747: 	    my @parts=split(/_/,$space);
 5748: 	    my $id=pop(@parts);
 5749: 	    my $part=join('_',@parts);
 5750: 	    if ($part eq '') { $part='0'; }
 5751: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5752: 				 $symbparm,$udom,$uname,$section,1);
 5753: 	    if (defined($partgeneral)) { return $partgeneral; }
 5754: 	}
 5755: 	if ($recurse) { return undef; }
 5756: 	my $pack_def=&packages_tab_default($filename,$varname);
 5757: 	if (defined($pack_def)) { return $pack_def; }
 5758: 
 5759: # ---------------------------------------------------- Any other user namespace
 5760:     } elsif ($realm eq 'environment') {
 5761: # ----------------------------------------------------------------- environment
 5762: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5763: 	    return $env{'environment.'.$spacequalifierrest};
 5764: 	} else {
 5765: 	    if ($uname eq 'anonymous' && $udom eq '') {
 5766: 		return '';
 5767: 	    }
 5768: 	    my %returnhash=&userenvironment($udom,$uname,
 5769: 					    $spacequalifierrest);
 5770: 	    return $returnhash{$spacequalifierrest};
 5771: 	}
 5772:     } elsif ($realm eq 'system') {
 5773: # ----------------------------------------------------------------- system.time
 5774: 	if ($space eq 'time') {
 5775: 	    return time;
 5776:         }
 5777:     } elsif ($realm eq 'server') {
 5778: # ----------------------------------------------------------------- system.time
 5779: 	if ($space eq 'name') {
 5780: 	    return $ENV{'SERVER_NAME'};
 5781:         }
 5782:     }
 5783:     return '';
 5784: }
 5785: 
 5786: sub check_group_parms {
 5787:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5788:     my @groupitems = ();
 5789:     my $resultitem;
 5790:     my @levels = ($symbparm,$mapparm,$what);
 5791:     foreach my $group (@{$groups}) {
 5792:         foreach my $level (@levels) {
 5793:              my $item = $courseid.'.['.$group.'].'.$level;
 5794:              push(@groupitems,$item);
 5795:         }
 5796:     }
 5797:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5798:                             $env{'course.'.$courseid.'.domain'},
 5799:                                      'course',@groupitems);
 5800:     return $coursereply;
 5801: }
 5802: 
 5803: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5804:     my ($courseid,@groups) = @_;
 5805:     @groups = sort(@groups);
 5806:     return @groups;
 5807: }
 5808: 
 5809: sub packages_tab_default {
 5810:     my ($uri,$varname)=@_;
 5811:     my (undef,$part,$name)=split(/\./,$varname);
 5812: 
 5813:     my (@extension,@specifics,$do_default);
 5814:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5815: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5816: 	if ($pack_type eq 'default') {
 5817: 	    $do_default=1;
 5818: 	} elsif ($pack_type eq 'extension') {
 5819: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5820: 	} else {
 5821: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5822: 	}
 5823:     }
 5824:     # first look for a package that matches the requested part id
 5825:     foreach my $package (@specifics) {
 5826: 	my (undef,$pack_type,$pack_part)=@{$package};
 5827: 	next if ($pack_part ne $part);
 5828: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5829: 	    return $packagetab{"$pack_type&$name&default"};
 5830: 	}
 5831:     }
 5832:     # look for any possible matching non extension_ package
 5833:     foreach my $package (@specifics) {
 5834: 	my (undef,$pack_type,$pack_part)=@{$package};
 5835: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5836: 	    return $packagetab{"$pack_type&$name&default"};
 5837: 	}
 5838: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5839: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5840: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5841: 	}
 5842:     }
 5843:     # look for any posible extension_ match
 5844:     foreach my $package (@extension) {
 5845: 	my ($package,$pack_type)=@{$package};
 5846: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5847: 	    return $packagetab{"$pack_type&$name&default"};
 5848: 	}
 5849: 	if (defined($packagetab{$package."&$name&default"})) {
 5850: 	    return $packagetab{$package."&$name&default"};
 5851: 	}
 5852:     }
 5853:     # look for a global default setting
 5854:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5855: 	return $packagetab{"default&$name&default"};
 5856:     }
 5857:     return undef;
 5858: }
 5859: 
 5860: sub add_prefix_and_part {
 5861:     my ($prefix,$part)=@_;
 5862:     my $keyroot;
 5863:     if (defined($prefix) && $prefix !~ /^__/) {
 5864: 	# prefix that has a part already
 5865: 	$keyroot=$prefix;
 5866:     } elsif (defined($prefix)) {
 5867: 	# prefix that is missing a part
 5868: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5869:     } else {
 5870: 	# no prefix at all
 5871: 	if (defined($part)) { $keyroot='_'.$part; }
 5872:     }
 5873:     return $keyroot;
 5874: }
 5875: 
 5876: # ---------------------------------------------------------------- Get metadata
 5877: 
 5878: my %metaentry;
 5879: sub metadata {
 5880:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5881:     $uri=&declutter($uri);
 5882:     # if it is a non metadata possible uri return quickly
 5883:     if (($uri eq '') || 
 5884: 	(($uri =~ m|^/*adm/|) && 
 5885: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5886:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5887: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5888: 	return undef;
 5889:     }
 5890:     my $filename=$uri;
 5891:     $uri=~s/\.meta$//;
 5892: #
 5893: # Is the metadata already cached?
 5894: # Look at timestamp of caching
 5895: # Everything is cached by the main uri, libraries are never directly cached
 5896: #
 5897:     if (!defined($liburi)) {
 5898: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5899: 	if (defined($cached)) { return $result->{':'.$what}; }
 5900:     }
 5901:     {
 5902: #
 5903: # Is this a recursive call for a library?
 5904: #
 5905: #	if (! exists($metacache{$uri})) {
 5906: #	    $metacache{$uri}={};
 5907: #	}
 5908:         if ($liburi) {
 5909: 	    $liburi=&declutter($liburi);
 5910:             $filename=$liburi;
 5911:         } else {
 5912: 	    &devalidate_cache_new('meta',$uri);
 5913: 	    undef(%metaentry);
 5914: 	}
 5915:         my %metathesekeys=();
 5916:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5917: 	my $metastring;
 5918: 	if ($uri !~ m -^(editupload)/-) {
 5919: 	    my $file=&filelocation('',&clutter($filename));
 5920: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5921: 	    $metastring=&getfile($file);
 5922: 	}
 5923:         my $parser=HTML::LCParser->new(\$metastring);
 5924:         my $token;
 5925:         undef %metathesekeys;
 5926:         while ($token=$parser->get_token) {
 5927: 	    if ($token->[0] eq 'S') {
 5928: 		if (defined($token->[2]->{'package'})) {
 5929: #
 5930: # This is a package - get package info
 5931: #
 5932: 		    my $package=$token->[2]->{'package'};
 5933: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5934: 		    if (defined($token->[2]->{'id'})) { 
 5935: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5936: 		    }
 5937: 		    if ($metaentry{':packages'}) {
 5938: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5939: 		    } else {
 5940: 			$metaentry{':packages'}=$package.$keyroot;
 5941: 		    }
 5942: 		    foreach my $pack_entry (keys(%packagetab)) {
 5943: 			my $part=$keyroot;
 5944: 			$part=~s/^\_//;
 5945: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 5946: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 5947: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 5948: 			    # ignore package.tab specified default values
 5949:                             # here &package_tab_default() will fetch those
 5950: 			    if ($subp eq 'default') { next; }
 5951: 			    my $value=$packagetab{$pack_entry};
 5952: 			    my $unikey;
 5953: 			    if ($pack =~ /_0$/) {
 5954: 				$unikey='parameter_0_'.$name;
 5955: 				$part=0;
 5956: 			    } else {
 5957: 				$unikey='parameter'.$keyroot.'_'.$name;
 5958: 			    }
 5959: 			    if ($subp eq 'display') {
 5960: 				$value.=' [Part: '.$part.']';
 5961: 			    }
 5962: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5963: 			    $metathesekeys{$unikey}=1;
 5964: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5965: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5966: 			    }
 5967: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5968: 				$metaentry{':'.$unikey}=
 5969: 				    $metaentry{':'.$unikey.'.default'};
 5970: 			    }
 5971: 			}
 5972: 		    }
 5973: 		} else {
 5974: #
 5975: # This is not a package - some other kind of start tag
 5976: #
 5977: 		    my $entry=$token->[1];
 5978: 		    my $unikey;
 5979: 		    if ($entry eq 'import') {
 5980: 			$unikey='';
 5981: 		    } else {
 5982: 			$unikey=$entry;
 5983: 		    }
 5984: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5985: 
 5986: 		    if (defined($token->[2]->{'id'})) { 
 5987: 			$unikey.='_'.$token->[2]->{'id'}; 
 5988: 		    }
 5989: 
 5990: 		    if ($entry eq 'import') {
 5991: #
 5992: # Importing a library here
 5993: #
 5994: 			if ($depthcount<20) {
 5995: 			    my $location=$parser->get_text('/import');
 5996: 			    my $dir=$filename;
 5997: 			    $dir=~s|[^/]*$||;
 5998: 			    $location=&filelocation($dir,$location);
 5999: 			    my $metadata = 
 6000: 				&metadata($uri,'keys', $location,$unikey,
 6001: 					  $depthcount+1);
 6002: 			    foreach my $meta (split(',',$metadata)) {
 6003: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6004: 				$metathesekeys{$meta}=1;
 6005: 			    }
 6006: 			}
 6007: 		    } else { 
 6008: 			
 6009: 			if (defined($token->[2]->{'name'})) { 
 6010: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6011: 			}
 6012: 			$metathesekeys{$unikey}=1;
 6013: 			foreach my $param (@{$token->[3]}) {
 6014: 			    $metaentry{':'.$unikey.'.'.$param} =
 6015: 				$token->[2]->{$param};
 6016: 			}
 6017: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6018: 			my $default=$metaentry{':'.$unikey.'.default'};
 6019: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6020: 		 # only ws inside the tag, and not in default, so use default
 6021: 		 # as value
 6022: 			    $metaentry{':'.$unikey}=$default;
 6023: 			} else {
 6024: 		  # either something interesting inside the tag or default
 6025:                   # uninteresting
 6026: 			    $metaentry{':'.$unikey}=$internaltext;
 6027: 			}
 6028: # end of not-a-package not-a-library import
 6029: 		    }
 6030: # end of not-a-package start tag
 6031: 		}
 6032: # the next is the end of "start tag"
 6033: 	    }
 6034: 	}
 6035: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6036: 	foreach my $key (keys(%packagetab)) {
 6037: 	    #no specific packages #how's our extension
 6038: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6039: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6040: 					 \%metathesekeys);
 6041: 	}
 6042: 	if (!exists($metaentry{':packages'})) {
 6043: 	    foreach my $key (keys(%packagetab)) {
 6044: 		#no specific packages well let's get default then
 6045: 		if ($key!~/^default&/) { next; }
 6046: 		&metadata_create_package_def($uri,$key,'default',
 6047: 					     \%metathesekeys);
 6048: 	    }
 6049: 	}
 6050: # are there custom rights to evaluate
 6051: 	if ($metaentry{':copyright'} eq 'custom') {
 6052: 
 6053:     #
 6054:     # Importing a rights file here
 6055:     #
 6056: 	    unless ($depthcount) {
 6057: 		my $location=$metaentry{':customdistributionfile'};
 6058: 		my $dir=$filename;
 6059: 		$dir=~s|[^/]*$||;
 6060: 		$location=&filelocation($dir,$location);
 6061: 		my $rights_metadata =
 6062: 		    &metadata($uri,'keys',$location,'_rights',
 6063: 			      $depthcount+1);
 6064: 		foreach my $rights (split(',',$rights_metadata)) {
 6065: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6066: 		    $metathesekeys{$rights}=1;
 6067: 		}
 6068: 	    }
 6069: 	}
 6070: 	# uniqifiy package listing
 6071: 	my %seen;
 6072: 	my @uniq_packages =
 6073: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6074: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6075: 
 6076: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6077: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6078: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6079: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6080: # this is the end of "was not already recently cached
 6081:     }
 6082:     return $metaentry{':'.$what};
 6083: }
 6084: 
 6085: sub metadata_create_package_def {
 6086:     my ($uri,$key,$package,$metathesekeys)=@_;
 6087:     my ($pack,$name,$subp)=split(/\&/,$key);
 6088:     if ($subp eq 'default') { next; }
 6089:     
 6090:     if (defined($metaentry{':packages'})) {
 6091: 	$metaentry{':packages'}.=','.$package;
 6092:     } else {
 6093: 	$metaentry{':packages'}=$package;
 6094:     }
 6095:     my $value=$packagetab{$key};
 6096:     my $unikey;
 6097:     $unikey='parameter_0_'.$name;
 6098:     $metaentry{':'.$unikey.'.part'}=0;
 6099:     $$metathesekeys{$unikey}=1;
 6100:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6101: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6102:     }
 6103:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6104: 	$metaentry{':'.$unikey}=
 6105: 	    $metaentry{':'.$unikey.'.default'};
 6106:     }
 6107: }
 6108: 
 6109: sub metadata_generate_part0 {
 6110:     my ($metadata,$metacache,$uri) = @_;
 6111:     my %allnames;
 6112:     foreach my $metakey (keys(%$metadata)) {
 6113: 	if ($metakey=~/^parameter\_(.*)/) {
 6114: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6115: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6116: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6117: 	    $allnames{$name}=$part;
 6118: 	  }
 6119: 	}
 6120:     }
 6121:     foreach my $name (keys(%allnames)) {
 6122:       $$metadata{"parameter_0_$name"}=1;
 6123:       my $key=":parameter_0_$name";
 6124:       $$metacache{"$key.part"}='0';
 6125:       $$metacache{"$key.name"}=$name;
 6126:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6127: 					   $allnames{$name}.'_'.$name.
 6128: 					   '.type'};
 6129:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6130: 			     '.display'};
 6131:       my $expr='[Part: '.$allnames{$name}.']';
 6132:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6133:       $$metacache{"$key.display"}=$olddis;
 6134:     }
 6135: }
 6136: 
 6137: # ------------------------------------------------------ Devalidate title cache
 6138: 
 6139: sub devalidate_title_cache {
 6140:     my ($url)=@_;
 6141:     if (!$env{'request.course.id'}) { return; }
 6142:     my $symb=&symbread($url);
 6143:     if (!$symb) { return; }
 6144:     my $key=$env{'request.course.id'}."\0".$symb;
 6145:     &devalidate_cache_new('title',$key);
 6146: }
 6147: 
 6148: # ------------------------------------------------- Get the title of a resource
 6149: 
 6150: sub gettitle {
 6151:     my $urlsymb=shift;
 6152:     my $symb=&symbread($urlsymb);
 6153:     if ($symb) {
 6154: 	my $key=$env{'request.course.id'}."\0".$symb;
 6155: 	my ($result,$cached)=&is_cached_new('title',$key);
 6156: 	if (defined($cached)) { 
 6157: 	    return $result;
 6158: 	}
 6159: 	my ($map,$resid,$url)=&decode_symb($symb);
 6160: 	my $title='';
 6161: 	my %bighash;
 6162: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6163: 		&GDBM_READER(),0640)) {
 6164: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6165: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6166: 	    untie %bighash;
 6167: 	}
 6168: 	$title=~s/\&colon\;/\:/gs;
 6169: 	if ($title) {
 6170: 	    return &do_cache_new('title',$key,$title,600);
 6171: 	}
 6172: 	$urlsymb=$url;
 6173:     }
 6174:     my $title=&metadata($urlsymb,'title');
 6175:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6176:     return $title;
 6177: }
 6178: 
 6179: sub get_slot {
 6180:     my ($which,$cnum,$cdom)=@_;
 6181:     if (!$cnum || !$cdom) {
 6182: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 6183: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6184: 	$cnum=$env{'course.'.$courseid.'.num'};
 6185:     }
 6186:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6187:     my %slotinfo;
 6188:     if (exists($remembered{$key})) {
 6189: 	$slotinfo{$which} = $remembered{$key};
 6190:     } else {
 6191: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6192: 	&Apache::lonhomework::showhash(%slotinfo);
 6193: 	my ($tmp)=keys(%slotinfo);
 6194: 	if ($tmp=~/^error:/) { return (); }
 6195: 	$remembered{$key} = $slotinfo{$which};
 6196:     }
 6197:     if (ref($slotinfo{$which}) eq 'HASH') {
 6198: 	return %{$slotinfo{$which}};
 6199:     }
 6200:     return $slotinfo{$which};
 6201: }
 6202: # ------------------------------------------------- Update symbolic store links
 6203: 
 6204: sub symblist {
 6205:     my ($mapname,%newhash)=@_;
 6206:     $mapname=&deversion(&declutter($mapname));
 6207:     my %hash;
 6208:     if (($env{'request.course.fn'}) && (%newhash)) {
 6209:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6210:                       &GDBM_WRCREAT(),0640)) {
 6211: 	    foreach my $url (keys %newhash) {
 6212: 		next if ($url eq 'last_known'
 6213: 			 && $env{'form.no_update_last_known'});
 6214: 		$hash{declutter($url)}=&encode_symb($mapname,
 6215: 						    $newhash{$url}->[1],
 6216: 						    $newhash{$url}->[0]);
 6217:             }
 6218:             if (untie(%hash)) {
 6219: 		return 'ok';
 6220:             }
 6221:         }
 6222:     }
 6223:     return 'error';
 6224: }
 6225: 
 6226: # --------------------------------------------------------------- Verify a symb
 6227: 
 6228: sub symbverify {
 6229:     my ($symb,$thisurl)=@_;
 6230:     my $thisfn=$thisurl;
 6231: # wrapper not part of symbs
 6232:     $thisfn=~s/^\/adm\/wrapper//;
 6233:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 6234:     $thisfn=&declutter($thisfn);
 6235: # direct jump to resource in page or to a sequence - will construct own symbs
 6236:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6237: # check URL part
 6238:     my ($map,$resid,$url)=&decode_symb($symb);
 6239: 
 6240:     unless ($url eq $thisfn) { return 0; }
 6241: 
 6242:     $symb=&symbclean($symb);
 6243:     $thisurl=&deversion($thisurl);
 6244:     $thisfn=&deversion($thisfn);
 6245: 
 6246:     my %bighash;
 6247:     my $okay=0;
 6248: 
 6249:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6250:                             &GDBM_READER(),0640)) {
 6251:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6252:         unless ($ids) { 
 6253:            $ids=$bighash{'ids_/'.$thisurl};
 6254:         }
 6255:         if ($ids) {
 6256: # ------------------------------------------------------------------- Has ID(s)
 6257: 	    foreach (split(/\,/,$ids)) {
 6258: 	       my ($mapid,$resid)=split(/\./,$_);
 6259:                if (
 6260:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6261:    eq $symb) { 
 6262: 		   if (($env{'request.role.adv'}) ||
 6263: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 6264: 		       $okay=1; 
 6265: 		   }
 6266: 	       }
 6267: 	   }
 6268:         }
 6269: 	untie(%bighash);
 6270:     }
 6271:     return $okay;
 6272: }
 6273: 
 6274: # --------------------------------------------------------------- Clean-up symb
 6275: 
 6276: sub symbclean {
 6277:     my $symb=shift;
 6278:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6279: # remove version from map
 6280:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6281: 
 6282: # remove version from URL
 6283:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6284: 
 6285: # remove wrapper
 6286: 
 6287:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6288:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6289:     return $symb;
 6290: }
 6291: 
 6292: # ---------------------------------------------- Split symb to find map and url
 6293: 
 6294: sub encode_symb {
 6295:     my ($map,$resid,$url)=@_;
 6296:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6297: }
 6298: 
 6299: sub decode_symb {
 6300:     my $symb=shift;
 6301:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6302:     my ($map,$resid,$url)=split(/___/,$symb);
 6303:     return (&fixversion($map),$resid,&fixversion($url));
 6304: }
 6305: 
 6306: sub fixversion {
 6307:     my $fn=shift;
 6308:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6309:     my %bighash;
 6310:     my $uri=&clutter($fn);
 6311:     my $key=$env{'request.course.id'}.'_'.$uri;
 6312: # is this cached?
 6313:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6314:     if (defined($cached)) { return $result; }
 6315: # unfortunately not cached, or expired
 6316:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6317: 	    &GDBM_READER(),0640)) {
 6318:  	if ($bighash{'version_'.$uri}) {
 6319:  	    my $version=$bighash{'version_'.$uri};
 6320:  	    unless (($version eq 'mostrecent') || 
 6321: 		    ($version==&getversion($uri))) {
 6322:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6323:  	    }
 6324:  	}
 6325:  	untie %bighash;
 6326:     }
 6327:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6328: }
 6329: 
 6330: sub deversion {
 6331:     my $url=shift;
 6332:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6333:     return $url;
 6334: }
 6335: 
 6336: # ------------------------------------------------------ Return symb list entry
 6337: 
 6338: sub symbread {
 6339:     my ($thisfn,$donotrecurse)=@_;
 6340:     my $cache_str='request.symbread.cached.'.$thisfn;
 6341:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6342: # no filename provided? try from environment
 6343:     unless ($thisfn) {
 6344:         if ($env{'request.symb'}) {
 6345: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6346: 	}
 6347: 	$thisfn=$env{'request.filename'};
 6348:     }
 6349:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6350: # is that filename actually a symb? Verify, clean, and return
 6351:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6352: 	if (&symbverify($thisfn,$1)) {
 6353: 	    return $env{$cache_str}=&symbclean($thisfn);
 6354: 	}
 6355:     }
 6356:     $thisfn=declutter($thisfn);
 6357:     my %hash;
 6358:     my %bighash;
 6359:     my $syval='';
 6360:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6361:         my $targetfn = $thisfn;
 6362:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6363:             $targetfn = 'adm/wrapper/'.$thisfn;
 6364:         }
 6365: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6366: 	    $targetfn=$1;
 6367: 	}
 6368:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6369:                       &GDBM_READER(),0640)) {
 6370: 	    $syval=$hash{$targetfn};
 6371:             untie(%hash);
 6372:         }
 6373: # ---------------------------------------------------------- There was an entry
 6374:         if ($syval) {
 6375: 	    #unless ($syval=~/\_\d+$/) {
 6376: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6377: 		    #&appenv('request.ambiguous' => $thisfn);
 6378: 		    #return $env{$cache_str}='';
 6379: 		#}    
 6380: 		#$syval.=$1;
 6381: 	    #}
 6382:         } else {
 6383: # ------------------------------------------------------- Was not in symb table
 6384:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6385:                             &GDBM_READER(),0640)) {
 6386: # ---------------------------------------------- Get ID(s) for current resource
 6387:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6388:               unless ($ids) { 
 6389:                  $ids=$bighash{'ids_/'.$thisfn};
 6390:               }
 6391:               unless ($ids) {
 6392: # alias?
 6393: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6394:               }
 6395:               if ($ids) {
 6396: # ------------------------------------------------------------------- Has ID(s)
 6397:                  my @possibilities=split(/\,/,$ids);
 6398:                  if ($#possibilities==0) {
 6399: # ----------------------------------------------- There is only one possibility
 6400: 		     my ($mapid,$resid)=split(/\./,$ids);
 6401: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6402: 						    $resid,$thisfn);
 6403:                  } elsif (!$donotrecurse) {
 6404: # ------------------------------------------ There is more than one possibility
 6405:                      my $realpossible=0;
 6406:                      foreach (@possibilities) {
 6407: 			 my $file=$bighash{'src_'.$_};
 6408:                          if (&allowed('bre',$file)) {
 6409:          		    my ($mapid,$resid)=split(/\./,$_);
 6410:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6411: 				$realpossible++;
 6412:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6413: 						    $resid,$thisfn);
 6414:                             }
 6415: 			 }
 6416:                      }
 6417: 		     if ($realpossible!=1) { $syval=''; }
 6418:                  } else {
 6419:                      $syval='';
 6420:                  }
 6421: 	      }
 6422:               untie(%bighash)
 6423:            }
 6424:         }
 6425:         if ($syval) {
 6426: 	    return $env{$cache_str}=$syval;
 6427:         }
 6428:     }
 6429:     &appenv('request.ambiguous' => $thisfn);
 6430:     return $env{$cache_str}='';
 6431: }
 6432: 
 6433: # ---------------------------------------------------------- Return random seed
 6434: 
 6435: sub numval {
 6436:     my $txt=shift;
 6437:     $txt=~tr/A-J/0-9/;
 6438:     $txt=~tr/a-j/0-9/;
 6439:     $txt=~tr/K-T/0-9/;
 6440:     $txt=~tr/k-t/0-9/;
 6441:     $txt=~tr/U-Z/0-5/;
 6442:     $txt=~tr/u-z/0-5/;
 6443:     $txt=~s/\D//g;
 6444:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6445:     return int($txt);
 6446: }
 6447: 
 6448: sub numval2 {
 6449:     my $txt=shift;
 6450:     $txt=~tr/A-J/0-9/;
 6451:     $txt=~tr/a-j/0-9/;
 6452:     $txt=~tr/K-T/0-9/;
 6453:     $txt=~tr/k-t/0-9/;
 6454:     $txt=~tr/U-Z/0-5/;
 6455:     $txt=~tr/u-z/0-5/;
 6456:     $txt=~s/\D//g;
 6457:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6458:     my $total;
 6459:     foreach my $val (@txts) { $total+=$val; }
 6460:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6461:     return int($total);
 6462: }
 6463: 
 6464: sub numval3 {
 6465:     use integer;
 6466:     my $txt=shift;
 6467:     $txt=~tr/A-J/0-9/;
 6468:     $txt=~tr/a-j/0-9/;
 6469:     $txt=~tr/K-T/0-9/;
 6470:     $txt=~tr/k-t/0-9/;
 6471:     $txt=~tr/U-Z/0-5/;
 6472:     $txt=~tr/u-z/0-5/;
 6473:     $txt=~s/\D//g;
 6474:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6475:     my $total;
 6476:     foreach my $val (@txts) { $total+=$val; }
 6477:     if ($_64bit) { $total=(($total<<32)>>32); }
 6478:     return $total;
 6479: }
 6480: 
 6481: sub digest {
 6482:     my ($data)=@_;
 6483:     my $digest=&Digest::MD5::md5($data);
 6484:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6485:     my ($e,$f);
 6486:     {
 6487:         use integer;
 6488:         $e=($a+$b);
 6489:         $f=($c+$d);
 6490:         if ($_64bit) {
 6491:             $e=(($e<<32)>>32);
 6492:             $f=(($f<<32)>>32);
 6493:         }
 6494:     }
 6495:     if (wantarray) {
 6496: 	return ($e,$f);
 6497:     } else {
 6498: 	my $g;
 6499: 	{
 6500: 	    use integer;
 6501: 	    $g=($e+$f);
 6502: 	    if ($_64bit) {
 6503: 		$g=(($g<<32)>>32);
 6504: 	    }
 6505: 	}
 6506: 	return $g;
 6507:     }
 6508: }
 6509: 
 6510: sub latest_rnd_algorithm_id {
 6511:     return '64bit5';
 6512: }
 6513: 
 6514: sub get_rand_alg {
 6515:     my ($courseid)=@_;
 6516:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 6517:     if ($courseid) {
 6518: 	return $env{"course.$courseid.rndseed"};
 6519:     }
 6520:     return &latest_rnd_algorithm_id();
 6521: }
 6522: 
 6523: sub validCODE {
 6524:     my ($CODE)=@_;
 6525:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6526:     return 0;
 6527: }
 6528: 
 6529: sub getCODE {
 6530:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6531:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6532: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6533: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6534: 	return $Apache::lonhomework::history{'resource.CODE'};
 6535:     }
 6536:     return undef;
 6537: }
 6538: 
 6539: sub rndseed {
 6540:     my ($symb,$courseid,$domain,$username)=@_;
 6541: 
 6542:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 6543:     if (!$symb) {
 6544: 	unless ($symb=$wsymb) { return time; }
 6545:     }
 6546:     if (!$courseid) { $courseid=$wcourseid; }
 6547:     if (!$domain) { $domain=$wdomain; }
 6548:     if (!$username) { $username=$wusername }
 6549:     my $which=&get_rand_alg();
 6550:     if (defined(&getCODE())) {
 6551: 	if ($which eq '64bit5') {
 6552: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6553: 	} elsif ($which eq '64bit4') {
 6554: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6555: 	} else {
 6556: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6557: 	}
 6558:     } elsif ($which eq '64bit5') {
 6559: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6560:     } elsif ($which eq '64bit4') {
 6561: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6562:     } elsif ($which eq '64bit3') {
 6563: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6564:     } elsif ($which eq '64bit2') {
 6565: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6566:     } elsif ($which eq '64bit') {
 6567: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6568:     }
 6569:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6570: }
 6571: 
 6572: sub rndseed_32bit {
 6573:     my ($symb,$courseid,$domain,$username)=@_;
 6574:     {
 6575: 	use integer;
 6576: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6577: 	my $symbseed=numval($symb) << 22;
 6578: 	my $namechck=unpack("%32C*",$username) << 17;
 6579: 	my $nameseed=numval($username) << 12;
 6580: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6581: 	my $courseseed=unpack("%32C*",$courseid);
 6582: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6583: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6584: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6585: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6586: 	return $num;
 6587:     }
 6588: }
 6589: 
 6590: sub rndseed_64bit {
 6591:     my ($symb,$courseid,$domain,$username)=@_;
 6592:     {
 6593: 	use integer;
 6594: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6595: 	my $symbseed=numval($symb) << 10;
 6596: 	my $namechck=unpack("%32S*",$username);
 6597: 	
 6598: 	my $nameseed=numval($username) << 21;
 6599: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6600: 	my $courseseed=unpack("%32S*",$courseid);
 6601: 	
 6602: 	my $num1=$symbchck+$symbseed+$namechck;
 6603: 	my $num2=$nameseed+$domainseed+$courseseed;
 6604: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6605: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6606: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6607: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6608: 	return "$num1,$num2";
 6609:     }
 6610: }
 6611: 
 6612: sub rndseed_64bit2 {
 6613:     my ($symb,$courseid,$domain,$username)=@_;
 6614:     {
 6615: 	use integer;
 6616: 	# strings need to be an even # of cahracters long, it it is odd the
 6617:         # last characters gets thrown away
 6618: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6619: 	my $symbseed=numval($symb) << 10;
 6620: 	my $namechck=unpack("%32S*",$username.' ');
 6621: 	
 6622: 	my $nameseed=numval($username) << 21;
 6623: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6624: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6625: 	
 6626: 	my $num1=$symbchck+$symbseed+$namechck;
 6627: 	my $num2=$nameseed+$domainseed+$courseseed;
 6628: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6629: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6630: 	return "$num1,$num2";
 6631:     }
 6632: }
 6633: 
 6634: sub rndseed_64bit3 {
 6635:     my ($symb,$courseid,$domain,$username)=@_;
 6636:     {
 6637: 	use integer;
 6638: 	# strings need to be an even # of cahracters long, it it is odd the
 6639:         # last characters gets thrown away
 6640: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6641: 	my $symbseed=numval2($symb) << 10;
 6642: 	my $namechck=unpack("%32S*",$username.' ');
 6643: 	
 6644: 	my $nameseed=numval2($username) << 21;
 6645: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6646: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6647: 	
 6648: 	my $num1=$symbchck+$symbseed+$namechck;
 6649: 	my $num2=$nameseed+$domainseed+$courseseed;
 6650: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6651: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6652: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6653: 	
 6654: 	return "$num1:$num2";
 6655:     }
 6656: }
 6657: 
 6658: sub rndseed_64bit4 {
 6659:     my ($symb,$courseid,$domain,$username)=@_;
 6660:     {
 6661: 	use integer;
 6662: 	# strings need to be an even # of cahracters long, it it is odd the
 6663:         # last characters gets thrown away
 6664: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6665: 	my $symbseed=numval3($symb) << 10;
 6666: 	my $namechck=unpack("%32S*",$username.' ');
 6667: 	
 6668: 	my $nameseed=numval3($username) << 21;
 6669: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6670: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6671: 	
 6672: 	my $num1=$symbchck+$symbseed+$namechck;
 6673: 	my $num2=$nameseed+$domainseed+$courseseed;
 6674: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6675: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6676: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6677: 	
 6678: 	return "$num1:$num2";
 6679:     }
 6680: }
 6681: 
 6682: sub rndseed_64bit5 {
 6683:     my ($symb,$courseid,$domain,$username)=@_;
 6684:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6685:     return "$num1:$num2";
 6686: }
 6687: 
 6688: sub rndseed_CODE_64bit {
 6689:     my ($symb,$courseid,$domain,$username)=@_;
 6690:     {
 6691: 	use integer;
 6692: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6693: 	my $symbseed=numval2($symb);
 6694: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6695: 	my $CODEseed=numval(&getCODE());
 6696: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6697: 	my $num1=$symbseed+$CODEchck;
 6698: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6699: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6700: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6701: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6702: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6703: 	return "$num1:$num2";
 6704:     }
 6705: }
 6706: 
 6707: sub rndseed_CODE_64bit4 {
 6708:     my ($symb,$courseid,$domain,$username)=@_;
 6709:     {
 6710: 	use integer;
 6711: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6712: 	my $symbseed=numval3($symb);
 6713: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6714: 	my $CODEseed=numval3(&getCODE());
 6715: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6716: 	my $num1=$symbseed+$CODEchck;
 6717: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6718: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6719: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6720: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6721: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6722: 	return "$num1:$num2";
 6723:     }
 6724: }
 6725: 
 6726: sub rndseed_CODE_64bit5 {
 6727:     my ($symb,$courseid,$domain,$username)=@_;
 6728:     my $code = &getCODE();
 6729:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6730:     return "$num1:$num2";
 6731: }
 6732: 
 6733: sub setup_random_from_rndseed {
 6734:     my ($rndseed)=@_;
 6735:     if ($rndseed =~/([,:])/) {
 6736: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6737: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6738:     } else {
 6739: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6740:     }
 6741: }
 6742: 
 6743: sub latest_receipt_algorithm_id {
 6744:     return 'receipt2';
 6745: }
 6746: 
 6747: sub recunique {
 6748:     my $fucourseid=shift;
 6749:     my $unique;
 6750:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6751: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6752:     } else {
 6753: 	$unique=$perlvar{'lonReceipt'};
 6754:     }
 6755:     return unpack("%32C*",$unique);
 6756: }
 6757: 
 6758: sub recprefix {
 6759:     my $fucourseid=shift;
 6760:     my $prefix;
 6761:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6762: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6763:     } else {
 6764: 	$prefix=$perlvar{'lonHostID'};
 6765:     }
 6766:     return unpack("%32C*",$prefix);
 6767: }
 6768: 
 6769: sub ireceipt {
 6770:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6771:     my $cuname=unpack("%32C*",$funame);
 6772:     my $cudom=unpack("%32C*",$fudom);
 6773:     my $cucourseid=unpack("%32C*",$fucourseid);
 6774:     my $cusymb=unpack("%32C*",$fusymb);
 6775:     my $cunique=&recunique($fucourseid);
 6776:     my $cpart=unpack("%32S*",$part);
 6777:     my $return =&recprefix($fucourseid).'-';
 6778:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6779: 	$env{'request.state'} eq 'construct') {
 6780: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6781: 			       " and ".($cpart%$cudom));
 6782: 			       
 6783: 	$return.= ($cunique%$cuname+
 6784: 		   $cunique%$cudom+
 6785: 		   $cusymb%$cuname+
 6786: 		   $cusymb%$cudom+
 6787: 		   $cucourseid%$cuname+
 6788: 		   $cucourseid%$cudom+
 6789: 		   $cpart%$cuname+
 6790: 		   $cpart%$cudom);
 6791:     } else {
 6792: 	$return.= ($cunique%$cuname+
 6793: 		   $cunique%$cudom+
 6794: 		   $cusymb%$cuname+
 6795: 		   $cusymb%$cudom+
 6796: 		   $cucourseid%$cuname+
 6797: 		   $cucourseid%$cudom);
 6798:     }
 6799:     return $return;
 6800: }
 6801: 
 6802: sub receipt {
 6803:     my ($part)=@_;
 6804:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6805:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6806: }
 6807: 
 6808: # ------------------------------------------------------------ Serves up a file
 6809: # returns either the contents of the file or 
 6810: # -1 if the file doesn't exist
 6811: #
 6812: # if the target is a file that was uploaded via DOCS, 
 6813: # a check will be made to see if a current copy exists on the local server,
 6814: # if it does this will be served, otherwise a copy will be retrieved from
 6815: # the home server for the course and stored in /home/httpd/html/userfiles on
 6816: # the local server.   
 6817: 
 6818: sub getfile {
 6819:     my ($file) = @_;
 6820:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6821:     &repcopy($file);
 6822:     return &readfile($file);
 6823: }
 6824: 
 6825: sub repcopy_userfile {
 6826:     my ($file)=@_;
 6827:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6828:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6829:     my ($cdom,$cnum,$filename) = 
 6830: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6831:     my ($info,$rtncode);
 6832:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6833:     if (-e "$file") {
 6834: 	my @fileinfo = stat($file);
 6835: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6836: 	if ($lwpresp ne 'ok') {
 6837: 	    if ($rtncode eq '404') {
 6838: 		unlink($file);
 6839: 	    }
 6840: 	    #my $ua=new LWP::UserAgent;
 6841: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6842: 	    #my $response=$ua->request($request);
 6843: 	    #if ($response->is_success()) {
 6844: 	#	return $response->content;
 6845: 	#    } else {
 6846: 	#	return -1;
 6847: 	#    }
 6848: 	    return -1;
 6849: 	}
 6850: 	if ($info < $fileinfo[9]) {
 6851: 	    return 'ok';
 6852: 	}
 6853: 	$info = '';
 6854: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6855: 	if ($lwpresp ne 'ok') {
 6856: 	    return -1;
 6857: 	}
 6858:     } else {
 6859: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6860: 	if ($lwpresp ne 'ok') {
 6861: 	    my $ua=new LWP::UserAgent;
 6862: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6863: 	    my $response=$ua->request($request);
 6864: 	    if ($response->is_success()) {
 6865: 		$info=$response->content;
 6866: 	    } else {
 6867: 		return -1;
 6868: 	    }
 6869: 	}
 6870: 	my @parts = ($cdom,$cnum); 
 6871: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6872: 	    push @parts, split(/\//,$1);
 6873: 	}
 6874: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6875: 	foreach my $part (@parts) {
 6876: 	    $path .= '/'.$part;
 6877: 	    if (!-e $path) {
 6878: 		mkdir($path,0770);
 6879: 	    }
 6880: 	}
 6881:     }
 6882:     open(FILE,">$file");
 6883:     print FILE $info;
 6884:     close(FILE);
 6885:     return 'ok';
 6886: }
 6887: 
 6888: sub tokenwrapper {
 6889:     my $uri=shift;
 6890:     $uri=~s|^http\://([^/]+)||;
 6891:     $uri=~s|^/||;
 6892:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6893:     my $token=$1;
 6894:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6895:     if ($udom && $uname && $file) {
 6896: 	$file=~s|(\?\.*)*$||;
 6897:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6898:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6899:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6900:                                '&tokenissued='.$perlvar{'lonHostID'};
 6901:     } else {
 6902:         return '/adm/notfound.html';
 6903:     }
 6904: }
 6905: 
 6906: sub getuploaded {
 6907:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6908:     $uri=~s/^\///;
 6909:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6910:     my $ua=new LWP::UserAgent;
 6911:     my $request=new HTTP::Request($reqtype,$uri);
 6912:     my $response=$ua->request($request);
 6913:     $$rtncode = $response->code;
 6914:     if (! $response->is_success()) {
 6915: 	return 'failed';
 6916:     }      
 6917:     if ($reqtype eq 'HEAD') {
 6918: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6919:     } elsif ($reqtype eq 'GET') {
 6920: 	$$info = $response->content;
 6921:     }
 6922:     return 'ok';
 6923: }
 6924: 
 6925: sub readfile {
 6926:     my $file = shift;
 6927:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6928:     my $fh;
 6929:     open($fh,"<$file");
 6930:     my $a='';
 6931:     while (<$fh>) { $a .=$_; }
 6932:     return $a;
 6933: }
 6934: 
 6935: sub filelocation {
 6936:     my ($dir,$file) = @_;
 6937:     my $location;
 6938:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6939: 
 6940:     if ($file =~ m-^/adm/-) {
 6941: 	$file=~s-^/adm/wrapper/-/-;
 6942: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6943:     }
 6944:     if ($file=~m:^/~:) { # is a contruction space reference
 6945:         $location = $file;
 6946:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6947:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6948: 	# is a correct contruction space reference
 6949:         $location = $file;
 6950:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6951:         my ($udom,$uname,$filename)=
 6952:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6953:         my $home=&homeserver($uname,$udom);
 6954:         my $is_me=0;
 6955:         my @ids=&current_machine_ids();
 6956:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6957:         if ($is_me) {
 6958:   	    $location=&propath($udom,$uname).
 6959:   	      '/userfiles/'.$filename;
 6960:         } else {
 6961:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6962:   	      $udom.'/'.$uname.'/'.$filename;
 6963:         }
 6964:     } else {
 6965:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6966:         $file=~s:^/res/:/:;
 6967:         if ( !( $file =~ m:^/:) ) {
 6968:             $location = $dir. '/'.$file;
 6969:         } else {
 6970:             $location = '/home/httpd/html/res'.$file;
 6971:         }
 6972:     }
 6973:     $location=~s://+:/:g; # remove duplicate /
 6974:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6975:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6976:     return $location;
 6977: }
 6978: 
 6979: sub hreflocation {
 6980:     my ($dir,$file)=@_;
 6981:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6982: 	$file=filelocation($dir,$file);
 6983:     } elsif ($file=~m-^/adm/-) {
 6984: 	$file=~s-^/adm/wrapper/-/-;
 6985: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6986:     }
 6987:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6988: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6989:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6990: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6991:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6992: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6993: 	    -/uploaded/$1/$2/-x;
 6994:     }
 6995:     return $file;
 6996: }
 6997: 
 6998: sub current_machine_domains {
 6999:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7000:     my @domains;
 7001:     while( my($id, $name) = each(%hostname)) {
 7002: #	&logthis("-$id-$name-$hostname-");
 7003: 	if ($hostname eq $name) {
 7004: 	    push(@domains,$hostdom{$id});
 7005: 	}
 7006:     }
 7007:     return @domains;
 7008: }
 7009: 
 7010: sub current_machine_ids {
 7011:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7012:     my @ids;
 7013:     while( my($id, $name) = each(%hostname)) {
 7014: #	&logthis("-$id-$name-$hostname-");
 7015: 	if ($hostname eq $name) {
 7016: 	    push(@ids,$id);
 7017: 	}
 7018:     }
 7019:     return @ids;
 7020: }
 7021: 
 7022: # ------------------------------------------------------------- Declutters URLs
 7023: 
 7024: sub declutter {
 7025:     my $thisfn=shift;
 7026:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7027:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7028:     $thisfn=~s/^\///;
 7029:     $thisfn=~s|^adm/wrapper/||;
 7030:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7031:     $thisfn=~s/^res\///;
 7032:     $thisfn=~s/\?.+$//;
 7033:     return $thisfn;
 7034: }
 7035: 
 7036: # ------------------------------------------------------------- Clutter up URLs
 7037: 
 7038: sub clutter {
 7039:     my $thisfn='/'.&declutter(shift);
 7040:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7041:        $thisfn='/res'.$thisfn; 
 7042:     }
 7043:     if ($thisfn !~m|/adm|) {
 7044: 	if ($thisfn =~ m|/ext/|) {
 7045: 	    $thisfn='/adm/wrapper'.$thisfn;
 7046: 	} else {
 7047: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7048: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7049: 	    if ($embstyle eq 'ssi'
 7050: 		|| ($embstyle eq 'hdn')
 7051: 		|| ($embstyle eq 'rat')
 7052: 		|| ($embstyle eq 'prv')
 7053: 		|| ($embstyle eq 'ign')) {
 7054: 		#do nothing with these
 7055: 	    } elsif (($embstyle eq 'img') 
 7056: 		|| ($embstyle eq 'emb')
 7057: 		|| ($embstyle eq 'wrp')) {
 7058: 		$thisfn='/adm/wrapper'.$thisfn;
 7059: 	    } elsif ($embstyle eq 'unk'
 7060: 		     && $thisfn!~/\.(sequence|page)$/) {
 7061: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7062: 	    } else {
 7063: #		&logthis("Got a blank emb style");
 7064: 	    }
 7065: 	}
 7066:     }
 7067:     return $thisfn;
 7068: }
 7069: 
 7070: sub freeze_escape {
 7071:     my ($value)=@_;
 7072:     if (ref($value)) {
 7073: 	$value=&nfreeze($value);
 7074: 	return '__FROZEN__'.&escape($value);
 7075:     }
 7076:     return &escape($value);
 7077: }
 7078: 
 7079: 
 7080: sub thaw_unescape {
 7081:     my ($value)=@_;
 7082:     if ($value =~ /^__FROZEN__/) {
 7083: 	substr($value,0,10,undef);
 7084: 	$value=&unescape($value);
 7085: 	return &thaw($value);
 7086:     }
 7087:     return &unescape($value);
 7088: }
 7089: 
 7090: sub correct_line_ends {
 7091:     my ($result)=@_;
 7092:     $$result =~s/\r\n/\n/mg;
 7093:     $$result =~s/\r/\n/mg;
 7094: }
 7095: # ================================================================ Main Program
 7096: 
 7097: sub goodbye {
 7098:    &logthis("Starting Shut down");
 7099: #not converted to using infrastruture and probably shouldn't be
 7100:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7101: #converted
 7102: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7103:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7104: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7105: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7106: #1.1 only
 7107: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7108: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7109: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7110: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7111:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7112:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7113:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7114:    &flushcourselogs();
 7115:    &logthis("Shutting down");
 7116: }
 7117: 
 7118: BEGIN {
 7119: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7120:     unless ($readit) {
 7121: {
 7122:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7123:     %perlvar = (%perlvar,%{$configvars});
 7124: }
 7125: 
 7126: # ------------------------------------------------------------ Read domain file
 7127: {
 7128:     %domaindescription = ();
 7129:     %domain_auth_def = ();
 7130:     %domain_auth_arg_def = ();
 7131:     my $fh;
 7132:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7133:        while (<$fh>) {
 7134:            next if (/^(\#|\s*$)/);
 7135: #           next if /^\#/;
 7136:            chomp;
 7137:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7138: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 7139: 	   $domain_auth_def{$domain}=$def_auth;
 7140:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7141: 	   $domaindescription{$domain}=$domain_description;
 7142: 	   $domain_lang_def{$domain}=$def_lang;
 7143: 	   $domain_city{$domain}=$city;
 7144: 	   $domain_longi{$domain}=$longi;
 7145: 	   $domain_lati{$domain}=$lati;
 7146:            $domain_primary{$domain}=$primary;
 7147: 
 7148:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7149: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7150: 	}
 7151:     }
 7152:     close ($fh);
 7153: }
 7154: 
 7155: 
 7156: # ------------------------------------------------------------- Read hosts file
 7157: {
 7158:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7159: 
 7160:     while (my $configline=<$config>) {
 7161:        next if ($configline =~ /^(\#|\s*$)/);
 7162:        chomp($configline);
 7163:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7164:        $name=~s/\s//g;
 7165:        if ($id && $domain && $role && $name) {
 7166: 	 $hostname{$id}=$name;
 7167: 	 $hostdom{$id}=$domain;
 7168: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7169:        }
 7170:     }
 7171:     close($config);
 7172:     # FIXME: dev server don't want this, production servers _do_ want this
 7173:     #&get_iphost();
 7174: }
 7175: 
 7176: sub get_iphost {
 7177:     if (%iphost) { return %iphost; }
 7178:     my %name_to_ip;
 7179:     foreach my $id (keys(%hostname)) {
 7180: 	my $name=$hostname{$id};
 7181: 	my $ip;
 7182: 	if (!exists($name_to_ip{$name})) {
 7183: 	    $ip = gethostbyname($name);
 7184: 	    if (!$ip || length($ip) ne 4) {
 7185: 		&logthis("Skipping host $id name $name no IP found\n");
 7186: 		next;
 7187: 	    }
 7188: 	    $ip=inet_ntoa($ip);
 7189: 	    $name_to_ip{$name} = $ip;
 7190: 	} else {
 7191: 	    $ip = $name_to_ip{$name};
 7192: 	}
 7193: 	push(@{$iphost{$ip}},$id);
 7194:     }
 7195:     return %iphost;
 7196: }
 7197: 
 7198: # ------------------------------------------------------ Read spare server file
 7199: {
 7200:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7201: 
 7202:     while (my $configline=<$config>) {
 7203:        chomp($configline);
 7204:        if ($configline) {
 7205: 	   my ($host,$type) = split(':',$configline,2);
 7206: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7207: 	   push(@{ $spareid{$type} }, $host);
 7208:        }
 7209:     }
 7210:     close($config);
 7211: }
 7212: # ------------------------------------------------------------ Read permissions
 7213: {
 7214:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7215: 
 7216:     while (my $configline=<$config>) {
 7217: 	chomp($configline);
 7218: 	if ($configline) {
 7219: 	    my ($role,$perm)=split(/ /,$configline);
 7220: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7221: 	}
 7222:     }
 7223:     close($config);
 7224: }
 7225: 
 7226: # -------------------------------------------- Read plain texts for permissions
 7227: {
 7228:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7229: 
 7230:     while (my $configline=<$config>) {
 7231: 	chomp($configline);
 7232: 	if ($configline) {
 7233: 	    my ($short,@plain)=split(/:/,$configline);
 7234:             %{$prp{$short}} = ();
 7235: 	    if (@plain > 0) {
 7236:                 $prp{$short}{'std'} = $plain[0];
 7237:                 for (my $i=1; $i<@plain; $i++) {
 7238:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7239:                 }
 7240:             }
 7241: 	}
 7242:     }
 7243:     close($config);
 7244: }
 7245: 
 7246: # ---------------------------------------------------------- Read package table
 7247: {
 7248:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7249: 
 7250:     while (my $configline=<$config>) {
 7251: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7252: 	chomp($configline);
 7253: 	my ($short,$plain)=split(/:/,$configline);
 7254: 	my ($pack,$name)=split(/\&/,$short);
 7255: 	if ($plain ne '') {
 7256: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7257: 	    $packagetab{$short}=$plain; 
 7258: 	}
 7259:     }
 7260:     close($config);
 7261: }
 7262: 
 7263: # ------------- set up temporary directory
 7264: {
 7265:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7266: 
 7267: }
 7268: 
 7269: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 7270: 
 7271: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7272: $dumpcount=0;
 7273: 
 7274: &logtouch();
 7275: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7276: $readit=1;
 7277:     {
 7278: 	use integer;
 7279: 	my $test=(2**32)+1;
 7280: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7281: 	&logthis(" Detected 64bit platform ($_64bit)");
 7282:     }
 7283: }
 7284: }
 7285: 
 7286: 1;
 7287: __END__
 7288: 
 7289: =pod
 7290: 
 7291: =head1 NAME
 7292: 
 7293: Apache::lonnet - Subroutines to ask questions about things in the network.
 7294: 
 7295: =head1 SYNOPSIS
 7296: 
 7297: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7298: 
 7299:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7300: 
 7301: Common parameters:
 7302: 
 7303: =over 4
 7304: 
 7305: =item *
 7306: 
 7307: $uname : an internal username (if $cname expecting a course Id specifically)
 7308: 
 7309: =item *
 7310: 
 7311: $udom : a domain (if $cdom expecting a course's domain specifically)
 7312: 
 7313: =item *
 7314: 
 7315: $symb : a resource instance identifier
 7316: 
 7317: =item *
 7318: 
 7319: $namespace : the name of a .db file that contains the data needed or
 7320: being set.
 7321: 
 7322: =back
 7323: 
 7324: =head1 OVERVIEW
 7325: 
 7326: lonnet provides subroutines which interact with the
 7327: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7328: about classes, users, and resources.
 7329: 
 7330: For many of these objects you can also use this to store data about
 7331: them or modify them in various ways.
 7332: 
 7333: =head2 Symbs
 7334: 
 7335: To identify a specific instance of a resource, LON-CAPA uses symbols
 7336: or "symbs"X<symb>. These identifiers are built from the URL of the
 7337: map, the resource number of the resource in the map, and the URL of
 7338: the resource itself. The latter is somewhat redundant, but might help
 7339: if maps change.
 7340: 
 7341: An example is
 7342: 
 7343:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7344: 
 7345: The respective map entry is
 7346: 
 7347:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7348:   title="Problem 2">
 7349:  </resource>
 7350: 
 7351: Symbs are used by the random number generator, as well as to store and
 7352: restore data specific to a certain instance of for example a problem.
 7353: 
 7354: =head2 Storing And Retrieving Data
 7355: 
 7356: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7357: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7358: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7359: is is the non-critical message twin of cstore. These functions are for
 7360: handlers to store a perl hash to a user's permanent data space in an
 7361: easy manner, and to retrieve it again on another call. It is expected
 7362: that a handler would use this once at the beginning to retrieve data,
 7363: and then again once at the end to send only the new data back.
 7364: 
 7365: The data is stored in the user's data directory on the user's
 7366: homeserver under the ID of the course.
 7367: 
 7368: The hash that is returned by restore will have all of the previous
 7369: value for all of the elements of the hash.
 7370: 
 7371: Example:
 7372: 
 7373:  #creating a hash
 7374:  my %hash;
 7375:  $hash{'foo'}='bar';
 7376: 
 7377:  #storing it
 7378:  &Apache::lonnet::cstore(\%hash);
 7379: 
 7380:  #changing a value
 7381:  $hash{'foo'}='notbar';
 7382: 
 7383:  #adding a new value
 7384:  $hash{'bar'}='foo';
 7385:  &Apache::lonnet::cstore(\%hash);
 7386: 
 7387:  #retrieving the hash
 7388:  my %history=&Apache::lonnet::restore();
 7389: 
 7390:  #print the hash
 7391:  foreach my $key (sort(keys(%history))) {
 7392:    print("\%history{$key} = $history{$key}");
 7393:  }
 7394: 
 7395: Will print out:
 7396: 
 7397:  %history{1:foo} = bar
 7398:  %history{1:keys} = foo:timestamp
 7399:  %history{1:timestamp} = 990455579
 7400:  %history{2:bar} = foo
 7401:  %history{2:foo} = notbar
 7402:  %history{2:keys} = foo:bar:timestamp
 7403:  %history{2:timestamp} = 990455580
 7404:  %history{bar} = foo
 7405:  %history{foo} = notbar
 7406:  %history{timestamp} = 990455580
 7407:  %history{version} = 2
 7408: 
 7409: Note that the special hash entries C<keys>, C<version> and
 7410: C<timestamp> were added to the hash. C<version> will be equal to the
 7411: total number of versions of the data that have been stored. The
 7412: C<timestamp> attribute will be the UNIX time the hash was
 7413: stored. C<keys> is available in every historical section to list which
 7414: keys were added or changed at a specific historical revision of a
 7415: hash.
 7416: 
 7417: B<Warning>: do not store the hash that restore returns directly. This
 7418: will cause a mess since it will restore the historical keys as if the
 7419: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7420: 
 7421: Calling convention:
 7422: 
 7423:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7424:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7425: 
 7426: For more detailed information, see lonnet specific documentation.
 7427: 
 7428: =head1 RETURN MESSAGES
 7429: 
 7430: =over 4
 7431: 
 7432: =item * B<con_lost>: unable to contact remote host
 7433: 
 7434: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7435: when the connection is brought back up
 7436: 
 7437: =item * B<con_failed>: unable to contact remote host and unable to save message
 7438: for later delivery
 7439: 
 7440: =item * B<error:>: an error a occured, a description of the error follows the :
 7441: 
 7442: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7443: that was requested
 7444: 
 7445: =back
 7446: 
 7447: =head1 PUBLIC SUBROUTINES
 7448: 
 7449: =head2 Session Environment Functions
 7450: 
 7451: =over 4
 7452: 
 7453: =item * 
 7454: X<appenv()>
 7455: B<appenv(%hash)>: the value of %hash is written to
 7456: the user envirnoment file, and will be restored for each access this
 7457: user makes during this session, also modifies the %env for the current
 7458: process
 7459: 
 7460: =item *
 7461: X<delenv()>
 7462: B<delenv($regexp)>: removes all items from the session
 7463: environment file that matches the regular expression in $regexp. The
 7464: values are also delted from the current processes %env.
 7465: 
 7466: =back
 7467: 
 7468: =head2 User Information
 7469: 
 7470: =over 4
 7471: 
 7472: =item *
 7473: X<queryauthenticate()>
 7474: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7475: authentication scheme
 7476: 
 7477: =item *
 7478: X<authenticate()>
 7479: B<authenticate($uname,$upass,$udom)>: try to
 7480: authenticate user from domain's lib servers (first use the current
 7481: one). C<$upass> should be the users password.
 7482: 
 7483: =item *
 7484: X<homeserver()>
 7485: B<homeserver($uname,$udom)>: find the server which has
 7486: the user's directory and files (there must be only one), this caches
 7487: the answer, and also caches if there is a borken connection.
 7488: 
 7489: =item *
 7490: X<idget()>
 7491: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7492: (IDs are a unique resource in a domain, there must be only 1 ID per
 7493: username, and only 1 username per ID in a specific domain) (returns
 7494: hash: id=>name,id=>name)
 7495: 
 7496: =item *
 7497: X<idrget()>
 7498: B<idrget($udom,@unames)>: find the IDs behind a list of
 7499: usernames (returns hash: name=>id,name=>id)
 7500: 
 7501: =item *
 7502: X<idput()>
 7503: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7504: 
 7505: =item *
 7506: X<rolesinit()>
 7507: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7508: 
 7509: =item *
 7510: X<getsection()>
 7511: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7512: course $cname, return section name/number or '' for "not in course"
 7513: and '-1' for "no section"
 7514: 
 7515: =item *
 7516: X<userenvironment()>
 7517: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7518: passed in @what from the requested user's environment, returns a hash
 7519: 
 7520: =back
 7521: 
 7522: =head2 User Roles
 7523: 
 7524: =over 4
 7525: 
 7526: =item *
 7527: 
 7528: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7529: actions
 7530:  F: full access
 7531:  U,I,K: authentication modes (cxx only)
 7532:  '': forbidden
 7533:  1: user needs to choose course
 7534:  2: browse allowed
 7535:  A: passphrase authentication needed
 7536: 
 7537: =item *
 7538: 
 7539: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7540: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7541: and course level
 7542: 
 7543: =item *
 7544: 
 7545: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7546: explanation of a user role term
 7547: 
 7548: =back
 7549: 
 7550: =head2 User Modification
 7551: 
 7552: =over 4
 7553: 
 7554: =item *
 7555: 
 7556: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7557: user for the level given by URL.  Optional start and end dates (leave empty
 7558: string or zero for "no date")
 7559: 
 7560: =item *
 7561: 
 7562: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7563: change a users, password, possible return values are: ok,
 7564: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7565: refused
 7566: 
 7567: =item *
 7568: 
 7569: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7570: 
 7571: =item *
 7572: 
 7573: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7574: modify user
 7575: 
 7576: =item *
 7577: 
 7578: modifystudent
 7579: 
 7580: modify a students enrollment and identification information.
 7581: The course id is resolved based on the current users environment.  
 7582: This means the envoking user must be a course coordinator or otherwise
 7583: associated with a course.
 7584: 
 7585: This call is essentially a wrapper for lonnet::modifyuser and
 7586: lonnet::modify_student_enrollment
 7587: 
 7588: Inputs: 
 7589: 
 7590: =over 4
 7591: 
 7592: =item B<$udom> Students loncapa domain
 7593: 
 7594: =item B<$uname> Students loncapa login name
 7595: 
 7596: =item B<$uid> Students id/student number
 7597: 
 7598: =item B<$umode> Students authentication mode
 7599: 
 7600: =item B<$upass> Students password
 7601: 
 7602: =item B<$first> Students first name
 7603: 
 7604: =item B<$middle> Students middle name
 7605: 
 7606: =item B<$last> Students last name
 7607: 
 7608: =item B<$gene> Students generation
 7609: 
 7610: =item B<$usec> Students section in course
 7611: 
 7612: =item B<$end> Unix time of the roles expiration
 7613: 
 7614: =item B<$start> Unix time of the roles start date
 7615: 
 7616: =item B<$forceid> If defined, allow $uid to be changed
 7617: 
 7618: =item B<$desiredhome> server to use as home server for student
 7619: 
 7620: =back
 7621: 
 7622: =item *
 7623: 
 7624: modify_student_enrollment
 7625: 
 7626: Change a students enrollment status in a class.  The environment variable
 7627: 'role.request.course' must be defined for this function to proceed.
 7628: 
 7629: Inputs:
 7630: 
 7631: =over 4
 7632: 
 7633: =item $udom, students domain
 7634: 
 7635: =item $uname, students name
 7636: 
 7637: =item $uid, students user id
 7638: 
 7639: =item $first, students first name
 7640: 
 7641: =item $middle
 7642: 
 7643: =item $last
 7644: 
 7645: =item $gene
 7646: 
 7647: =item $usec
 7648: 
 7649: =item $end
 7650: 
 7651: =item $start
 7652: 
 7653: =back
 7654: 
 7655: 
 7656: =item *
 7657: 
 7658: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7659: custom role; give a custom role to a user for the level given by URL.  Specify
 7660: name and domain of role author, and role name
 7661: 
 7662: =item *
 7663: 
 7664: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7665: 
 7666: =item *
 7667: 
 7668: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7669: 
 7670: =back
 7671: 
 7672: =head2 Course Infomation
 7673: 
 7674: =over 4
 7675: 
 7676: =item *
 7677: 
 7678: coursedescription($courseid) : returns a hash of information about the
 7679: specified course id, including all environment settings for the
 7680: course, the description of the course will be in the hash under the
 7681: key 'description'
 7682: 
 7683: =item *
 7684: 
 7685: resdata($name,$domain,$type,@which) : request for current parameter
 7686: setting for a specific $type, where $type is either 'course' or 'user',
 7687: @what should be a list of parameters to ask about. This routine caches
 7688: answers for 5 minutes.
 7689: 
 7690: =back
 7691: 
 7692: =head2 Course Modification
 7693: 
 7694: =over 4
 7695: 
 7696: =item *
 7697: 
 7698: writecoursepref($courseid,%prefs) : write preferences (environment
 7699: database) for a course
 7700: 
 7701: =item *
 7702: 
 7703: createcourse($udom,$description,$url) : make/modify course
 7704: 
 7705: =back
 7706: 
 7707: =head2 Resource Subroutines
 7708: 
 7709: =over 4
 7710: 
 7711: =item *
 7712: 
 7713: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7714: 
 7715: =item *
 7716: 
 7717: repcopy($filename) : subscribes to the requested file, and attempts to
 7718: replicate from the owning library server, Might return
 7719: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7720: 'bad_request', also attempts to grab the metadata for the
 7721: resource. Expects the local filesystem pathname
 7722: (/home/httpd/html/res/....)
 7723: 
 7724: =back
 7725: 
 7726: =head2 Resource Information
 7727: 
 7728: =over 4
 7729: 
 7730: =item *
 7731: 
 7732: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7733: a vairety of different possible values, $varname should be a request
 7734: string, and the other parameters can be used to specify who and what
 7735: one is asking about.
 7736: 
 7737: Possible values for $varname are environment.lastname (or other item
 7738: from the envirnment hash), user.name (or someother aspect about the
 7739: user), resource.0.maxtries (or some other part and parameter of a
 7740: resource)
 7741: 
 7742: =item *
 7743: 
 7744: directcondval($number) : get current value of a condition; reads from a state
 7745: string
 7746: 
 7747: =item *
 7748: 
 7749: condval($condidx) : value of condition index based on state
 7750: 
 7751: =item *
 7752: 
 7753: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7754: resource's metadata, $what should be either a specific key, or either
 7755: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7756: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7757: 
 7758: this function automatically caches all requests
 7759: 
 7760: =item *
 7761: 
 7762: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7763: network of library servers; returns file handle of where SQL and regex results
 7764: will be stored for query
 7765: 
 7766: =item *
 7767: 
 7768: symbread($filename) : return symbolic list entry (filename argument optional);
 7769: returns the data handle
 7770: 
 7771: =item *
 7772: 
 7773: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7774: a possible symb for the URL in $thisfn, and if is an encryypted
 7775: resource that the user accessed using /enc/ returns a 1 on success, 0
 7776: on failure, user must be in a course, as it assumes the existance of
 7777: the course initial hash, and uses $env('request.course.id'}
 7778: 
 7779: 
 7780: =item *
 7781: 
 7782: symbclean($symb) : removes versions numbers from a symb, returns the
 7783: cleaned symb
 7784: 
 7785: =item *
 7786: 
 7787: is_on_map($uri) : checks if the $uri is somewhere on the current
 7788: course map, user must be in a course for it to work.
 7789: 
 7790: =item *
 7791: 
 7792: numval($salt) : return random seed value (addend for rndseed)
 7793: 
 7794: =item *
 7795: 
 7796: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7797: a random seed, all arguments are optional, if they aren't sent it uses the
 7798: environment to derive them. Note: if symb isn't sent and it can't get one
 7799: from &symbread it will use the current time as its return value
 7800: 
 7801: =item *
 7802: 
 7803: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7804: unfakeable, receipt
 7805: 
 7806: =item *
 7807: 
 7808: receipt() : API to ireceipt working off of env values; given out to users
 7809: 
 7810: =item *
 7811: 
 7812: countacc($url) : count the number of accesses to a given URL
 7813: 
 7814: =item *
 7815: 
 7816: 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
 7817: 
 7818: =item *
 7819: 
 7820: 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)
 7821: 
 7822: =item *
 7823: 
 7824: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7825: 
 7826: =item *
 7827: 
 7828: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7829: forcing spreadsheet to reevaluate the resource scores next time.
 7830: 
 7831: =back
 7832: 
 7833: =head2 Storing/Retreiving Data
 7834: 
 7835: =over 4
 7836: 
 7837: =item *
 7838: 
 7839: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7840: for this url; hashref needs to be given and should be a \%hashname; the
 7841: remaining args aren't required and if they aren't passed or are '' they will
 7842: be derived from the env
 7843: 
 7844: =item *
 7845: 
 7846: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7847: uses critical subroutine
 7848: 
 7849: =item *
 7850: 
 7851: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7852: all args are optional
 7853: 
 7854: =item *
 7855: 
 7856: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7857: dumps the complete (or key matching regexp) namespace into a hash
 7858: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7859: normally &store()ed into
 7860: 
 7861: $range should be either an integer '100' (give me the first 100
 7862:                                            matching records)
 7863:               or be  two integers sperated by a - with no spaces
 7864:                  '30-50' (give me the 30th through the 50th matching
 7865:                           records)
 7866: 
 7867: 
 7868: =item *
 7869: 
 7870: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7871: replaces a &store() version of data with a replacement set of data
 7872: for a particular resource in a namespace passed in the $storehash hash 
 7873: reference
 7874: 
 7875: =item *
 7876: 
 7877: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7878: works very similar to store/cstore, but all data is stored in a
 7879: temporary location and can be reset using tmpreset, $storehash should
 7880: be a hash reference, returns nothing on success
 7881: 
 7882: =item *
 7883: 
 7884: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7885: similar to restore, but all data is stored in a temporary location and
 7886: can be reset using tmpreset. Returns a hash of values on success,
 7887: error string otherwise.
 7888: 
 7889: =item *
 7890: 
 7891: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7892: deltes all keys for $symb form the temporary storage hash.
 7893: 
 7894: =item *
 7895: 
 7896: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7897: reference filled in from namesp ($udom and $uname are optional)
 7898: 
 7899: =item *
 7900: 
 7901: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7902: namesp ($udom and $uname are optional)
 7903: 
 7904: =item *
 7905: 
 7906: dump($namespace,$udom,$uname,$regexp,$range) : 
 7907: dumps the complete (or key matching regexp) namespace into a hash
 7908: ($udom, $uname, $regexp, $range are optional)
 7909: 
 7910: $range should be either an integer '100' (give me the first 100
 7911:                                            matching records)
 7912:               or be  two integers sperated by a - with no spaces
 7913:                  '30-50' (give me the 30th through the 50th matching
 7914:                           records)
 7915: =item *
 7916: 
 7917: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7918: $store can be a scalar, an array reference, or if the amount to be 
 7919: incremented is > 1, a hash reference.
 7920: 
 7921: ($udom and $uname are optional)
 7922: 
 7923: =item *
 7924: 
 7925: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7926: ($udom and $uname are optional)
 7927: 
 7928: =item *
 7929: 
 7930: cput($namespace,$storehash,$udom,$uname) : critical put
 7931: ($udom and $uname are optional)
 7932: 
 7933: =item *
 7934: 
 7935: newput($namespace,$storehash,$udom,$uname) :
 7936: 
 7937: Attempts to store the items in the $storehash, but only if they don't
 7938: currently exist, if this succeeds you can be certain that you have 
 7939: successfully created a new key value pair in the $namespace db.
 7940: 
 7941: 
 7942: Args:
 7943:  $namespace: name of database to store values to
 7944:  $storehash: hashref to store to the db
 7945:  $udom: (optional) domain of user containing the db
 7946:  $uname: (optional) name of user caontaining the db
 7947: 
 7948: Returns:
 7949:  'ok' -> succeeded in storing all keys of $storehash
 7950:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 7951:                         least <key> already existed in the db (other
 7952:                         requested keys may also already exist)
 7953:  'error: <msg>' -> unable to tie the DB or other erorr occured
 7954:  'con_lost' -> unable to contact request server
 7955:  'refused' -> action was not allowed by remote machine
 7956: 
 7957: 
 7958: =item *
 7959: 
 7960: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7961: reference filled in from namesp (encrypts the return communication)
 7962: ($udom and $uname are optional)
 7963: 
 7964: =item *
 7965: 
 7966: log($udom,$name,$home,$message) : write to permanent log for user; use
 7967: critical subroutine
 7968: 
 7969: =back
 7970: 
 7971: =head2 Network Status Functions
 7972: 
 7973: =over 4
 7974: 
 7975: =item *
 7976: 
 7977: dirlist($uri) : return directory list based on URI
 7978: 
 7979: =item *
 7980: 
 7981: spareserver() : find server with least workload from spare.tab
 7982: 
 7983: =back
 7984: 
 7985: =head2 Apache Request
 7986: 
 7987: =over 4
 7988: 
 7989: =item *
 7990: 
 7991: ssi($url,%hash) : server side include, does a complete request cycle on url to
 7992: localhost, posts hash
 7993: 
 7994: =back
 7995: 
 7996: =head2 Data to String to Data
 7997: 
 7998: =over 4
 7999: 
 8000: =item *
 8001: 
 8002: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8003: and '&' separators, supports elements that are arrayrefs and hashrefs
 8004: 
 8005: =item *
 8006: 
 8007: hashref2str($hashref) : convert a hashref into a string complete with
 8008: escaping and '=' and '&' separators, supports elements that are
 8009: arrayrefs and hashrefs
 8010: 
 8011: =item *
 8012: 
 8013: arrayref2str($arrayref) : convert an arrayref into a string complete
 8014: with escaping and '&' separators, supports elements that are arrayrefs
 8015: and hashrefs
 8016: 
 8017: =item *
 8018: 
 8019: str2hash($string) : convert string to hash using unescaping and
 8020: splitting on '=' and '&', supports elements that are arrayrefs and
 8021: hashrefs
 8022: 
 8023: =item *
 8024: 
 8025: str2array($string) : convert string to hash using unescaping and
 8026: splitting on '&', supports elements that are arrayrefs and hashrefs
 8027: 
 8028: =back
 8029: 
 8030: =head2 Logging Routines
 8031: 
 8032: =over 4
 8033: 
 8034: These routines allow one to make log messages in the lonnet.log and
 8035: lonnet.perm logfiles.
 8036: 
 8037: =item *
 8038: 
 8039: logtouch() : make sure the logfile, lonnet.log, exists
 8040: 
 8041: =item *
 8042: 
 8043: logthis() : append message to the normal lonnet.log file, it gets
 8044: preiodically rolled over and deleted.
 8045: 
 8046: =item *
 8047: 
 8048: logperm() : append a permanent message to lonnet.perm.log, this log
 8049: file never gets deleted by any automated portion of the system, only
 8050: messages of critical importance should go in here.
 8051: 
 8052: =back
 8053: 
 8054: =head2 General File Helper Routines
 8055: 
 8056: =over 4
 8057: 
 8058: =item *
 8059: 
 8060: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8061: (a) files in /uploaded
 8062:   (i) If a local copy of the file exists - 
 8063:       compares modification date of local copy with last-modified date for 
 8064:       definitive version stored on home server for course. If local copy is 
 8065:       stale, requests a new version from the home server and stores it. 
 8066:       If the original has been removed from the home server, then local copy 
 8067:       is unlinked.
 8068:   (ii) If local copy does not exist -
 8069:       requests the file from the home server and stores it. 
 8070:   
 8071:   If $caller is 'uploadrep':  
 8072:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8073:     for request for files originally uploaded via DOCS. 
 8074:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8075:   
 8076:   Otherwise:
 8077:      This indicates a call from the content generation phase of the request.
 8078:      -  returns the entire contents of the file or -1.
 8079:      
 8080: (b) files in /res
 8081:    - returns the entire contents of a file or -1; 
 8082:    it properly subscribes to and replicates the file if neccessary.
 8083: 
 8084: 
 8085: =item *
 8086: 
 8087: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8088:                   reference
 8089: 
 8090: returns either a stat() list of data about the file or an empty list
 8091: if the file doesn't exist or couldn't find out about it (connection
 8092: problems or user unknown)
 8093: 
 8094: =item *
 8095: 
 8096: filelocation($dir,$file) : returns file system location of a file
 8097: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8098: directory that relative $file lookups are to looked in ($dir of /a/dir
 8099: and a file of ../bob will become /a/bob)
 8100: 
 8101: =item *
 8102: 
 8103: hreflocation($dir,$file) : returns file system location or a URL; same as
 8104: filelocation except for hrefs
 8105: 
 8106: =item *
 8107: 
 8108: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8109: 
 8110: =back
 8111: 
 8112: =head2 Usererfile file routines (/uploaded*)
 8113: 
 8114: =over 4
 8115: 
 8116: =item *
 8117: 
 8118: userfileupload(): main rotine for putting a file in a user or course's
 8119:                   filespace, arguments are,
 8120: 
 8121:  formname - required - this is the name of the element in $env where the
 8122:            filename, and the contents of the file to create/modifed exist
 8123:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8124:            contents of the file is located in $env{'form.'.$formname}
 8125:  coursedoc - if true, store the file in the course of the active role
 8126:              of the current user
 8127:  subdir - required - subdirectory to put the file in under ../userfiles/
 8128:          if undefined, it will be placed in "unknown"
 8129: 
 8130:  (This routine calls clean_filename() to remove any dangerous
 8131:  characters from the filename, and then calls finuserfileupload() to
 8132:  complete the transaction)
 8133: 
 8134:  returns either the url of the uploaded file (/uploaded/....) if successful
 8135:  and /adm/notfound.html if unsuccessful
 8136: 
 8137: =item *
 8138: 
 8139: clean_filename(): routine for cleaing a filename up for storage in
 8140:                  userfile space, argument is:
 8141: 
 8142:  filename - proposed filename
 8143: 
 8144: returns: the new clean filename
 8145: 
 8146: =item *
 8147: 
 8148: finishuserfileupload(): routine that creaes and sends the file to
 8149: userspace, probably shouldn't be called directly
 8150: 
 8151:   docuname: username or courseid of destination for the file
 8152:   docudom: domain of user/course of destination for the file
 8153:   formname: same as for userfileupload()
 8154:   fname: filename (inculding subdirectories) for the file
 8155: 
 8156:  returns either the url of the uploaded file (/uploaded/....) if successful
 8157:  and /adm/notfound.html if unsuccessful
 8158: 
 8159: =item *
 8160: 
 8161: renameuserfile(): renames an existing userfile to a new name
 8162: 
 8163:   Args:
 8164:    docuname: username or courseid of destination for the file
 8165:    docudom: domain of user/course of destination for the file
 8166:    old: current file name (including any subdirs under userfiles)
 8167:    new: desired file name (including any subdirs under userfiles)
 8168: 
 8169: =item *
 8170: 
 8171: mkdiruserfile(): creates a directory is a userfiles dir
 8172: 
 8173:   Args:
 8174:    docuname: username or courseid of destination for the file
 8175:    docudom: domain of user/course of destination for the file
 8176:    dir: dir to create (including any subdirs under userfiles)
 8177: 
 8178: =item *
 8179: 
 8180: removeuserfile(): removes a file that exists in userfiles
 8181: 
 8182:   Args:
 8183:    docuname: username or courseid of destination for the file
 8184:    docudom: domain of user/course of destination for the file
 8185:    fname: filname to delete (including any subdirs under userfiles)
 8186: 
 8187: =item *
 8188: 
 8189: removeuploadedurl(): convience function for removeuserfile()
 8190: 
 8191:   Args:
 8192:    url:  a full /uploaded/... url to delete
 8193: 
 8194: =item * 
 8195: 
 8196: get_portfile_permissions():
 8197:   Args:
 8198:     domain: domain of user or course contain the portfolio files
 8199:     user: name of user or num of course contain the portfolio files
 8200:   Returns:
 8201:     hashref of a dump of the proper file_permissions.db
 8202:    
 8203: 
 8204: =item * 
 8205: 
 8206: get_access_controls():
 8207: 
 8208: Args:
 8209:   current_permissions: the hash ref returned from get_portfile_permissions()
 8210:   group: (optional) the group you want the files associated with
 8211:   file: (optional) the file you want access info on
 8212: 
 8213: Returns:
 8214:     a hash (keys are file names) of hashes containing
 8215:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8216:         values are XML containing access control settings (see below) 
 8217: 
 8218: Internal notes:
 8219: 
 8220:  access controls are stored in file_permissions.db as key=value pairs.
 8221:     key -> path to file/file_name\0uniqueID:scope_end_start
 8222:         where scope -> public,guest,course,group,domains or users.
 8223:               end -> UNIX time for end of access (0 -> no end date)
 8224:               start -> UNIX time for start of access
 8225: 
 8226:     value -> XML description of access control
 8227:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8228:             <start></start>
 8229:             <end></end>
 8230: 
 8231:             <password></password>  for scope type = guest
 8232: 
 8233:             <domain></domain>     for scope type = course or group
 8234:             <number></number>
 8235:             <roles id="">
 8236:              <role></role>
 8237:              <access></access>
 8238:              <section></section>
 8239:              <group></group>
 8240:             </roles>
 8241: 
 8242:             <dom></dom>         for scope type = domains
 8243: 
 8244:             <users>             for scope type = users
 8245:              <user>
 8246:               <uname></uname>
 8247:               <udom></udom>
 8248:              </user>
 8249:             </users>
 8250:            </scope> 
 8251:               
 8252:  Access data is also aggregated for each file in an additional key=value pair:
 8253:  key -> path to file/file_name\0accesscontrol 
 8254:  value -> reference to hash
 8255:           hash contains key = value pairs
 8256:           where key = uniqueID:scope_end_start
 8257:                 value = UNIX time record was last updated
 8258: 
 8259:           Used to improve speed of look-ups of access controls for each file.  
 8260:  
 8261:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8262: 
 8263: modify_access_controls():
 8264: 
 8265: Modifies access controls for a portfolio file
 8266: Args
 8267: 1. file name
 8268: 2. reference to hash of required changes,
 8269: 3. domain
 8270: 4. username
 8271:   where domain,username are the domain of the portfolio owner 
 8272:   (either a user or a course) 
 8273: 
 8274: Returns:
 8275: 1. result of additions or updates ('ok' or 'error', with error message). 
 8276: 2. result of deletions ('ok' or 'error', with error message).
 8277: 3. reference to hash of any new or updated access controls.
 8278: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8279:    key = integer (inbound ID)
 8280:    value = uniqueID  
 8281: 
 8282: =back
 8283: 
 8284: =head2 HTTP Helper Routines
 8285: 
 8286: =over 4
 8287: 
 8288: =item *
 8289: 
 8290: escape() : unpack non-word characters into CGI-compatible hex codes
 8291: 
 8292: =item *
 8293: 
 8294: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8295: 
 8296: =back
 8297: 
 8298: =head1 PRIVATE SUBROUTINES
 8299: 
 8300: =head2 Underlying communication routines (Shouldn't call)
 8301: 
 8302: =over 4
 8303: 
 8304: =item *
 8305: 
 8306: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8307: 
 8308: =item *
 8309: 
 8310: reply() : uses subreply to send a message to remote machine, logs all failures
 8311: 
 8312: =item *
 8313: 
 8314: critical() : passes a critical message to another server; if cannot
 8315: get through then place message in connection buffer directory and
 8316: returns con_delayed, if incapable of saving message, returns
 8317: con_failed
 8318: 
 8319: =item *
 8320: 
 8321: reconlonc() : tries to reconnect lonc client processes.
 8322: 
 8323: =back
 8324: 
 8325: =head2 Resource Access Logging
 8326: 
 8327: =over 4
 8328: 
 8329: =item *
 8330: 
 8331: flushcourselogs() : flush (save) buffer logs and access logs
 8332: 
 8333: =item *
 8334: 
 8335: courselog($what) : save message for course in hash
 8336: 
 8337: =item *
 8338: 
 8339: courseacclog($what) : save message for course using &courselog().  Perform
 8340: special processing for specific resource types (problems, exams, quizzes, etc).
 8341: 
 8342: =item *
 8343: 
 8344: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8345: as a PerlChildExitHandler
 8346: 
 8347: =back
 8348: 
 8349: =head2 Other
 8350: 
 8351: =over 4
 8352: 
 8353: =item *
 8354: 
 8355: symblist($mapname,%newhash) : update symbolic storage links
 8356: 
 8357: =back
 8358: 
 8359: =cut

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