Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.681

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.681   ! raeburn     4: # $Id: lonnet.pm,v 1.680 2005/11/17 16:58:23 www Exp $
1.178     www         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: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.619     albertel   43:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit
                     44:    %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.8       www        48: use Apache::Constants qw(:common :http);
1.208     albertel   49: use HTML::LCParser;
1.637     raeburn    50: use HTML::Parser;
1.88      www        51: use Fcntl qw(:flock);
1.557     albertel   52: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   53: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   54: use Cache::Memcached;
1.676     albertel   55: use Digest::MD5;
                     56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
                     89: 
1.163     harris41   90: sub logtouch {
                     91:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel   92:     unless (-e "$execdir/logs/lonnet.log") {	
                     93: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41   94: 	close $fh;
                     95:     }
                     96:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     97:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     98: }
                     99: 
1.1       albertel  100: sub logthis {
                    101:     my $message=shift;
                    102:     my $execdir=$perlvar{'lonDaemons'};
                    103:     my $now=time;
                    104:     my $local=localtime($now);
1.448     albertel  105:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    106: 	print $fh "$local ($$): $message\n";
                    107: 	close($fh);
                    108:     }
1.1       albertel  109:     return 1;
                    110: }
                    111: 
                    112: sub logperm {
                    113:     my $message=shift;
                    114:     my $execdir=$perlvar{'lonDaemons'};
                    115:     my $now=time;
                    116:     my $local=localtime($now);
1.448     albertel  117:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    118: 	print $fh "$now:$message:$local\n";
                    119: 	close($fh);
                    120:     }
1.1       albertel  121:     return 1;
                    122: }
                    123: 
                    124: # -------------------------------------------------- Non-critical communication
                    125: sub subreply {
                    126:     my ($cmd,$server)=@_;
                    127:     my $peerfile="$perlvar{'lonSockDir'}/$server";
1.549     foxr      128:     #
                    129:     #  With loncnew process trimming, there's a timing hole between lonc server
                    130:     #  process exit and the master server picking up the listen on the AF_UNIX
                    131:     #  socket.  In that time interval, a lock file will exist:
                    132: 
                    133:     my $lockfile=$peerfile.".lock";
                    134:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    135: 	sleep(1);
                    136:     }
                    137:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      138:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      139:     #
1.550     foxr      140:     #   We'll give the connection a few tries before abandoning it.  If
                    141:     #   connection is not possible, we'll con_lost back to the client.
                    142:     #   
                    143:     my $client;
                    144:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    145: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    146: 				      Type    => SOCK_STREAM,
                    147: 				      Timeout => 10);
                    148: 	if($client) {
                    149: 	    last;		# Connected!
                    150: 	}
                    151: 	sleep(1);		# Try again later if failed connection.
                    152:     }
                    153:     my $answer;
                    154:     if ($client) {
                    155: 	print $client "$cmd\n";
                    156: 	$answer=<$client>;
                    157: 	if (!$answer) { $answer="con_lost"; }
                    158: 	chomp($answer);
                    159:     } else {
                    160: 	$answer = 'con_lost';	# Failed connection.
                    161:     }
1.1       albertel  162:     return $answer;
                    163: }
                    164: 
                    165: sub reply {
                    166:     my ($cmd,$server)=@_;
1.205     www       167:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  168:     my $answer=subreply($cmd,$server);
1.65      www       169:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  170:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       171:                 " $cmd to $server returned $answer</font>");
                    172:     }
1.1       albertel  173:     return $answer;
                    174: }
                    175: 
                    176: # ----------------------------------------------------------- Send USR1 to lonc
                    177: 
                    178: sub reconlonc {
                    179:     my $peerfile=shift;
                    180:     &logthis("Trying to reconnect for $peerfile");
                    181:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  182:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  183: 	my $loncpid=<$fh>;
                    184:         chomp($loncpid);
                    185:         if (kill 0 => $loncpid) {
                    186: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    187:             kill USR1 => $loncpid;
                    188:             sleep 1;
                    189:             if (-e "$peerfile") { return; }
                    190:             &logthis("$peerfile still not there, give it another try");
                    191:             sleep 5;
                    192:             if (-e "$peerfile") { return; }
1.12      www       193:             &logthis(
1.672     albertel  194:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  195:         } else {
1.12      www       196: 	    &logthis(
1.672     albertel  197:                "<font color=\"blue\">WARNING:".
1.12      www       198:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  199:         }
                    200:     } else {
1.672     albertel  201:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  202:     }
                    203: }
                    204: 
                    205: # ------------------------------------------------------ Critical communication
1.12      www       206: 
1.1       albertel  207: sub critical {
                    208:     my ($cmd,$server)=@_;
1.89      www       209:     unless ($hostname{$server}) {
1.672     albertel  210:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       211:                " Critical message to unknown server ($server)</font>");
                    212:         return 'no_such_host';
                    213:     }
1.1       albertel  214:     my $answer=reply($cmd,$server);
                    215:     if ($answer eq 'con_lost') {
                    216: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  217: 	my $answer=reply($cmd,$server);
1.1       albertel  218:         if ($answer eq 'con_lost') {
                    219:             my $now=time;
                    220:             my $middlename=$cmd;
1.5       www       221:             $middlename=substr($middlename,0,16);
1.1       albertel  222:             $middlename=~s/\W//g;
                    223:             my $dfilename=
1.305     www       224:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    225:             $dumpcount++;
1.1       albertel  226:             {
1.448     albertel  227: 		my $dfh;
                    228: 		if (open($dfh,">$dfilename")) {
                    229: 		    print $dfh "$cmd\n"; 
                    230: 		    close($dfh);
                    231: 		}
1.1       albertel  232:             }
                    233:             sleep 2;
                    234:             my $wcmd='';
                    235:             {
1.448     albertel  236: 		my $dfh;
                    237: 		if (open($dfh,"<$dfilename")) {
                    238: 		    $wcmd=<$dfh>; 
                    239: 		    close($dfh);
                    240: 		}
1.1       albertel  241:             }
                    242:             chomp($wcmd);
1.7       www       243:             if ($wcmd eq $cmd) {
1.672     albertel  244: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       245:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  246:                 &logperm("D:$server:$cmd");
                    247: 	        return 'con_delayed';
                    248:             } else {
1.672     albertel  249:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       250:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  251:                 &logperm("F:$server:$cmd");
                    252:                 return 'con_failed';
                    253:             }
                    254:         }
                    255:     }
                    256:     return $answer;
1.405     albertel  257: }
                    258: 
1.374     www       259: # ------------------------------------------- Transfer profile into environment
                    260: 
                    261: sub transfer_profile_to_env {
                    262:     my ($lonidsdir,$handle)=@_;
                    263:     my @profile;
                    264:     {
1.448     albertel  265: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       266: 	flock($idf,LOCK_SH);
                    267: 	@profile=<$idf>;
1.448     albertel  268: 	close($idf);
1.374     www       269:     }
                    270:     my $envi;
1.433     matthew   271:     my %Remove;
1.374     www       272:     for ($envi=0;$envi<=$#profile;$envi++) {
                    273: 	chomp($profile[$envi]);
                    274: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
1.619     albertel  275: 	$env{$envname} = $envvalue;
1.433     matthew   276:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    277:             if ($time < time-300) {
                    278:                 $Remove{$key}++;
                    279:             }
                    280:         }
                    281:     }
1.619     albertel  282:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   283:     foreach my $expired_key (keys(%Remove)) {
                    284:         &delenv($expired_key);
1.374     www       285:     }
1.1       albertel  286: }
                    287: 
1.5       www       288: # ---------------------------------------------------------- Append Environment
                    289: 
                    290: sub appenv {
1.6       www       291:     my %newenv=@_;
1.191     harris41  292:     foreach (keys %newenv) {
1.35      www       293: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
1.672     albertel  294:             &logthis("<font color=\"blue\">WARNING: ".
1.151     www       295:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    296:                 .'</font>');
1.35      www       297: 	    delete($newenv{$_});
                    298:         } else {
1.619     albertel  299:             $env{$_}=$newenv{$_};
1.35      www       300:         }
1.191     harris41  301:     }
1.95      www       302: 
                    303:     my $lockfh;
1.620     albertel  304:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  305: 	return 'error: '.$!;
1.95      www       306:     }
                    307:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  308:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       309:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  310:          close($lockfh);
1.95      www       311:          return 'error: '.$!;
                    312:     }
                    313: 
1.6       www       314:     my @oldenv;
                    315:     {
1.448     albertel  316: 	my $fh;
1.620     albertel  317: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  318: 	    return 'error: '.$!;
                    319: 	}
                    320: 	@oldenv=<$fh>;
                    321: 	close($fh);
1.6       www       322:     }
                    323:     for (my $i=0; $i<=$#oldenv; $i++) {
                    324:         chomp($oldenv[$i]);
1.9       www       325:         if ($oldenv[$i] ne '') {
1.448     albertel  326: 	    my ($name,$value)=split(/=/,$oldenv[$i]);
                    327: 	    unless (defined($newenv{$name})) {
                    328: 		$newenv{$name}=$value;
                    329: 	    }
1.9       www       330:         }
1.6       www       331:     }
                    332:     {
1.448     albertel  333: 	my $fh;
1.620     albertel  334: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  335: 	    return 'error';
                    336: 	}
                    337: 	my $newname;
                    338: 	foreach $newname (keys %newenv) {
                    339: 	    print $fh "$newname=$newenv{$newname}\n";
                    340: 	}
                    341: 	close($fh);
1.56      www       342:     }
1.448     albertel  343: 	
                    344:     close($lockfh);
1.56      www       345:     return 'ok';
                    346: }
                    347: # ----------------------------------------------------- Delete from Environment
                    348: 
                    349: sub delenv {
                    350:     my $delthis=shift;
                    351:     my %newenv=();
                    352:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  353:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       354:                 "Attempt to delete from environment ".$delthis);
                    355:         return 'error';
                    356:     }
                    357:     my @oldenv;
                    358:     {
1.448     albertel  359: 	my $fh;
1.620     albertel  360: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  361: 	    return 'error';
                    362: 	}
                    363: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  364: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  365: 		     'Could not obtain shared lock in delenv: '.$!);
                    366: 	    close($fh);
                    367: 	    return 'error: '.$!;
                    368: 	}
                    369: 	@oldenv=<$fh>;
                    370: 	close($fh);
1.56      www       371:     }
                    372:     {
1.448     albertel  373: 	my $fh;
1.620     albertel  374: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  375: 	    return 'error';
                    376: 	}
                    377: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  378: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  379: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    380: 	    close($fh);
                    381: 	    return 'error: '.$!;
                    382: 	}
                    383: 	foreach (@oldenv) {
1.473     matthew   384: 	    if ($_=~/^$delthis/) { 
                    385:                 my ($key,undef) = split('=',$_);
1.619     albertel  386:                 delete($env{$key});
1.473     matthew   387:             } else {
                    388:                 print $fh $_; 
                    389:             }
1.448     albertel  390: 	}
                    391: 	close($fh);
1.5       www       392:     }
                    393:     return 'ok';
1.369     albertel  394: }
                    395: 
                    396: # ------------------------------------------ Find out current server userload
                    397: # there is a copy in lond
                    398: sub userload {
                    399:     my $numusers=0;
                    400:     {
                    401: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    402: 	my $filename;
                    403: 	my $curtime=time;
                    404: 	while ($filename=readdir(LONIDS)) {
                    405: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  406: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  407: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  408: 	}
                    409: 	closedir(LONIDS);
                    410:     }
                    411:     my $userloadpercent=0;
                    412:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    413:     if ($maxuserload) {
1.371     albertel  414: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  415:     }
1.372     albertel  416:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  417:     return $userloadpercent;
1.283     www       418: }
                    419: 
                    420: # ------------------------------------------ Fight off request when overloaded
                    421: 
                    422: sub overloaderror {
                    423:     my ($r,$checkserver)=@_;
                    424:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    425:     my $loadavg;
                    426:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  427:        open(my $loadfile,'/proc/loadavg');
1.283     www       428:        $loadavg=<$loadfile>;
                    429:        $loadavg =~ s/\s.*//g;
1.285     matthew   430:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  431:        close($loadfile);
1.283     www       432:     } else {
                    433:        $loadavg=&reply('load',$checkserver);
                    434:     }
1.285     matthew   435:     my $overload=$loadavg-100;
1.283     www       436:     if ($overload>0) {
1.285     matthew   437: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       438:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       439:         return 413;
1.283     www       440:     }    
                    441:     return '';
1.5       www       442: }
1.1       albertel  443: 
                    444: # ------------------------------ Find server with least workload from spare.tab
1.11      www       445: 
1.1       albertel  446: sub spareserver {
1.670     albertel  447:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  448:     my $tryserver;
                    449:     my $spareserver='';
1.370     albertel  450:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    451:     my $lowestserver=$loadpercent > $userloadpercent?
                    452: 	             $loadpercent :  $userloadpercent;
1.670     albertel  453:     foreach $tryserver (keys(%spareid)) {
                    454: 	my $loadans=&reply('load',$tryserver);
                    455: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  456: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    457: 	    next; #didn't get a number from the server
                    458: 	}
                    459: 	my $answer;
                    460: 	if ($loadans =~ /\d/) {
                    461: 	    if ($userloadans =~ /\d/) {
                    462: 		#both are numbers, pick the bigger one
                    463: 		$answer=$loadans > $userloadans?
                    464: 		    $loadans :  $userloadans;
                    465: 	    } else {
                    466: 		$answer = $loadans;
                    467: 	    }
                    468: 	} else {
                    469: 	    $answer = $userloadans;
                    470: 	}
                    471: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  472: 	    if ($want_server_name) {
                    473: 		$spareserver=$tryserver;
                    474: 	    } else {
                    475: 		$spareserver="http://$hostname{$tryserver}";
                    476: 	    }
1.411     albertel  477: 	    $lowestserver=$answer;
                    478: 	}
1.370     albertel  479:     }
1.1       albertel  480:     return $spareserver;
1.202     matthew   481: }
                    482: 
                    483: # --------------------------------------------- Try to change a user's password
                    484: 
                    485: sub changepass {
                    486:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    487:     $currentpass = &escape($currentpass);
                    488:     $newpass     = &escape($newpass);
                    489:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    490: 		       $server);
                    491:     if (! $answer) {
                    492: 	&logthis("No reply on password change request to $server ".
                    493: 		 "by $uname in domain $udom.");
                    494:     } elsif ($answer =~ "^ok") {
                    495:         &logthis("$uname in $udom successfully changed their password ".
                    496: 		 "on $server.");
                    497:     } elsif ($answer =~ "^pwchange_failure") {
                    498: 	&logthis("$uname in $udom was unable to change their password ".
                    499: 		 "on $server.  The action was blocked by either lcpasswd ".
                    500: 		 "or pwchange");
                    501:     } elsif ($answer =~ "^non_authorized") {
                    502:         &logthis("$uname in $udom did not get their password correct when ".
                    503: 		 "attempting to change it on $server.");
                    504:     } elsif ($answer =~ "^auth_mode_error") {
                    505:         &logthis("$uname in $udom attempted to change their password despite ".
                    506: 		 "not being locally or internally authenticated on $server.");
                    507:     } elsif ($answer =~ "^unknown_user") {
                    508:         &logthis("$uname in $udom attempted to change their password ".
                    509: 		 "on $server but were unable to because $server is not ".
                    510: 		 "their home server.");
                    511:     } elsif ($answer =~ "^refused") {
                    512: 	&logthis("$server refused to change $uname in $udom password because ".
                    513: 		 "it was sent an unencrypted request to change the password.");
                    514:     }
                    515:     return $answer;
1.1       albertel  516: }
                    517: 
1.169     harris41  518: # ----------------------- Try to determine user's current authentication scheme
                    519: 
                    520: sub queryauthenticate {
                    521:     my ($uname,$udom)=@_;
1.456     albertel  522:     my $uhome=&homeserver($uname,$udom);
                    523:     if (!$uhome) {
                    524: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    525: 	return 'no_host';
                    526:     }
                    527:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    528:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    529: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  530:     }
1.456     albertel  531:     return $answer;
1.169     harris41  532: }
                    533: 
1.1       albertel  534: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       535: 
1.1       albertel  536: sub authenticate {
                    537:     my ($uname,$upass,$udom)=@_;
1.12      www       538:     $upass=escape($upass);
1.199     www       539:     $uname=~s/\W//g;
1.471     albertel  540:     my $uhome=&homeserver($uname,$udom);
                    541:     if (!$uhome) {
                    542: 	&logthis("User $uname at $udom is unknown in authenticate");
                    543: 	return 'no_host';
1.1       albertel  544:     }
1.471     albertel  545:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    546:     if ($answer eq 'authorized') {
                    547: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    548: 	return $uhome; 
                    549:     }
                    550:     if ($answer eq 'non_authorized') {
                    551: 	&logthis("User $uname at $udom rejected by $uhome");
                    552: 	return 'no_host'; 
1.9       www       553:     }
1.471     albertel  554:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  555:     return 'no_host';
                    556: }
                    557: 
                    558: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       559: 
1.599     albertel  560: my %homecache;
1.1       albertel  561: sub homeserver {
1.230     stredwic  562:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  563:     my $index="$uname:$udom";
1.426     albertel  564: 
1.599     albertel  565:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  566:     my $tryserver;
                    567:     foreach $tryserver (keys %libserv) {
1.230     stredwic  568:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  569: 		 exists($badServerCache{$tryserver}));
1.1       albertel  570: 	if ($hostdom{$tryserver} eq $udom) {
                    571:            my $answer=reply("home:$udom:$uname",$tryserver);
                    572:            if ($answer eq 'found') { 
1.599     albertel  573: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  574:            } elsif ($answer eq 'no_host') {
                    575: 	       $badServerCache{$tryserver}=1;
1.221     matthew   576:            }
1.1       albertel  577:        }
                    578:     }    
                    579:     return 'no_host';
1.70      www       580: }
                    581: 
                    582: # ------------------------------------- Find the usernames behind a list of IDs
                    583: 
                    584: sub idget {
                    585:     my ($udom,@ids)=@_;
                    586:     my %returnhash=();
                    587:     
                    588:     my $tryserver;
                    589:     foreach $tryserver (keys %libserv) {
                    590:        if ($hostdom{$tryserver} eq $udom) {
                    591: 	  my $idlist=join('&',@ids);
                    592:           $idlist=~tr/A-Z/a-z/; 
                    593: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    594:           my @answer=();
1.76      www       595:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       596: 	      @answer=split(/\&/,$reply);
                    597:           }                    ;
                    598:           my $i;
                    599:           for ($i=0;$i<=$#ids;$i++) {
                    600:               if ($answer[$i]) {
                    601: 		  $returnhash{$ids[$i]}=$answer[$i];
                    602:               } 
                    603:           }
                    604:        }
                    605:     }    
                    606:     return %returnhash;
                    607: }
                    608: 
                    609: # ------------------------------------- Find the IDs behind a list of usernames
                    610: 
                    611: sub idrget {
                    612:     my ($udom,@unames)=@_;
                    613:     my %returnhash=();
1.191     harris41  614:     foreach (@unames) {
1.70      www       615:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  616:     }
1.70      www       617:     return %returnhash;
                    618: }
                    619: 
                    620: # ------------------------------- Store away a list of names and associated IDs
                    621: 
                    622: sub idput {
                    623:     my ($udom,%ids)=@_;
                    624:     my %servers=();
1.191     harris41  625:     foreach (keys %ids) {
1.487     albertel  626: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       627:         my $uhom=&homeserver($_,$udom);
                    628:         if ($uhom ne 'no_host') {
                    629:             my $id=&escape($ids{$_});
                    630:             $id=~tr/A-Z/a-z/;
                    631:             my $unam=&escape($_);
                    632: 	    if ($servers{$uhom}) {
                    633: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    634:             } else {
                    635:                 $servers{$uhom}=$id.'='.$unam;
                    636:             }
                    637:         }
1.191     harris41  638:     }
                    639:     foreach (keys %servers) {
1.70      www       640:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  641:     }
1.344     www       642: }
                    643: 
                    644: # --------------------------------------------------- Assign a key to a student
                    645: 
                    646: sub assign_access_key {
1.364     www       647: #
                    648: # a valid key looks like uname:udom#comments
                    649: # comments are being appended
                    650: #
1.498     www       651:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    652:     $kdom=
1.620     albertel  653:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       654:     $knum=
1.620     albertel  655:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       656:     $cdom=
1.620     albertel  657:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       658:     $cnum=
1.620     albertel  659:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    660:     $udom=$env{'user.name'} unless (defined($udom));
                    661:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       662:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       663:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  664:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       665:                                                   # assigned to this person
                    666:                                                   # - this should not happen,
1.345     www       667:                                                   # unless something went wrong
                    668:                                                   # the first time around
                    669: # ready to assign
1.364     www       670:         $logentry=$1.'; '.$logentry;
1.496     www       671:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       672:                                                  $kdom,$knum) eq 'ok') {
1.345     www       673: # key now belongs to user
1.346     www       674: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       675:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    676:                 &appenv('environment.'.$envkey => $ckey);
                    677:                 return 'ok';
                    678:             } else {
                    679:                 return 
                    680:   'error: Count not permanently assign key, will need to be re-entered later.';
                    681: 	    }
                    682:         } else {
                    683:             return 'error: Could not assign key, try again later.';
                    684:         }
1.364     www       685:     } elsif (!$existing{$ckey}) {
1.345     www       686: # the key does not exist
                    687: 	return 'error: The key does not exist';
                    688:     } else {
                    689: # the key is somebody else's
                    690: 	return 'error: The key is already in use';
                    691:     }
1.344     www       692: }
                    693: 
1.364     www       694: # ------------------------------------------ put an additional comment on a key
                    695: 
                    696: sub comment_access_key {
                    697: #
                    698: # a valid key looks like uname:udom#comments
                    699: # comments are being appended
                    700: #
                    701:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    702:     $cdom=
1.620     albertel  703:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       704:     $cnum=
1.620     albertel  705:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       706:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    707:     if ($existing{$ckey}) {
                    708:         $existing{$ckey}.='; '.$logentry;
                    709: # ready to assign
1.367     www       710:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       711:                                                  $cdom,$cnum) eq 'ok') {
                    712: 	    return 'ok';
                    713:         } else {
                    714: 	    return 'error: Count not store comment.';
                    715:         }
                    716:     } else {
                    717: # the key does not exist
                    718: 	return 'error: The key does not exist';
                    719:     }
                    720: }
                    721: 
1.344     www       722: # ------------------------------------------------------ Generate a set of keys
                    723: 
                    724: sub generate_access_keys {
1.364     www       725:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       726:     $cdom=
1.620     albertel  727:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       728:     $cnum=
1.620     albertel  729:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       730:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       731:     unless (($cdom) && ($cnum)) { return 0; }
                    732:     if ($number>10000) { return 0; }
                    733:     sleep(2); # make sure don't get same seed twice
                    734:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    735:     my $total=0;
                    736:     for (my $i=1;$i<=$number;$i++) {
                    737:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    738:                   sprintf("%lx",int(100000*rand)).'-'.
                    739:                   sprintf("%lx",int(100000*rand));
                    740:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    741:        $newkey=~s/0/h/g; # and also 0 and O
                    742:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    743:        if ($existing{$newkey}) {
                    744:            $i--;
                    745:        } else {
1.364     www       746: 	  if (&put('accesskeys',
                    747:               { $newkey => '# generated '.localtime().
1.620     albertel  748:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       749:                            '; '.$logentry },
                    750: 		   $cdom,$cnum) eq 'ok') {
1.344     www       751:               $total++;
                    752: 	  }
                    753:        }
                    754:     }
1.620     albertel  755:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       756:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    757:     return $total;
                    758: }
                    759: 
                    760: # ------------------------------------------------------- Validate an accesskey
                    761: 
                    762: sub validate_access_key {
                    763:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    764:     $cdom=
1.620     albertel  765:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       766:     $cnum=
1.620     albertel  767:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    768:     $udom=$env{'user.domain'} unless (defined($udom));
                    769:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       770:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  771:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       772: }
                    773: 
                    774: # ------------------------------------- Find the section of student in a course
1.652     albertel  775: sub devalidate_getsection_cache {
                    776:     my ($udom,$unam,$courseid)=@_;
                    777:     $courseid=~s/\_/\//g;
                    778:     $courseid=~s/^(\w)/\/$1/;
                    779:     my $hashid="$udom:$unam:$courseid";
                    780:     &devalidate_cache_new('getsection',$hashid);
                    781: }
1.298     matthew   782: 
                    783: sub getsection {
                    784:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  785:     my $cachetime=1800;
1.298     matthew   786:     $courseid=~s/\_/\//g;
                    787:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  788: 
                    789:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  790:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  791:     if (defined($cached)) { return $result; }
                    792: 
1.298     matthew   793:     my %Pending; 
                    794:     my %Expired;
                    795:     #
                    796:     # Each role can either have not started yet (pending), be active, 
                    797:     #    or have expired.
                    798:     #
                    799:     # If there is an active role, we are done.
                    800:     #
                    801:     # If there is more than one role which has not started yet, 
                    802:     #     choose the one which will start sooner
                    803:     # If there is one role which has not started yet, return it.
                    804:     #
                    805:     # If there is more than one expired role, choose the one which ended last.
                    806:     # If there is a role which has expired, return it.
                    807:     #
                    808:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    809:                         &homeserver($unam,$udom)))) {
                    810:         my ($key,$value)=split(/\=/,$_);
                    811:         $key=&unescape($key);
1.479     albertel  812:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   813:         my $section=$1;
                    814:         if ($key eq $courseid.'_st') { $section=''; }
                    815:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    816:         my $now=time;
1.548     albertel  817:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   818:             $Expired{$end}=$section;
                    819:             next;
                    820:         }
1.548     albertel  821:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   822:             $Pending{$start}=$section;
                    823:             next;
                    824:         }
1.599     albertel  825:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   826:     }
                    827:     #
                    828:     # Presumedly there will be few matching roles from the above
                    829:     # loop and the sorting time will be negligible.
                    830:     if (scalar(keys(%Pending))) {
                    831:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  832:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   833:     } 
                    834:     if (scalar(keys(%Expired))) {
                    835:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    836:         my $time = pop(@sorted);
1.599     albertel  837:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   838:     }
1.599     albertel  839:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   840: }
1.70      www       841: 
1.599     albertel  842: sub save_cache {
1.628     albertel  843:     my ($r)=@_;
                    844:     if (! $r->is_initial_req()) { return DECLINED; }
1.599     albertel  845:     &purge_remembered();
1.620     albertel  846:     undef(%env);
1.628     albertel  847:     return OK;
1.599     albertel  848: }
1.452     albertel  849: 
1.599     albertel  850: my $to_remember=-1;
                    851: my %remembered;
                    852: my %accessed;
                    853: my $kicks=0;
                    854: my $hits=0;
                    855: sub devalidate_cache_new {
                    856:     my ($name,$id,$debug) = @_;
                    857:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    858:     $id=&escape($name.':'.$id);
                    859:     $memcache->delete($id);
                    860:     delete($remembered{$id});
                    861:     delete($accessed{$id});
                    862: }
                    863: 
                    864: sub is_cached_new {
                    865:     my ($name,$id,$debug) = @_;
                    866:     $id=&escape($name.':'.$id);
                    867:     if (exists($remembered{$id})) {
                    868: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    869: 	$accessed{$id}=[&gettimeofday()];
                    870: 	$hits++;
                    871: 	return ($remembered{$id},1);
                    872:     }
                    873:     my $value = $memcache->get($id);
                    874:     if (!(defined($value))) {
                    875: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  876: 	return (undef,undef);
1.416     albertel  877:     }
1.599     albertel  878:     if ($value eq '__undef__') {
                    879: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    880: 	$value=undef;
                    881:     }
                    882:     &make_room($id,$value,$debug);
                    883:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    884:     return ($value,1);
                    885: }
                    886: 
                    887: sub do_cache_new {
                    888:     my ($name,$id,$value,$time,$debug) = @_;
                    889:     $id=&escape($name.':'.$id);
                    890:     my $setvalue=$value;
                    891:     if (!defined($setvalue)) {
                    892: 	$setvalue='__undef__';
                    893:     }
1.623     albertel  894:     if (!defined($time) ) {
                    895: 	$time=600;
                    896:     }
1.599     albertel  897:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  898:     $memcache->set($id,$setvalue,$time);
                    899:     # need to make a copy of $value
                    900:     #&make_room($id,$value,$debug);
1.599     albertel  901:     return $value;
                    902: }
                    903: 
                    904: sub make_room {
                    905:     my ($id,$value,$debug)=@_;
                    906:     $remembered{$id}=$value;
                    907:     if ($to_remember<0) { return; }
                    908:     $accessed{$id}=[&gettimeofday()];
                    909:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    910:     my $to_kick;
                    911:     my $max_time=0;
                    912:     foreach my $other (keys(%accessed)) {
                    913: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    914: 	    $to_kick=$other;
                    915: 	    $max_time=&tv_interval($accessed{$other});
                    916: 	}
                    917:     }
                    918:     delete($remembered{$to_kick});
                    919:     delete($accessed{$to_kick});
                    920:     $kicks++;
                    921:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  922:     return;
                    923: }
                    924: 
1.599     albertel  925: sub purge_remembered {
1.604     albertel  926:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    927:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  928:     undef(%remembered);
                    929:     undef(%accessed);
1.428     albertel  930: }
1.70      www       931: # ------------------------------------- Read an entry from a user's environment
                    932: 
                    933: sub userenvironment {
                    934:     my ($udom,$unam,@what)=@_;
                    935:     my %returnhash=();
                    936:     my @answer=split(/\&/,
                    937:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    938:                       &homeserver($unam,$udom)));
                    939:     my $i;
                    940:     for ($i=0;$i<=$#what;$i++) {
                    941: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    942:     }
                    943:     return %returnhash;
1.1       albertel  944: }
                    945: 
1.617     albertel  946: # ---------------------------------------------------------- Get a studentphoto
                    947: sub studentphoto {
                    948:     my ($udom,$unam,$ext) = @_;
                    949:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                    950:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext",$home);
                    951:     my $url="/uploaded/$udom/$unam/internal/studentphoto.".$ext;
                    952:     if ($ret ne 'ok') {
                    953: 	return '/adm/lonKaputt/lonlogo_broken.gif';
                    954:     }
                    955:     my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                    956:     return $tokenurl;
                    957: }
                    958: 
1.263     www       959: # -------------------------------------------------------------------- New chat
                    960: 
                    961: sub chatsend {
                    962:     my ($newentry,$anon)=@_;
1.620     albertel  963:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                    964:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                    965:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www       966:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel  967: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.263     www       968: 		   &escape($newentry)),$chome);
1.292     www       969: }
                    970: 
                    971: # ------------------------------------------ Find current version of a resource
                    972: 
                    973: sub getversion {
                    974:     my $fname=&clutter(shift);
                    975:     unless ($fname=~/^\/res\//) { return -1; }
                    976:     return &currentversion(&filelocation('',$fname));
                    977: }
                    978: 
                    979: sub currentversion {
                    980:     my $fname=shift;
1.599     albertel  981:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www       982:     if (defined($cached)) { return $result; }
1.292     www       983:     my $author=$fname;
                    984:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    985:     my ($udom,$uname)=split(/\//,$author);
                    986:     my $home=homeserver($uname,$udom);
                    987:     if ($home eq 'no_host') { 
                    988:         return -1; 
                    989:     }
                    990:     my $answer=reply("currentversion:$fname",$home);
                    991:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    992: 	return -1;
                    993:     }
1.599     albertel  994:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www       995: }
                    996: 
1.1       albertel  997: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       998: 
1.1       albertel  999: sub subscribe {
                   1000:     my $fname=shift;
1.312     www      1001:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1002:     $fname=~s/[\n\r]//g;
1.1       albertel 1003:     my $author=$fname;
                   1004:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1005:     my ($udom,$uname)=split(/\//,$author);
                   1006:     my $home=homeserver($uname,$udom);
1.335     albertel 1007:     if ($home eq 'no_host') {
                   1008:         return 'not_found';
1.1       albertel 1009:     }
                   1010:     my $answer=reply("sub:$fname",$home);
1.64      www      1011:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1012: 	$answer.=' by '.$home;
                   1013:     }
1.1       albertel 1014:     return $answer;
                   1015: }
                   1016:     
1.8       www      1017: # -------------------------------------------------------------- Replicate file
                   1018: 
                   1019: sub repcopy {
                   1020:     my $filename=shift;
1.23      www      1021:     $filename=~s/\/+/\//g;
1.607     raeburn  1022:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1023:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1024:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1025: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1026: 	return &repcopy_userfile($filename);
                   1027:     }
1.532     albertel 1028:     $filename=~s/[\n\r]//g;
1.8       www      1029:     my $transname="$filename.in.transfer";
1.607     raeburn  1030:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1031:     my $remoteurl=subscribe($filename);
1.64      www      1032:     if ($remoteurl =~ /^con_lost by/) {
                   1033: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1034:            return 'unavailable';
1.8       www      1035:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1036: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1037: 	   return 'not_found';
1.64      www      1038:     } elsif ($remoteurl =~ /^rejected by/) {
                   1039: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1040:            return 'forbidden';
1.20      www      1041:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1042:            return 'ok';
1.8       www      1043:     } else {
1.290     www      1044:         my $author=$filename;
                   1045:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1046:         my ($udom,$uname)=split(/\//,$author);
                   1047:         my $home=homeserver($uname,$udom);
                   1048:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1049:            my @parts=split(/\//,$filename);
                   1050:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1051:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1052:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1053: 	       return 'bad_request';
1.8       www      1054:            }
                   1055:            my $count;
                   1056:            for ($count=5;$count<$#parts;$count++) {
                   1057:                $path.="/$parts[$count]";
                   1058:                if ((-e $path)!=1) {
                   1059: 		   mkdir($path,0777);
                   1060:                }
                   1061:            }
                   1062:            my $ua=new LWP::UserAgent;
                   1063:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1064:            my $response=$ua->request($request,$transname);
                   1065:            if ($response->is_error()) {
                   1066: 	       unlink($transname);
                   1067:                my $message=$response->status_line;
1.672     albertel 1068:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1069:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1070:                return 'unavailable';
1.8       www      1071:            } else {
1.16      www      1072: 	       if ($remoteurl!~/\.meta$/) {
                   1073:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1074:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1075:                   if ($mresponse->is_error()) {
                   1076: 		      unlink($filename.'.meta');
                   1077:                       &logthis(
1.672     albertel 1078:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1079:                   }
                   1080: 	       }
1.8       www      1081:                rename($transname,$filename);
1.607     raeburn  1082:                return 'ok';
1.8       www      1083:            }
1.290     www      1084:        }
1.8       www      1085:     }
1.330     www      1086: }
                   1087: 
                   1088: # ------------------------------------------------ Get server side include body
                   1089: sub ssi_body {
1.381     albertel 1090:     my ($filelink,%form)=@_;
1.606     matthew  1091:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1092:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1093:     }
1.330     www      1094:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1095:                                      &ssi($filelink,%form));
1.565     albertel 1096:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1097:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1098:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1099:     return $output;
1.8       www      1100: }
                   1101: 
1.15      www      1102: # --------------------------------------------------------- Server Side Include
                   1103: 
                   1104: sub ssi {
                   1105: 
1.23      www      1106:     my ($fn,%form)=@_;
1.15      www      1107: 
                   1108:     my $ua=new LWP::UserAgent;
1.23      www      1109:     
                   1110:     my $request;
                   1111:     
                   1112:     if (%form) {
                   1113:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1114:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1115:     } else {
                   1116:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1117:     }
                   1118: 
1.15      www      1119:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1120:     my $response=$ua->request($request);
                   1121: 
1.324     www      1122:     return $response->content;
                   1123: }
                   1124: 
                   1125: sub externalssi {
                   1126:     my ($url)=@_;
                   1127:     my $ua=new LWP::UserAgent;
                   1128:     my $request=new HTTP::Request('GET',$url);
                   1129:     my $response=$ua->request($request);
1.15      www      1130:     return $response->content;
                   1131: }
1.254     www      1132: 
1.492     albertel 1133: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1134: 
                   1135: sub allowuploaded {
                   1136:     my ($srcurl,$url)=@_;
                   1137:     $url=&clutter(&declutter($url));
                   1138:     my $dir=$url;
                   1139:     $dir=~s/\/[^\/]+$//;
                   1140:     my %httpref=();
                   1141:     my $httpurl=&hreflocation('',$url);
                   1142:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1143:     &Apache::lonnet::appenv(%httpref);
1.254     www      1144: }
1.477     raeburn  1145: 
1.478     albertel 1146: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1147: # input: action, courseID, current domain, intended
1.637     raeburn  1148: #        path to file, source of file, instruction to parse file for objects,
                   1149: #        ref to hash for embedded objects,
                   1150: #        ref to hash for codebase of java objects.
                   1151: #
1.485     raeburn  1152: # output: url to file (if action was uploaddoc), 
                   1153: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1154: #
1.478     albertel 1155: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1156: # course.
1.477     raeburn  1157: #
1.478     albertel 1158: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1159: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1160: #          course's home server.
1.477     raeburn  1161: #
1.478     albertel 1162: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1163: #          be copied from $source (current location) to 
                   1164: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1165: #         and will then be copied to
                   1166: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1167: #         course's home server.
1.485     raeburn  1168: #
1.481     raeburn  1169: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1170: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1171: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1172: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1173: #         in course's home server.
1.637     raeburn  1174: #
1.477     raeburn  1175: 
                   1176: sub process_coursefile {
1.638     albertel 1177:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1178:     my $fetchresult;
1.638     albertel 1179:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1180:     if ($action eq 'propagate') {
1.638     albertel 1181:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1182: 			     $home);
1.481     raeburn  1183:     } else {
1.477     raeburn  1184:         my $fpath = '';
                   1185:         my $fname = $file;
1.478     albertel 1186:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1187:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1188:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1189:         if ($action eq 'copy') {
                   1190:             if ($source eq '') {
                   1191:                 $fetchresult = 'no source file';
                   1192:                 return $fetchresult;
                   1193:             } else {
                   1194:                 my $destination = $filepath.'/'.$fname;
                   1195:                 rename($source,$destination);
                   1196:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1197:                                  $home);
1.481     raeburn  1198:             }
                   1199:         } elsif ($action eq 'uploaddoc') {
                   1200:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1201:             print $fh $env{'form.'.$source};
1.481     raeburn  1202:             close($fh);
1.637     raeburn  1203:             if ($parser eq 'parse') {
                   1204:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1205:                 unless ($parse_result eq 'ok') {
                   1206:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1207:                 }
                   1208:             }
1.477     raeburn  1209:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1210:                                  $home);
1.481     raeburn  1211:             if ($fetchresult eq 'ok') {
                   1212:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1213:             } else {
                   1214:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1215:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1216:                 return '/adm/notfound.html';
                   1217:             }
1.477     raeburn  1218:         }
                   1219:     }
1.485     raeburn  1220:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1221:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1222:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1223:     }
                   1224:     return $fetchresult;
                   1225: }
                   1226: 
1.637     raeburn  1227: sub build_filepath {
                   1228:     my ($fpath) = @_;
                   1229:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1230:     unless ($fpath eq '') {
                   1231:         my @parts=split('/',$fpath);
                   1232:         foreach my $part (@parts) {
                   1233:             $filepath.= '/'.$part;
                   1234:             if ((-e $filepath)!=1) {
                   1235:                 mkdir($filepath,0777);
                   1236:             }
                   1237:         }
                   1238:     }
                   1239:     return $filepath;
                   1240: }
                   1241: 
                   1242: sub store_edited_file {
1.638     albertel 1243:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1244:     my $file = $primary_url;
                   1245:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1246:     my $fpath = '';
                   1247:     my $fname = $file;
                   1248:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1249:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1250:     my $filepath = &build_filepath($fpath);
                   1251:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1252:     print $fh $content;
                   1253:     close($fh);
1.638     albertel 1254:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1255:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1256: 			  $home);
1.637     raeburn  1257:     if ($$fetchresult eq 'ok') {
                   1258:         return '/uploaded/'.$fpath.'/'.$fname;
                   1259:     } else {
1.638     albertel 1260:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1261: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1262:         return '/adm/notfound.html';
                   1263:     }
                   1264: }
                   1265: 
1.531     albertel 1266: sub clean_filename {
                   1267:     my ($fname)=@_;
1.315     www      1268: # Replace Windows backslashes by forward slashes
1.257     www      1269:     $fname=~s/\\/\//g;
1.315     www      1270: # Get rid of everything but the actual filename
1.257     www      1271:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1272: # Replace spaces by underscores
                   1273:     $fname=~s/\s+/\_/g;
                   1274: # Replace all other weird characters by nothing
1.317     www      1275:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1276: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1277: # numbers
                   1278:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1279:     return $fname;
                   1280: }
                   1281: 
1.608     albertel 1282: # --------------- Take an uploaded file and put it into the userfiles directory
                   1283: # input: name of form element, coursedoc=1 means this is for the course
                   1284: # output: url of file in userspace
                   1285: 
                   1286: 
1.531     albertel 1287: sub userfileupload {
1.637     raeburn  1288:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase)=@_;
1.531     albertel 1289:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1290:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1291:     $fname=&clean_filename($fname);
1.315     www      1292: # See if there is anything left
1.257     www      1293:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1294:     chop($env{'form.'.$formname});
1.523     raeburn  1295:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1296:         my $now = time;
                   1297:         my $filepath = 'tmp/helprequests/'.$now;
                   1298:         my @parts=split(/\//,$filepath);
                   1299:         my $fullpath = $perlvar{'lonDaemons'};
                   1300:         for (my $i=0;$i<@parts;$i++) {
                   1301:             $fullpath .= '/'.$parts[$i];
                   1302:             if ((-e $fullpath)!=1) {
                   1303:                 mkdir($fullpath,0777);
                   1304:             }
                   1305:         }
                   1306:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1307:         print $fh $env{'form.'.$formname};
1.523     raeburn  1308:         close($fh);
                   1309:         return $fullpath.'/'.$fname; 
                   1310:     }
1.258     www      1311: # Create the directory if not present
1.493     albertel 1312:     $fname="$subdir/$fname";
1.259     www      1313:     if ($coursedoc) {
1.638     albertel 1314: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1315: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1316:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1317:             return &finishuserfileupload($docuname,$docudom,
                   1318: 					 $formname,$fname,$parser,$allfiles,
                   1319: 					 $codebase);
1.481     raeburn  1320:         } else {
1.620     albertel 1321:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1322:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1323: 				       $fname,$formname,$parser,
                   1324: 				       $allfiles,$codebase);
1.481     raeburn  1325:         }
1.259     www      1326:     } else {
1.638     albertel 1327:         my $docuname=$env{'user.name'};
                   1328:         my $docudom=$env{'user.domain'};
                   1329: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1330: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1331:     }
1.271     www      1332: }
                   1333: 
                   1334: sub finishuserfileupload {
1.638     albertel 1335:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1336:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1337:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1338:     my ($fnamepath,$file);
                   1339:     $file=$fname;
                   1340:     if ($fname=~m|/|) {
                   1341:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1342: 	$path.=$fnamepath.'/';
                   1343:     }
1.259     www      1344:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1345:     my $count;
                   1346:     for ($count=4;$count<=$#parts;$count++) {
                   1347:         $filepath.="/$parts[$count]";
                   1348:         if ((-e $filepath)!=1) {
                   1349: 	    mkdir($filepath,0777);
                   1350:         }
                   1351:     }
                   1352: # Save the file
                   1353:     {
1.570     albertel 1354: 	open(FH,'>'.$filepath.'/'.$file);
1.620     albertel 1355: 	print FH $env{'form.'.$formname};
1.570     albertel 1356: 	close(FH);
1.258     www      1357:     }
1.637     raeburn  1358:     if ($parser eq 'parse') {
1.638     albertel 1359:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1360: 						   $codebase);
1.637     raeburn  1361:         unless ($parse_result eq 'ok') {
1.638     albertel 1362:             &logthis('Failed to parse '.$filepath.$file.
                   1363: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1364:         }
                   1365:     }
1.259     www      1366: # Notify homeserver to grep it
                   1367: #
1.638     albertel 1368:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1369:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1370:     if ($fetchresult eq 'ok') {
1.259     www      1371: #
1.258     www      1372: # Return the URL to it
1.494     albertel 1373:         return '/uploaded/'.$path.$file;
1.263     www      1374:     } else {
1.494     albertel 1375:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1376: 		 ': '.$fetchresult);
1.263     www      1377:         return '/adm/notfound.html';
                   1378:     }    
1.493     albertel 1379: }
                   1380: 
1.637     raeburn  1381: sub extract_embedded_items {
1.648     raeburn  1382:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1383:     my @state = ();
                   1384:     my %javafiles = (
                   1385:                       codebase => '',
                   1386:                       code => '',
                   1387:                       archive => ''
                   1388:                     );
                   1389:     my %mediafiles = (
                   1390:                       src => '',
                   1391:                       movie => '',
                   1392:                      );
1.648     raeburn  1393:     my $p;
                   1394:     if ($content) {
                   1395:         $p = HTML::LCParser->new($content);
                   1396:     } else {
                   1397:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1398:     }
1.641     albertel 1399:     while (my $t=$p->get_token()) {
1.640     albertel 1400: 	if ($t->[0] eq 'S') {
                   1401: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1402: 	    push (@state, $tagname);
1.648     raeburn  1403:             if (lc($tagname) eq 'allow') {
                   1404:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1405:             }
1.640     albertel 1406: 	    if (lc($tagname) eq 'img') {
                   1407: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1408: 	    }
1.645     raeburn  1409:             if (lc($tagname) eq 'script') {
                   1410:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1411:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1412:                 } else {
                   1413:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1414:                 }
                   1415:             }
                   1416:             if (lc($tagname) eq 'link') {
                   1417:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1418:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1419:                 }
                   1420:             }
1.640     albertel 1421: 	    if (lc($tagname) eq 'object' ||
                   1422: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1423: 		foreach my $item (keys(%javafiles)) {
                   1424: 		    $javafiles{$item} = '';
                   1425: 		}
                   1426: 	    }
                   1427: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1428: 		my $name = lc($attr->{'name'});
                   1429: 		foreach my $item (keys(%javafiles)) {
                   1430: 		    if ($name eq $item) {
                   1431: 			$javafiles{$item} = $attr->{'value'};
                   1432: 			last;
                   1433: 		    }
                   1434: 		}
                   1435: 		foreach my $item (keys(%mediafiles)) {
                   1436: 		    if ($name eq $item) {
                   1437: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1438: 			last;
                   1439: 		    }
                   1440: 		}
                   1441: 	    }
                   1442: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1443: 		foreach my $item (keys(%javafiles)) {
                   1444: 		    if ($attr->{$item}) {
                   1445: 			$javafiles{$item} = $attr->{$item};
                   1446: 			last;
                   1447: 		    }
                   1448: 		}
                   1449: 		foreach my $item (keys(%mediafiles)) {
                   1450: 		    if ($attr->{$item}) {
                   1451: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1452: 			last;
                   1453: 		    }
                   1454: 		}
                   1455: 	    }
                   1456: 	} elsif ($t->[0] eq 'E') {
                   1457: 	    my ($tagname) = ($t->[1]);
                   1458: 	    if ($javafiles{'codebase'} ne '') {
                   1459: 		$javafiles{'codebase'} .= '/';
                   1460: 	    }  
                   1461: 	    if (lc($tagname) eq 'applet' ||
                   1462: 		lc($tagname) eq 'object' ||
                   1463: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1464: 		) {
                   1465: 		foreach my $item (keys(%javafiles)) {
                   1466: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1467: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1468: 			&add_filetype($allfiles,$file,$item);
                   1469: 		    }
                   1470: 		}
                   1471: 	    } 
                   1472: 	    pop @state;
                   1473: 	}
                   1474:     }
1.637     raeburn  1475:     return 'ok';
                   1476: }
                   1477: 
1.639     albertel 1478: sub add_filetype {
                   1479:     my ($allfiles,$file,$type)=@_;
                   1480:     if (exists($allfiles->{$file})) {
                   1481: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1482: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1483: 	}
                   1484:     } else {
                   1485: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1486:     }
                   1487: }
                   1488: 
1.493     albertel 1489: sub removeuploadedurl {
                   1490:     my ($url)=@_;
                   1491:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1492:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1493: }
                   1494: 
                   1495: sub removeuserfile {
                   1496:     my ($docuname,$docudom,$fname)=@_;
                   1497:     my $home=&homeserver($docuname,$docudom);
                   1498:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1499: }
1.15      www      1500: 
1.530     albertel 1501: sub mkdiruserfile {
                   1502:     my ($docuname,$docudom,$dir)=@_;
                   1503:     my $home=&homeserver($docuname,$docudom);
                   1504:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1505: }
                   1506: 
1.531     albertel 1507: sub renameuserfile {
                   1508:     my ($docuname,$docudom,$old,$new)=@_;
                   1509:     my $home=&homeserver($docuname,$docudom);
                   1510:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1511: 		  &escape("$new"),$home);
                   1512: }
                   1513: 
1.14      www      1514: # ------------------------------------------------------------------------- Log
                   1515: 
                   1516: sub log {
                   1517:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1518:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1519: }
                   1520: 
                   1521: # ------------------------------------------------------------------ Course Log
1.352     www      1522: #
                   1523: # This routine flushes several buffers of non-mission-critical nature
                   1524: #
1.157     www      1525: 
                   1526: sub flushcourselogs {
1.352     www      1527:     &logthis('Flushing log buffers');
                   1528: #
                   1529: # course logs
                   1530: # This is a log of all transactions in a course, which can be used
                   1531: # for data mining purposes
                   1532: #
                   1533: # It also collects the courseid database, which lists last transaction
                   1534: # times and course titles for all courseids
                   1535: #
                   1536:     my %courseidbuffer=();
1.191     harris41 1537:     foreach (keys %courselogs) {
1.157     www      1538:         my $crsid=$_;
1.352     www      1539:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1540: 		          &escape($courselogs{$crsid}),
                   1541: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1542: 	    delete $courselogs{$crsid};
                   1543:         } else {
                   1544:             &logthis('Failed to flush log buffer for '.$crsid);
                   1545:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1546:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1547:                         " exceeded maximum size, deleting.</font>");
                   1548:                delete $courselogs{$crsid};
                   1549:             }
1.352     www      1550:         }
                   1551:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1552:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1553: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1554:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1555:         } else {
                   1556:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1557: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1558:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1559:         }
1.191     harris41 1560:     }
1.352     www      1561: #
                   1562: # Write course id database (reverse lookup) to homeserver of courses 
                   1563: # Is used in pickcourse
                   1564: #
                   1565:     foreach (keys %courseidbuffer) {
1.353     www      1566:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1567:     }
                   1568: #
                   1569: # File accesses
                   1570: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1571: #
1.449     matthew  1572:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1573:         if ($entry =~ /___count$/) {
                   1574:             my ($dom,$name);
                   1575:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1576:             if (! defined($dom) || $dom eq '' || 
                   1577:                 ! defined($name) || $name eq '') {
1.620     albertel 1578:                 my $cid = $env{'request.course.id'};
                   1579:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1580:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1581:             }
1.450     matthew  1582:             my $value = $accesshash{$entry};
                   1583:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1584:             my %temphash=($url => $value);
1.449     matthew  1585:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1586:             if ($result eq 'ok') {
                   1587:                 delete $accesshash{$entry};
                   1588:             } elsif ($result eq 'unknown_cmd') {
                   1589:                 # Target server has old code running on it.
1.450     matthew  1590:                 my %temphash=($entry => $value);
1.449     matthew  1591:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1592:                     delete $accesshash{$entry};
                   1593:                 }
                   1594:             }
                   1595:         } else {
1.458     matthew  1596:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1597:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1598:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1599:                 delete $accesshash{$entry};
                   1600:             }
1.185     www      1601:         }
1.191     harris41 1602:     }
1.352     www      1603: #
                   1604: # Roles
                   1605: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1606: #
1.349     www      1607:     foreach (keys %userrolehash) {
                   1608:         my $entry=$_;
1.351     www      1609:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1610: 	    split(/\:/,$entry);
                   1611:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1612:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1613:                 $rudom,$runame) eq 'ok') {
                   1614: 	    delete $userrolehash{$entry};
                   1615:         }
                   1616:     }
1.662     raeburn  1617: #
                   1618: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1619: #
                   1620:     my %domrolebuffer = ();
                   1621:     foreach my $entry (keys %domainrolehash) {
                   1622:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1623:         if ($domrolebuffer{$rudom}) {
                   1624:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1625:                       '='.&escape($domainrolehash{$entry});
                   1626:         } else {
                   1627:             $domrolebuffer{$rudom}.=&escape($entry).
                   1628:                       '='.&escape($domainrolehash{$entry});
                   1629:         }
                   1630:         delete $domainrolehash{$entry};
                   1631:     }
                   1632:     foreach my $dom (keys(%domrolebuffer)) {
                   1633:         foreach my $tryserver (keys %libserv) {
                   1634:             if ($hostdom{$tryserver} eq $dom) {
                   1635:                 unless (&reply('domroleput:'.$dom.':'.
                   1636:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1637:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1638:                 }
                   1639:             }
                   1640:         }
                   1641:     }
1.186     www      1642:     $dumpcount++;
1.157     www      1643: }
                   1644: 
                   1645: sub courselog {
                   1646:     my $what=shift;
1.158     www      1647:     $what=time.':'.$what;
1.620     albertel 1648:     unless ($env{'request.course.id'}) { return ''; }
                   1649:     $coursedombuf{$env{'request.course.id'}}=
                   1650:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1651:     $coursenumbuf{$env{'request.course.id'}}=
                   1652:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1653:     $coursehombuf{$env{'request.course.id'}}=
                   1654:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1655:     $coursedescrbuf{$env{'request.course.id'}}=
                   1656:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1657:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1658:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1659:     $courseownerbuf{$env{'request.course.id'}}=
                   1660:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1661:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1662: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1663:     } else {
1.620     albertel 1664: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1665:     }
1.620     albertel 1666:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1667: 	&flushcourselogs();
                   1668:     }
1.158     www      1669: }
                   1670: 
                   1671: sub courseacclog {
                   1672:     my $fnsymb=shift;
1.620     albertel 1673:     unless ($env{'request.course.id'}) { return ''; }
                   1674:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1675:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1676:         $what.=':POST';
1.583     matthew  1677:         # FIXME: Probably ought to escape things....
1.620     albertel 1678: 	foreach (keys %env) {
1.158     www      1679:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1680: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1681:             }
1.191     harris41 1682:         }
1.583     matthew  1683:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1684:         # FIXME: We should not be depending on a form parameter that someone
                   1685:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1686:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1687:             $what.= ':POST';
                   1688:             # FIXME: Probably ought to escape things....
                   1689:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1690:                                  'crsdiscuss') {
1.620     albertel 1691:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1692:             }
                   1693:         }
1.158     www      1694:     }
                   1695:     &courselog($what);
1.149     www      1696: }
                   1697: 
1.185     www      1698: sub countacc {
                   1699:     my $url=&declutter(shift);
1.458     matthew  1700:     return if (! defined($url) || $url eq '');
1.620     albertel 1701:     unless ($env{'request.course.id'}) { return ''; }
                   1702:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1703:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1704:     $accesshash{$key}++;
1.185     www      1705: }
1.349     www      1706: 
1.361     www      1707: sub linklog {
                   1708:     my ($from,$to)=@_;
                   1709:     $from=&declutter($from);
                   1710:     $to=&declutter($to);
                   1711:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1712:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1713: }
                   1714:   
1.349     www      1715: sub userrolelog {
                   1716:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1717:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1718:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1719:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1720:         ($trole=~/^ta/)) {
1.350     www      1721:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1722:        $userrolehash
                   1723:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1724:                     =$tend.':'.$tstart;
1.662     raeburn  1725:     }
                   1726:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1727:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1728:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1729:         ($trole=~/^sc/)) {
                   1730:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1731:        $domainrolehash
                   1732:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1733:                     = $tend.':'.$tstart;
                   1734:     }
1.351     www      1735: }
                   1736: 
                   1737: sub get_course_adv_roles {
                   1738:     my $cid=shift;
1.620     albertel 1739:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1740:     my %coursehash=&coursedescription($cid);
1.470     www      1741:     my %nothide=();
                   1742:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1743: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1744:     }
1.351     www      1745:     my %returnhash=();
                   1746:     my %dumphash=
                   1747:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1748:     my $now=time;
                   1749:     foreach (keys %dumphash) {
                   1750: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1751:         if (($tstart) && ($tstart<0)) { next; }
                   1752:         if (($tend) && ($tend<$now)) { next; }
                   1753:         if (($tstart) && ($now<$tstart)) { next; }
                   1754:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1755: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1756: 	if ((&privileged($username,$domain)) && 
                   1757: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1758: 	if ($role eq 'cr') { next; }
1.351     www      1759:         my $key=&plaintext($role);
1.656     albertel 1760: 	if ($role =~ /^cr/) {
                   1761: 	    $key=(split('/',$role))[3];
                   1762: 	}
1.351     www      1763:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1764:         if ($returnhash{$key}) {
                   1765: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1766:         } else {
                   1767:             $returnhash{$key}=$username.':'.$domain;
                   1768:         }
1.400     www      1769:      }
                   1770:     return %returnhash;
                   1771: }
                   1772: 
                   1773: sub get_my_roles {
                   1774:     my ($uname,$udom)=@_;
1.620     albertel 1775:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1776:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1777:     my %dumphash=
                   1778:             &dump('nohist_userroles',$udom,$uname);
                   1779:     my %returnhash=();
                   1780:     my $now=time;
                   1781:     foreach (keys %dumphash) {
                   1782: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1783:         if (($tstart) && ($tstart<0)) { next; }
                   1784:         if (($tend) && ($tend<$now)) { next; }
                   1785:         if (($tstart) && ($now<$tstart)) { next; }
                   1786:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1787: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1788:      }
                   1789:     return %returnhash;
1.399     www      1790: }
                   1791: 
                   1792: # ----------------------------------------------------- Frontpage Announcements
                   1793: #
                   1794: #
                   1795: 
                   1796: sub postannounce {
                   1797:     my ($server,$text)=@_;
                   1798:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1799:     unless ($text=~/\w/) { $text=''; }
                   1800:     return &reply('setannounce:'.&escape($text),$server);
                   1801: }
                   1802: 
                   1803: sub getannounce {
1.448     albertel 1804: 
                   1805:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1806: 	my $announcement='';
                   1807: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1808: 	close($fh);
1.399     www      1809: 	if ($announcement=~/\w/) { 
                   1810: 	    return 
                   1811:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1812:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1813: 	} else {
                   1814: 	    return '';
                   1815: 	}
                   1816:     } else {
                   1817: 	return '';
                   1818:     }
1.351     www      1819: }
1.353     www      1820: 
                   1821: # ---------------------------------------------------------- Course ID routines
                   1822: # Deal with domain's nohist_courseid.db files
                   1823: #
                   1824: 
                   1825: sub courseidput {
                   1826:     my ($domain,$what,$coursehome)=@_;
                   1827:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1828: }
                   1829: 
                   1830: sub courseiddump {
1.622     raeburn  1831:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1832:     my %returnhash=();
1.355     www      1833:     unless ($domfilter) { $domfilter=''; }
1.353     www      1834:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1835:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1836: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1837: 	        foreach (
                   1838:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1839: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1840:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1841:                                $tryserver))) {
1.506     raeburn  1842: 		    my ($key,$value)=split(/\=/,$_);
                   1843:                     if (($key) && ($value)) {
1.516     raeburn  1844: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1845:                     }
1.353     www      1846:                 }
                   1847:             }
                   1848:         }
                   1849:     }
                   1850:     return %returnhash;
                   1851: }
                   1852: 
1.658     raeburn  1853: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1854: 
                   1855: sub dcmailput {
                   1856:     my ($domain,$msgid,$contents,$server)=@_;
                   1857:     my $status = &Apache::lonnet::critical(
                   1858:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
                   1859:        &Apache::lonnet::escape($$contents{$server}),$server);
                   1860:     return $status;
                   1861: }
                   1862: 
1.658     raeburn  1863: sub dcmaildump {
                   1864:     my ($dom,$startdate,$enddate,$senders) = @_;
                   1865:     my %returnhash=(); 
1.660     raeburn  1866:     foreach my $tryserver (keys(%libserv)) {
1.658     raeburn  1867:         if ($hostdom{$tryserver} eq $dom) {
                   1868:             %{$returnhash{$tryserver}}=();
1.664     albertel 1869: 	    my $cmd='dcmaildump:'.$dom.':'.
                   1870: 		&escape($startdate).':'.&escape($enddate).':';
                   1871: 	    my @esc_senders=map { &escape($_)} @$senders;
                   1872: 	    $cmd.=&escape(join('&',@esc_senders));
                   1873: 	    foreach (split(/\&/,&reply($cmd,$tryserver))) {
1.662     raeburn  1874:                 my ($key,$value) = split(/\=/,$_);
1.658     raeburn  1875:                 if (($key) && ($value)) {
1.660     raeburn  1876:                     $returnhash{$tryserver}{&unescape($key)} = &unescape($value);
1.658     raeburn  1877:                 }
                   1878:             }
                   1879:         }
                   1880:     }
                   1881:     return %returnhash;
                   1882: }
1.662     raeburn  1883: # ---------------------------------------------------------- Domain roles
                   1884: 
                   1885: sub get_domain_roles {
                   1886:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1887:     if (undef($startdate) || $startdate eq '') {
                   1888:         $startdate = '.';
                   1889:     }
                   1890:     if (undef($enddate) || $enddate eq '') {
                   1891:         $enddate = '.';
                   1892:     }
                   1893:     my $rolelist = join(':',@{$roles});
                   1894:     my %personnel = ();
                   1895:     foreach my $tryserver (keys(%libserv)) {
                   1896:         if ($hostdom{$tryserver} eq $dom) {
                   1897:             %{$personnel{$tryserver}}=();
                   1898:             foreach (
                   1899:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1900:                    &escape($startdate).':'.&escape($enddate).':'.
                   1901:                    &escape($rolelist), $tryserver))) {
                   1902:                 my($key,$value) = split(/\=/,$_);
                   1903:                 if (($key) && ($value)) {
                   1904:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   1905:                 }
                   1906:             }
                   1907:         }
                   1908:     }
                   1909:     return %personnel;
                   1910: }
1.658     raeburn  1911: 
1.149     www      1912: # ----------------------------------------------------------- Check out an item
                   1913: 
1.504     albertel 1914: sub get_first_access {
                   1915:     my ($type,$argsymb)=@_;
                   1916:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1917:     if ($argsymb) { $symb=$argsymb; }
                   1918:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1919:     if ($type eq 'map') {
                   1920: 	$res=&symbread($map);
                   1921:     } else {
                   1922: 	$res=$symb;
                   1923:     }
                   1924:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   1925:     return $times{"$courseid\0$res"};
1.504     albertel 1926: }
                   1927: 
                   1928: sub set_first_access {
                   1929:     my ($type)=@_;
                   1930:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1931:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1932:     if ($type eq 'map') {
                   1933: 	$res=&symbread($map);
                   1934:     } else {
                   1935: 	$res=$symb;
                   1936:     }
                   1937:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 1938:     if (!$firstaccess) {
1.588     albertel 1939: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 1940:     }
                   1941:     return 'already_set';
1.504     albertel 1942: }
                   1943: 
1.149     www      1944: sub checkout {
                   1945:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1946:     my $now=time;
                   1947:     my $lonhost=$perlvar{'lonHostID'};
                   1948:     my $infostr=&escape(
1.234     www      1949:                  'CHECKOUTTOKEN&'.
1.149     www      1950:                  $tuname.'&'.
                   1951:                  $tudom.'&'.
                   1952:                  $tcrsid.'&'.
                   1953:                  $symb.'&'.
                   1954: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1955:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1956:     if ($token=~/^error\:/) { 
1.672     albertel 1957:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      1958:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1959:                  "</font>");
                   1960:         return ''; 
                   1961:     }
                   1962: 
1.149     www      1963:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1964:     $token=~tr/a-z/A-Z/;
                   1965: 
1.153     www      1966:     my %infohash=('resource.0.outtoken' => $token,
                   1967:                   'resource.0.checkouttime' => $now,
                   1968:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1969: 
                   1970:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1971:        return '';
1.151     www      1972:     } else {
1.672     albertel 1973:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      1974:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1975:                  "</font>");
1.149     www      1976:     }    
                   1977: 
                   1978:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1979:                          &escape('Checkout '.$infostr.' - '.
                   1980:                                                  $token)) ne 'ok') {
                   1981: 	return '';
1.151     www      1982:     } else {
1.672     albertel 1983:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      1984:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1985:                  "</font>");
1.149     www      1986:     }
1.151     www      1987:     return $token;
1.149     www      1988: }
                   1989: 
                   1990: # ------------------------------------------------------------ Check in an item
                   1991: 
                   1992: sub checkin {
                   1993:     my $token=shift;
1.150     www      1994:     my $now=time;
                   1995:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1996:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 1997:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      1998:     $dtoken=~s/\W/\_/g;
1.234     www      1999:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2000:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2001: 
1.154     www      2002:     unless (($tuname) && ($tudom)) {
                   2003:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2004:         return '';
                   2005:     }
                   2006:     
                   2007:     unless (&allowed('mgr',$tcrsid)) {
                   2008:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2009:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2010:         return '';
                   2011:     }
                   2012: 
1.153     www      2013:     my %infohash=('resource.0.intoken' => $token,
                   2014:                   'resource.0.checkintime' => $now,
                   2015:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2016: 
                   2017:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2018:        return '';
                   2019:     }    
                   2020: 
                   2021:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2022:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2023: 	return '';
                   2024:     }
                   2025: 
                   2026:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2027: }
                   2028: 
                   2029: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2030: 
                   2031: sub expirespread {
                   2032:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2033:     my $cid=$env{'request.course.id'}; 
1.110     www      2034:     if ($cid) {
                   2035:        my $now=time;
                   2036:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2037:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2038:                             $env{'course.'.$cid.'.num'}.
1.110     www      2039: 	        	    ':nohist_expirationdates:'.
                   2040:                             &escape($key).'='.$now,
1.620     albertel 2041:                             $env{'course.'.$cid.'.home'})
1.110     www      2042:     }
                   2043:     return 'ok';
1.14      www      2044: }
                   2045: 
1.109     www      2046: # ----------------------------------------------------- Devalidate Spreadsheets
                   2047: 
                   2048: sub devalidate {
1.325     www      2049:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2050:     my $cid=$env{'request.course.id'}; 
1.109     www      2051:     if ($cid) {
1.391     matthew  2052:         # delete the stored spreadsheets for
                   2053:         # - the student level sheet of this user in course's homespace
                   2054:         # - the assessment level sheet for this resource 
                   2055:         #   for this user in user's homespace
1.553     albertel 2056: 	# - current conditional state info
1.325     www      2057: 	my $key=$uname.':'.$udom.':';
1.109     www      2058:         my $status=
1.299     matthew  2059: 	    &del('nohist_calculatedsheets',
1.391     matthew  2060: 		 [$key.'studentcalc:'],
1.620     albertel 2061: 		 $env{'course.'.$cid.'.domain'},
                   2062: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2063: 		.' '.
                   2064: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2065: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2066:         unless ($status eq 'ok ok') {
                   2067:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2068:                     $uname.' at '.$udom.' for '.
1.109     www      2069: 		    $symb.': '.$status);
1.133     albertel 2070:         }
1.553     albertel 2071: 	&delenv('user.state.'.$cid);
1.109     www      2072:     }
                   2073: }
                   2074: 
1.265     albertel 2075: sub get_scalar {
                   2076:     my ($string,$end) = @_;
                   2077:     my $value;
                   2078:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2079: 	$value = $1;
                   2080:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2081: 	$value = $1;
                   2082:     }
                   2083:     return &unescape($value);
                   2084: }
                   2085: 
                   2086: sub array2str {
                   2087:   my (@array) = @_;
                   2088:   my $result=&arrayref2str(\@array);
                   2089:   $result=~s/^__ARRAY_REF__//;
                   2090:   $result=~s/__END_ARRAY_REF__$//;
                   2091:   return $result;
                   2092: }
                   2093: 
1.204     albertel 2094: sub arrayref2str {
                   2095:   my ($arrayref) = @_;
1.265     albertel 2096:   my $result='__ARRAY_REF__';
1.204     albertel 2097:   foreach my $elem (@$arrayref) {
1.265     albertel 2098:     if(ref($elem) eq 'ARRAY') {
                   2099:       $result.=&arrayref2str($elem).'&';
                   2100:     } elsif(ref($elem) eq 'HASH') {
                   2101:       $result.=&hashref2str($elem).'&';
                   2102:     } elsif(ref($elem)) {
                   2103:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2104:     } else {
                   2105:       $result.=&escape($elem).'&';
                   2106:     }
                   2107:   }
                   2108:   $result=~s/\&$//;
1.265     albertel 2109:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2110:   return $result;
                   2111: }
                   2112: 
1.168     albertel 2113: sub hash2str {
1.204     albertel 2114:   my (%hash) = @_;
                   2115:   my $result=&hashref2str(\%hash);
1.265     albertel 2116:   $result=~s/^__HASH_REF__//;
                   2117:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2118:   return $result;
                   2119: }
                   2120: 
                   2121: sub hashref2str {
                   2122:   my ($hashref)=@_;
1.265     albertel 2123:   my $result='__HASH_REF__';
1.495     albertel 2124:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2125:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2126:       $result.=&arrayref2str($_).'=';
1.204     albertel 2127:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2128:       $result.=&hashref2str($_).'=';
1.204     albertel 2129:     } elsif (ref($_)) {
1.265     albertel 2130:       $result.='=';
                   2131:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2132:     } else {
1.265     albertel 2133: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2134:     }
                   2135: 
1.265     albertel 2136:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2137:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2138:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2139:       $result.=&hashref2str($hashref->{$_}).'&';
                   2140:     } elsif(ref($hashref->{$_})) {
                   2141:        $result.='&';
                   2142:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2143:     } else {
1.265     albertel 2144:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2145:     }
                   2146:   }
1.168     albertel 2147:   $result=~s/\&$//;
1.265     albertel 2148:   $result .= '__END_HASH_REF__';
1.168     albertel 2149:   return $result;
                   2150: }
                   2151: 
                   2152: sub str2hash {
1.265     albertel 2153:     my ($string)=@_;
                   2154:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2155:     return %$hash;
                   2156: }
                   2157: 
                   2158: sub str2hashref {
1.168     albertel 2159:   my ($string) = @_;
1.265     albertel 2160: 
                   2161:   my %hash;
                   2162: 
                   2163:   if($string !~ /^__HASH_REF__/) {
                   2164:       if (! ($string eq '' || !defined($string))) {
                   2165: 	  $hash{'error'}='Not hash reference';
                   2166:       }
                   2167:       return (\%hash, $string);
                   2168:   }
                   2169: 
                   2170:   $string =~ s/^__HASH_REF__//;
                   2171: 
                   2172:   while($string !~ /^__END_HASH_REF__/) {
                   2173:       #key
                   2174:       my $key='';
                   2175:       if($string =~ /^__HASH_REF__/) {
                   2176:           ($key, $string)=&str2hashref($string);
                   2177:           if(defined($key->{'error'})) {
                   2178:               $hash{'error'}='Bad data';
                   2179:               return (\%hash, $string);
                   2180:           }
                   2181:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2182:           ($key, $string)=&str2arrayref($string);
                   2183:           if($key->[0] eq 'Array reference error') {
                   2184:               $hash{'error'}='Bad data';
                   2185:               return (\%hash, $string);
                   2186:           }
                   2187:       } else {
                   2188:           $string =~ s/^(.*?)=//;
1.267     albertel 2189: 	  $key=&unescape($1);
1.265     albertel 2190:       }
                   2191:       $string =~ s/^=//;
                   2192: 
                   2193:       #value
                   2194:       my $value='';
                   2195:       if($string =~ /^__HASH_REF__/) {
                   2196:           ($value, $string)=&str2hashref($string);
                   2197:           if(defined($value->{'error'})) {
                   2198:               $hash{'error'}='Bad data';
                   2199:               return (\%hash, $string);
                   2200:           }
                   2201:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2202:           ($value, $string)=&str2arrayref($string);
                   2203:           if($value->[0] eq 'Array reference error') {
                   2204:               $hash{'error'}='Bad data';
                   2205:               return (\%hash, $string);
                   2206:           }
                   2207:       } else {
                   2208: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2209:       }
                   2210:       $string =~ s/^&//;
                   2211: 
                   2212:       $hash{$key}=$value;
1.204     albertel 2213:   }
1.265     albertel 2214: 
                   2215:   $string =~ s/^__END_HASH_REF__//;
                   2216: 
                   2217:   return (\%hash, $string);
1.204     albertel 2218: }
                   2219: 
                   2220: sub str2array {
1.265     albertel 2221:     my ($string)=@_;
                   2222:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2223:     return @$array;
                   2224: }
                   2225: 
                   2226: sub str2arrayref {
1.204     albertel 2227:   my ($string) = @_;
1.265     albertel 2228:   my @array;
                   2229: 
                   2230:   if($string !~ /^__ARRAY_REF__/) {
                   2231:       if (! ($string eq '' || !defined($string))) {
                   2232: 	  $array[0]='Array reference error';
                   2233:       }
                   2234:       return (\@array, $string);
                   2235:   }
                   2236: 
                   2237:   $string =~ s/^__ARRAY_REF__//;
                   2238: 
                   2239:   while($string !~ /^__END_ARRAY_REF__/) {
                   2240:       my $value='';
                   2241:       if($string =~ /^__HASH_REF__/) {
                   2242:           ($value, $string)=&str2hashref($string);
                   2243:           if(defined($value->{'error'})) {
                   2244:               $array[0] ='Array reference error';
                   2245:               return (\@array, $string);
                   2246:           }
                   2247:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2248:           ($value, $string)=&str2arrayref($string);
                   2249:           if($value->[0] eq 'Array reference error') {
                   2250:               $array[0] ='Array reference error';
                   2251:               return (\@array, $string);
                   2252:           }
                   2253:       } else {
                   2254: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2255:       }
                   2256:       $string =~ s/^&//;
                   2257: 
                   2258:       push(@array, $value);
1.191     harris41 2259:   }
1.265     albertel 2260: 
                   2261:   $string =~ s/^__END_ARRAY_REF__//;
                   2262: 
                   2263:   return (\@array, $string);
1.168     albertel 2264: }
                   2265: 
1.167     albertel 2266: # -------------------------------------------------------------------Temp Store
                   2267: 
1.168     albertel 2268: sub tmpreset {
                   2269:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2270:   if (!$symb) {
                   2271:     $symb=&symbread();
1.620     albertel 2272:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2273:   }
                   2274:   $symb=escape($symb);
                   2275: 
1.620     albertel 2276:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2277:   $namespace=~s/\//\_/g;
                   2278:   $namespace=~s/\W//g;
                   2279: 
1.620     albertel 2280:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2281:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2282:   if ($domain eq 'public' && $stuname eq 'public') {
                   2283:       $stuname=$ENV{'REMOTE_ADDR'};
                   2284:   }
1.168     albertel 2285:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2286:   my %hash;
                   2287:   if (tie(%hash,'GDBM_File',
                   2288: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2289: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2290:     foreach my $key (keys %hash) {
1.180     albertel 2291:       if ($key=~ /:$symb/) {
1.168     albertel 2292: 	delete($hash{$key});
                   2293:       }
                   2294:     }
                   2295:   }
                   2296: }
                   2297: 
1.167     albertel 2298: sub tmpstore {
1.168     albertel 2299:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2300: 
                   2301:   if (!$symb) {
                   2302:     $symb=&symbread();
1.620     albertel 2303:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2304:   }
                   2305:   $symb=escape($symb);
                   2306: 
                   2307:   if (!$namespace) {
                   2308:     # I don't think we would ever want to store this for a course.
                   2309:     # it seems this will only be used if we don't have a course.
1.620     albertel 2310:     #$namespace=$env{'request.course.id'};
1.168     albertel 2311:     #if (!$namespace) {
1.620     albertel 2312:       $namespace=$env{'request.state'};
1.168     albertel 2313:     #}
                   2314:   }
                   2315:   $namespace=~s/\//\_/g;
                   2316:   $namespace=~s/\W//g;
1.620     albertel 2317:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2318:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2319:   if ($domain eq 'public' && $stuname eq 'public') {
                   2320:       $stuname=$ENV{'REMOTE_ADDR'};
                   2321:   }
1.168     albertel 2322:   my $now=time;
                   2323:   my %hash;
                   2324:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2325:   if (tie(%hash,'GDBM_File',
                   2326: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2327: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2328:     $hash{"version:$symb"}++;
                   2329:     my $version=$hash{"version:$symb"};
                   2330:     my $allkeys=''; 
                   2331:     foreach my $key (keys(%$storehash)) {
                   2332:       $allkeys.=$key.':';
1.591     albertel 2333:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2334:     }
                   2335:     $hash{"$version:$symb:timestamp"}=$now;
                   2336:     $allkeys.='timestamp';
                   2337:     $hash{"$version:keys:$symb"}=$allkeys;
                   2338:     if (untie(%hash)) {
                   2339:       return 'ok';
                   2340:     } else {
                   2341:       return "error:$!";
                   2342:     }
                   2343:   } else {
                   2344:     return "error:$!";
                   2345:   }
                   2346: }
1.167     albertel 2347: 
1.168     albertel 2348: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2349: 
1.168     albertel 2350: sub tmprestore {
                   2351:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2352: 
1.168     albertel 2353:   if (!$symb) {
                   2354:     $symb=&symbread();
1.620     albertel 2355:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2356:   }
                   2357:   $symb=escape($symb);
                   2358: 
1.620     albertel 2359:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2360: 
1.620     albertel 2361:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2362:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2363:   if ($domain eq 'public' && $stuname eq 'public') {
                   2364:       $stuname=$ENV{'REMOTE_ADDR'};
                   2365:   }
1.168     albertel 2366:   my %returnhash;
                   2367:   $namespace=~s/\//\_/g;
                   2368:   $namespace=~s/\W//g;
                   2369:   my %hash;
                   2370:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2371:   if (tie(%hash,'GDBM_File',
                   2372: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2373: 	  &GDBM_READER(),0640)) {
1.168     albertel 2374:     my $version=$hash{"version:$symb"};
                   2375:     $returnhash{'version'}=$version;
                   2376:     my $scope;
                   2377:     for ($scope=1;$scope<=$version;$scope++) {
                   2378:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2379:       my @keys=split(/:/,$vkeys);
                   2380:       my $key;
                   2381:       $returnhash{"$scope:keys"}=$vkeys;
                   2382:       foreach $key (@keys) {
1.591     albertel 2383: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2384: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2385:       }
                   2386:     }
1.168     albertel 2387:     if (!(untie(%hash))) {
                   2388:       return "error:$!";
                   2389:     }
                   2390:   } else {
                   2391:     return "error:$!";
                   2392:   }
                   2393:   return %returnhash;
1.167     albertel 2394: }
                   2395: 
1.9       www      2396: # ----------------------------------------------------------------------- Store
                   2397: 
                   2398: sub store {
1.124     www      2399:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2400:     my $home='';
                   2401: 
1.168     albertel 2402:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2403: 
1.213     www      2404:     $symb=&symbclean($symb);
1.122     albertel 2405:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2406: 
1.620     albertel 2407:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2408:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2409: 
                   2410:     &devalidate($symb,$stuname,$domain);
1.109     www      2411: 
                   2412:     $symb=escape($symb);
1.187     www      2413:     if (!$namespace) { 
1.620     albertel 2414:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2415:           return ''; 
                   2416:        } 
                   2417:     }
1.620     albertel 2418:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2419: 
                   2420:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2421:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2422: 
1.12      www      2423:     my $namevalue='';
1.191     harris41 2424:     foreach (keys %$storehash) {
1.591     albertel 2425:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2426:     }
1.12      www      2427:     $namevalue=~s/\&$//;
1.187     www      2428:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2429:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2430: }
                   2431: 
1.47      www      2432: # -------------------------------------------------------------- Critical Store
                   2433: 
                   2434: sub cstore {
1.124     www      2435:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2436:     my $home='';
                   2437: 
1.168     albertel 2438:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2439: 
1.213     www      2440:     $symb=&symbclean($symb);
1.122     albertel 2441:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2442: 
1.620     albertel 2443:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2444:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2445: 
                   2446:     &devalidate($symb,$stuname,$domain);
1.109     www      2447: 
                   2448:     $symb=escape($symb);
1.187     www      2449:     if (!$namespace) { 
1.620     albertel 2450:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2451:           return ''; 
                   2452:        } 
                   2453:     }
1.620     albertel 2454:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2455: 
                   2456:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2457:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2458: 
1.47      www      2459:     my $namevalue='';
1.191     harris41 2460:     foreach (keys %$storehash) {
1.591     albertel 2461:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2462:     }
1.47      www      2463:     $namevalue=~s/\&$//;
1.187     www      2464:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2465:     return critical
                   2466:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2467: }
                   2468: 
1.9       www      2469: # --------------------------------------------------------------------- Restore
                   2470: 
                   2471: sub restore {
1.124     www      2472:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2473:     my $home='';
                   2474: 
1.168     albertel 2475:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2476: 
1.122     albertel 2477:     if (!$symb) {
                   2478:       unless ($symb=escape(&symbread())) { return ''; }
                   2479:     } else {
1.213     www      2480:       $symb=&escape(&symbclean($symb));
1.122     albertel 2481:     }
1.188     www      2482:     if (!$namespace) { 
1.620     albertel 2483:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2484:           return ''; 
                   2485:        } 
                   2486:     }
1.620     albertel 2487:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2488:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2489:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2490:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2491: 
1.12      www      2492:     my %returnhash=();
1.191     harris41 2493:     foreach (split(/\&/,$answer)) {
1.12      www      2494: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2495:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2496:     }
1.75      www      2497:     my $version;
                   2498:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2499:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2500:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2501:        }
1.75      www      2502:     }
1.13      www      2503:     return %returnhash;
1.34      www      2504: }
                   2505: 
                   2506: # ---------------------------------------------------------- Course Description
                   2507: 
                   2508: sub coursedescription {
                   2509:     my $courseid=shift;
                   2510:     $courseid=~s/^\///;
1.49      www      2511:     $courseid=~s/\_/\//g;
1.34      www      2512:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2513:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2514:     my $normalid=$cdomain.'_'.$cnum;
                   2515:     # need to always cache even if we get errors otherwise we keep 
                   2516:     # trying and trying and trying to get the course description.
                   2517:     my %envhash=();
                   2518:     my %returnhash=();
                   2519:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2520:     if ($chome ne 'no_host') {
1.302     albertel 2521:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2522:        if (!exists($returnhash{'con_lost'})) {
                   2523:            $returnhash{'home'}= $chome;
                   2524: 	   $returnhash{'domain'} = $cdomain;
                   2525: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2526:            while (my ($name,$value) = each %returnhash) {
1.53      www      2527:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2528:            }
1.270     www      2529:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2530:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2531: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2532:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2533:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2534:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2535:        }
                   2536:     }
1.302     albertel 2537:     &appenv(%envhash);
                   2538:     return %returnhash;
1.461     www      2539: }
                   2540: 
                   2541: # -------------------------------------------------See if a user is privileged
                   2542: 
                   2543: sub privileged {
                   2544:     my ($username,$domain)=@_;
                   2545:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2546: 			&homeserver($username,$domain));
                   2547:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2548:     my $now=time;
                   2549:     if ($rolesdump ne '') {
                   2550:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2551: 	    if ($_!~/^rolesdef_/) {
1.461     www      2552: 		my ($area,$role)=split(/=/,$_);
                   2553: 		$area=~s/\_\w\w$//;
                   2554: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2555: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2556: 		    my $active=1;
                   2557: 		    if ($tend) {
                   2558: 			if ($tend<$now) { $active=0; }
                   2559: 		    }
                   2560: 		    if ($tstart) {
                   2561: 			if ($tstart>$now) { $active=0; }
                   2562: 		    }
                   2563: 		    if ($active) { return 1; }
                   2564: 		}
                   2565: 	    }
                   2566: 	}
                   2567:     }
                   2568:     return 0;
1.9       www      2569: }
1.1       albertel 2570: 
1.103     harris41 2571: # -------------------------------------------------------- Get user privileges
1.11      www      2572: 
                   2573: sub rolesinit {
                   2574:     my ($domain,$username,$authhost)=@_;
                   2575:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2576:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2577:     my %allroles=();
1.678     raeburn  2578:     my %allgroups=();   
1.11      www      2579:     my $now=time;
1.21      www      2580:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2581:     my $group_privs;
1.11      www      2582: 
                   2583:     if ($rolesdump ne '') {
1.191     harris41 2584:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2585: 	  if ($_!~/^rolesdef_/) {
1.11      www      2586:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2587: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2588:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2589: 	    if ($role=~/^cr/) { 
1.655     albertel 2590: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2591: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2592: 		    ($tend,$tstart)=split('_',$trest);
                   2593: 		} else {
                   2594: 		    $trole=$role;
                   2595: 		}
1.678     raeburn  2596:             } elsif ($role =~ m|^gr/|) {
                   2597:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2598:                 ($trole,$group_privs) = split(/\//,$trole);
                   2599:                 $group_privs = &unescape($group_privs);
1.587     albertel 2600: 	    } else {
                   2601: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2602: 	    }
1.576     albertel 2603:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2604:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2605:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2606:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2607: 		my $spec=$trole.'.'.$area;
                   2608: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2609: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2610:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2611:                 } elsif ($trole eq 'gr') {
                   2612:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2613: 		} else {
1.567     raeburn  2614:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2615: 		}
1.12      www      2616:             }
1.662     raeburn  2617:           }
1.191     harris41 2618:         }
1.678     raeburn  2619:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2620:         $userroles.='user.adv='.$adv."\n".
                   2621: 	            'user.author='.$author."\n";
1.620     albertel 2622:         $env{'user.adv'}=$adv;
1.11      www      2623:     }
                   2624:     return $userroles;  
                   2625: }
                   2626: 
1.567     raeburn  2627: sub set_arearole {
                   2628:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2629: # log the associated role with the area
                   2630:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2631:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2632: }
                   2633: 
                   2634: sub custom_roleprivs {
                   2635:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2636:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2637:     my $homsvr=homeserver($rauthor,$rdomain);
                   2638:     if ($hostname{$homsvr} ne '') {
                   2639:         my ($rdummy,$roledef)=
                   2640:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2641:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2642:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2643:             if (defined($syspriv)) {
                   2644:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2645:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2646:             }
                   2647:             if ($tdomain ne '') {
                   2648:                 if (defined($dompriv)) {
                   2649:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2650:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2651:                 }
                   2652:                 if (($trest ne '') && (defined($coursepriv))) {
                   2653:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2654:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2655:                 }
                   2656:             }
                   2657:         }
                   2658:     }
                   2659: }
                   2660: 
1.678     raeburn  2661: sub group_roleprivs {
                   2662:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2663:     my $access = 1;
                   2664:     my $now = time;
                   2665:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2666:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2667:     if ($access) {
                   2668:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2669:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2670:     }
                   2671: }
1.567     raeburn  2672: 
                   2673: sub standard_roleprivs {
                   2674:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2675:     if (defined($pr{$trole.':s'})) {
                   2676:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2677:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2678:     }
                   2679:     if ($tdomain ne '') {
                   2680:         if (defined($pr{$trole.':d'})) {
                   2681:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2682:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2683:         }
                   2684:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2685:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2686:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2687:         }
                   2688:     }
                   2689: }
                   2690: 
                   2691: sub set_userprivs {
1.678     raeburn  2692:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2693:     my $author=0;
                   2694:     my $adv=0;
1.678     raeburn  2695:     my %grouproles = ();
                   2696:     if (keys(%{$allgroups}) > 0) {
                   2697:         foreach my $role (keys %{$allroles}) {
1.681   ! raeburn  2698:             my ($trole,$area,$sec,$extendedarea);
        !          2699:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2700:                 $trole = $1;
                   2701:                 $area = $2;
1.681   ! raeburn  2702:                 $sec = $3;
        !          2703:                 $extendedarea = $area.$sec;
        !          2704:                 if (exists($$allgroups{$area})) {
        !          2705:                     foreach my $group (keys(%{$$allgroups{$area}})) {
        !          2706:                         my $spec = $trole.'.'.$extendedarea;
        !          2707:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
        !          2708:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2709:                     }
                   2710:                 }
                   2711:             }
                   2712:         }
                   2713:     }
                   2714:     foreach (keys(%grouproles)) {
                   2715:         $$allroles{$_} = $grouproles{$_};
                   2716:     }
1.567     raeburn  2717:     foreach (keys %{$allroles}) {
                   2718:         my %thesepriv=();
                   2719:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2720:         foreach (split(/:/,$$allroles{$_})) {
                   2721:             if ($_ ne '') {
                   2722:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2723:                 if ($restrictions eq '') {
                   2724:                     $thesepriv{$privilege}='F';
                   2725:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2726:                     $thesepriv{$privilege}.=$restrictions;
                   2727:                 }
                   2728:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2729:             }
                   2730:         }
                   2731:         my $thesestr='';
                   2732:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2733:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2734:     }
                   2735:     return ($author,$adv);
                   2736: }
                   2737: 
1.12      www      2738: # --------------------------------------------------------------- get interface
                   2739: 
                   2740: sub get {
1.131     albertel 2741:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2742:    my $items='';
1.191     harris41 2743:    foreach (@$storearr) {
1.12      www      2744:        $items.=escape($_).'&';
1.191     harris41 2745:    }
1.12      www      2746:    $items=~s/\&$//;
1.620     albertel 2747:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2748:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2749:    my $uhome=&homeserver($uname,$udomain);
                   2750: 
1.133     albertel 2751:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2752:    my @pairs=split(/\&/,$rep);
1.273     albertel 2753:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2754:      return @pairs;
                   2755:    }
1.15      www      2756:    my %returnhash=();
1.42      www      2757:    my $i=0;
1.191     harris41 2758:    foreach (@$storearr) {
1.557     albertel 2759:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2760:       $i++;
1.191     harris41 2761:    }
1.15      www      2762:    return %returnhash;
1.27      www      2763: }
                   2764: 
                   2765: # --------------------------------------------------------------- del interface
                   2766: 
                   2767: sub del {
1.133     albertel 2768:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2769:    my $items='';
1.191     harris41 2770:    foreach (@$storearr) {
1.27      www      2771:        $items.=escape($_).'&';
1.191     harris41 2772:    }
1.27      www      2773:    $items=~s/\&$//;
1.620     albertel 2774:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2775:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2776:    my $uhome=&homeserver($uname,$udomain);
                   2777: 
                   2778:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2779: }
                   2780: 
                   2781: # -------------------------------------------------------------- dump interface
                   2782: 
                   2783: sub dump {
1.193     www      2784:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.620     albertel 2785:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2786:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2787:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2788:    if ($regexp) {
                   2789:        $regexp=&escape($regexp);
                   2790:    } else {
                   2791:        $regexp='.';
                   2792:    }
                   2793:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2794:    my @pairs=split(/\&/,$rep);
                   2795:    my %returnhash=();
1.191     harris41 2796:    foreach (@pairs) {
1.12      www      2797:       my ($key,$value)=split(/=/,$_);
1.557     albertel 2798:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2799:    }
                   2800:    return %returnhash;
1.407     www      2801: }
                   2802: 
                   2803: # -------------------------------------------------------------- keys interface
                   2804: 
                   2805: sub getkeys {
                   2806:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2807:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2808:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2809:    my $uhome=&homeserver($uname,$udomain);
                   2810:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2811:    my @keyarray=();
                   2812:    foreach (split(/\&/,$rep)) {
                   2813:       push (@keyarray,&unescape($_));
                   2814:    }
                   2815:    return @keyarray;
1.318     matthew  2816: }
                   2817: 
1.319     matthew  2818: # --------------------------------------------------------------- currentdump
                   2819: sub currentdump {
1.328     matthew  2820:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2821:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2822:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2823:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2824:    my $uhome = &homeserver($sname,$sdom);
                   2825:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2826:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2827:    #
1.318     matthew  2828:    my %returnhash=();
1.319     matthew  2829:    #
                   2830:    if ($rep eq "unknown_cmd") { 
                   2831:        # an old lond will not know currentdump
                   2832:        # Do a dump and make it look like a currentdump
1.326     matthew  2833:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2834:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2835:        my %hash = @tmp;
                   2836:        @tmp=();
1.424     matthew  2837:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2838:    } else {
                   2839:        my @pairs=split(/\&/,$rep);
                   2840:        foreach (@pairs) {
                   2841:            my ($key,$value)=split(/=/,$_);
                   2842:            my ($symb,$param) = split(/:/,$key);
                   2843:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2844:                                                         &thaw_unescape($value);
1.319     matthew  2845:        }
1.191     harris41 2846:    }
1.12      www      2847:    return %returnhash;
1.424     matthew  2848: }
                   2849: 
                   2850: sub convert_dump_to_currentdump{
                   2851:     my %hash = %{shift()};
                   2852:     my %returnhash;
                   2853:     # Code ripped from lond, essentially.  The only difference
                   2854:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2855:     # we might run in to problems with parameter names =~ /^v\./
                   2856:     while (my ($key,$value) = each(%hash)) {
                   2857:         my ($v,$symb,$param) = split(/:/,$key);
                   2858:         next if ($v eq 'version' || $symb eq 'keys');
                   2859:         next if (exists($returnhash{$symb}) &&
                   2860:                  exists($returnhash{$symb}->{$param}) &&
                   2861:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2862:         $returnhash{$symb}->{$param}=$value;
                   2863:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2864:     }
                   2865:     #
                   2866:     # Remove all of the keys in the hashes which keep track of
                   2867:     # the version of the parameter.
                   2868:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2869:         # use a foreach because we are going to delete from the hash.
                   2870:         foreach my $key (keys(%$param_hash)) {
                   2871:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2872:         }
                   2873:     }
                   2874:     return \%returnhash;
1.12      www      2875: }
                   2876: 
1.627     albertel 2877: # ------------------------------------------------------ critical inc interface
                   2878: 
                   2879: sub cinc {
                   2880:     return &inc(@_,'critical');
                   2881: }
                   2882: 
1.449     matthew  2883: # --------------------------------------------------------------- inc interface
                   2884: 
                   2885: sub inc {
1.627     albertel 2886:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 2887:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2888:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  2889:     my $uhome=&homeserver($uname,$udomain);
                   2890:     my $items='';
                   2891:     if (! ref($store)) {
                   2892:         # got a single value, so use that instead
                   2893:         $items = &escape($store).'=&';
                   2894:     } elsif (ref($store) eq 'SCALAR') {
                   2895:         $items = &escape($$store).'=&';        
                   2896:     } elsif (ref($store) eq 'ARRAY') {
                   2897:         $items = join('=&',map {&escape($_);} @{$store});
                   2898:     } elsif (ref($store) eq 'HASH') {
                   2899:         while (my($key,$value) = each(%{$store})) {
                   2900:             $items.= &escape($key).'='.&escape($value).'&';
                   2901:         }
                   2902:     }
                   2903:     $items=~s/\&$//;
1.627     albertel 2904:     if ($critical) {
                   2905: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2906:     } else {
                   2907: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2908:     }
1.449     matthew  2909: }
                   2910: 
1.12      www      2911: # --------------------------------------------------------------- put interface
                   2912: 
                   2913: sub put {
1.134     albertel 2914:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2916:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2917:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2918:    my $items='';
1.191     harris41 2919:    foreach (keys %$storehash) {
1.557     albertel 2920:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2921:    }
1.12      www      2922:    $items=~s/\&$//;
1.134     albertel 2923:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2924: }
                   2925: 
1.631     albertel 2926: # ------------------------------------------------------------ newput interface
                   2927: 
                   2928: sub newput {
                   2929:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2930:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2931:    if (!$uname) { $uname=$env{'user.name'}; }
                   2932:    my $uhome=&homeserver($uname,$udomain);
                   2933:    my $items='';
                   2934:    foreach my $key (keys(%$storehash)) {
                   2935:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2936:    }
                   2937:    $items=~s/\&$//;
                   2938:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   2939: }
                   2940: 
                   2941: # ---------------------------------------------------------  putstore interface
                   2942: 
1.524     raeburn  2943: sub putstore {
                   2944:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2945:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2946:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  2947:    my $uhome=&homeserver($uname,$udomain);
                   2948:    my $items='';
                   2949:    my %allitems = ();
                   2950:    foreach (keys %$storehash) {
                   2951:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   2952:            my $key = $1.':keys:'.$2;
                   2953:            $allitems{$key} .= $3.':';
                   2954:        }
1.591     albertel 2955:        $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
1.524     raeburn  2956:    }
                   2957:    foreach (keys %allitems) {
                   2958:        $allitems{$_} =~ s/\:$//;
                   2959:        $items.= $_.'='.$allitems{$_}.'&';
                   2960:    }
                   2961:    $items=~s/\&$//;
                   2962:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   2963: }
                   2964: 
1.47      www      2965: # ------------------------------------------------------ critical put interface
                   2966: 
                   2967: sub cput {
1.134     albertel 2968:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2970:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2971:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2972:    my $items='';
1.191     harris41 2973:    foreach (keys %$storehash) {
1.557     albertel 2974:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2975:    }
1.47      www      2976:    $items=~s/\&$//;
1.134     albertel 2977:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2978: }
                   2979: 
                   2980: # -------------------------------------------------------------- eget interface
                   2981: 
                   2982: sub eget {
1.133     albertel 2983:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2984:    my $items='';
1.191     harris41 2985:    foreach (@$storearr) {
1.12      www      2986:        $items.=escape($_).'&';
1.191     harris41 2987:    }
1.12      www      2988:    $items=~s/\&$//;
1.620     albertel 2989:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2990:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2991:    my $uhome=&homeserver($uname,$udomain);
                   2992:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2993:    my @pairs=split(/\&/,$rep);
                   2994:    my %returnhash=();
1.42      www      2995:    my $i=0;
1.191     harris41 2996:    foreach (@$storearr) {
1.557     albertel 2997:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2998:       $i++;
1.191     harris41 2999:    }
1.12      www      3000:    return %returnhash;
                   3001: }
                   3002: 
1.667     albertel 3003: # ------------------------------------------------------------ tmpput interface
                   3004: sub tmpput {
                   3005:     my ($storehash,$server)=@_;
                   3006:     my $items='';
                   3007:     foreach (keys(%$storehash)) {
                   3008: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3009:     }
                   3010:     $items=~s/\&$//;
                   3011:     return &reply("tmpput:$items",$server);
                   3012: }
                   3013: 
                   3014: # ------------------------------------------------------------ tmpget interface
                   3015: sub tmpget {
                   3016:     my ($token)=@_;
                   3017:     my $rep=&reply("tmpget:$token",$perlvar{'lonHostID'});
                   3018:     my %returnhash;
                   3019:     foreach my $item (split(/\&/,$rep)) {
                   3020: 	my ($key,$value)=split(/=/,$item);
                   3021: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3022:     }
                   3023:     return %returnhash;
                   3024: }
                   3025: 
1.341     www      3026: # ---------------------------------------------- Custom access rule evaluation
                   3027: 
                   3028: sub customaccess {
                   3029:     my ($priv,$uri)=@_;
1.620     albertel 3030:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3031:     $urealm=~s/^\W//;
                   3032:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3033:     my $access=0;
                   3034:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3035: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3036:         if ($role) {
                   3037: 	   if ($role ne $urole) { next; }
                   3038:         }
                   3039:         foreach (split(/\s*\,\s*/,$realm)) {
                   3040:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3041:             if ($tdom) {
                   3042: 		if ($tdom ne $udom) { next; }
                   3043:             }
                   3044:             if ($tcrs) {
                   3045: 		if ($tcrs ne $ucrs) { next; }
                   3046:             }
                   3047:             if ($tsec) {
                   3048: 		if ($tsec ne $usec) { next; }
                   3049:             }
                   3050:             $access=($effect eq 'allow');
                   3051:             last;
1.342     www      3052:         }
1.402     bowersj2 3053: 	if ($realm eq '' && $role eq '') {
                   3054:             $access=($effect eq 'allow');
                   3055: 	}
1.341     www      3056:     }
                   3057:     return $access;
                   3058: }
                   3059: 
1.103     harris41 3060: # ------------------------------------------------- Check for a user privilege
1.12      www      3061: 
                   3062: sub allowed {
1.579     albertel 3063:     my ($priv,$uri,$symb)=@_;
1.439     www      3064:     $uri=&deversion($uri);
1.152     www      3065:     my $orguri=$uri;
1.52      www      3066:     $uri=&declutter($uri);
1.545     banghart 3067:     
1.620     albertel 3068:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3069: # Free bre access to adm and meta resources
1.529     albertel 3070:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3071: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3072: 	return 'F';
1.159     www      3073:     }
                   3074: 
1.545     banghart 3075: # Free bre access to user's own portfolio contents
1.546     albertel 3076:     my ($space,$domain,$name,$dir)=split('/',$uri);
1.647     raeburn  3077:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.620     albertel 3078: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545     banghart 3079:         return 'F';
                   3080:     }
                   3081: 
1.159     www      3082: # Free bre to public access
                   3083: 
                   3084:     if ($priv eq 'bre') {
1.238     www      3085:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3086: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3087:            return 'F'; 
                   3088:         }
1.238     www      3089:         if ($copyright eq 'priv') {
                   3090:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3091: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3092: 		return '';
                   3093:             }
                   3094:         }
                   3095:         if ($copyright eq 'domain') {
                   3096:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3097: 	    unless (($env{'user.domain'} eq $1) ||
                   3098:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3099: 		return '';
                   3100:             }
1.262     matthew  3101:         }
1.620     albertel 3102:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3103:             # Library role, so allow browsing of resources in this domain.
                   3104:             return 'F';
1.238     www      3105:         }
1.341     www      3106:         if ($copyright eq 'custom') {
                   3107: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3108:         }
1.14      www      3109:     }
1.264     matthew  3110:     # Domain coordinator is trying to create a course
1.620     albertel 3111:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3112:         # uri is the requested domain in this case.
                   3113:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3114:         # a role of dc for the domain in question.
1.620     albertel 3115:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3116:     }
1.29      www      3117: 
1.52      www      3118:     my $thisallowed='';
                   3119:     my $statecond=0;
                   3120:     my $courseprivid='';
                   3121: 
                   3122: # Course
                   3123: 
1.620     albertel 3124:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3125:        $thisallowed.=$1;
                   3126:     }
1.29      www      3127: 
1.52      www      3128: # Domain
                   3129: 
1.620     albertel 3130:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3131:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3132:        $thisallowed.=$1;
                   3133:     }
1.52      www      3134: 
                   3135: # Course: uri itself is a course
1.66      www      3136:     my $courseuri=$uri;
                   3137:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3138:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3139: 
1.620     albertel 3140:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3141:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3142:        $thisallowed.=$1;
                   3143:     }
1.29      www      3144: 
1.678     raeburn  3145: # Group: uri itself is a group
                   3146:     my $groupuri=$uri;
                   3147:     $groupuri=~s/^([^\/])/\/$1/;
                   3148:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3149:        =~/\Q$priv\E\&([^\:]*)/) {
                   3150:        $thisallowed.=$1;
                   3151:     }
                   3152: 
1.665     albertel 3153: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3154: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3155:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3156: 	$thisallowed='';
1.671     raeburn  3157:         my ($match)=&is_on_map($uri);
                   3158:         if ($match) {
                   3159:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3160:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3161:                 $thisallowed.=$1;
                   3162:             }
                   3163:         } else {
                   3164:             my $refuri=$env{'httpref.'.$orguri};
                   3165:             if ($refuri) {
                   3166:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3167:                     $thisallowed='F';
1.671     raeburn  3168:                 } else {
                   3169:                     $refuri=&declutter($refuri);
                   3170:                     my ($match) = &is_on_map($refuri);
                   3171:                     if ($match) {
                   3172:                         $thisallowed='F';
                   3173:                     }
1.669     raeburn  3174:                 }
1.671     raeburn  3175:             }
                   3176:         }
1.314     www      3177:     }
1.492     albertel 3178: 
1.52      www      3179: # Full access at system, domain or course-wide level? Exit.
1.29      www      3180: 
                   3181:     if ($thisallowed=~/F/) {
                   3182: 	return 'F';
                   3183:     }
                   3184: 
1.52      www      3185: # If this is generating or modifying users, exit with special codes
1.29      www      3186: 
1.643     www      3187:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3188: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3189: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3190: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3191: 	    unless ($auname) { return $thisallowed; }
                   3192: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3193: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3194: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3195: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3196: 	}
1.52      www      3197: 	return $thisallowed;
                   3198:     }
                   3199: #
1.103     harris41 3200: # Gathered so far: system, domain and course wide privileges
1.52      www      3201: #
                   3202: # Course: See if uri or referer is an individual resource that is part of 
                   3203: # the course
                   3204: 
1.620     albertel 3205:     if ($env{'request.course.id'}) {
1.232     www      3206: 
1.620     albertel 3207:        $courseprivid=$env{'request.course.id'};
                   3208:        if ($env{'request.course.sec'}) {
                   3209:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3210:        }
                   3211:        $courseprivid=~s/\_/\//;
                   3212:        my $checkreferer=1;
1.232     www      3213:        my ($match,$cond)=&is_on_map($uri);
                   3214:        if ($match) {
                   3215:            $statecond=$cond;
1.620     albertel 3216:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3217:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3218:                $thisallowed.=$1;
                   3219:                $checkreferer=0;
                   3220:            }
1.29      www      3221:        }
1.83      www      3222:        
1.148     www      3223:        if ($checkreferer) {
1.620     albertel 3224: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3225:             unless ($refuri) {
1.620     albertel 3226:                 foreach (keys %env) {
1.148     www      3227: 		    if ($_=~/^httpref\..*\*/) {
                   3228: 			my $pattern=$_;
1.156     www      3229:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3230:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3231:                         $pattern=~s/\//\\\//g;
1.152     www      3232:                         if ($orguri=~/$pattern/) {
1.620     albertel 3233: 			    $refuri=$env{$_};
1.148     www      3234:                         }
                   3235:                     }
1.191     harris41 3236:                 }
1.148     www      3237:             }
1.232     www      3238: 
1.148     www      3239:          if ($refuri) { 
1.152     www      3240: 	  $refuri=&declutter($refuri);
1.232     www      3241:           my ($match,$cond)=&is_on_map($refuri);
                   3242:             if ($match) {
                   3243:               my $refstatecond=$cond;
1.620     albertel 3244:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3245:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3246:                   $thisallowed.=$1;
1.53      www      3247:                   $uri=$refuri;
                   3248:                   $statecond=$refstatecond;
1.52      www      3249:               }
                   3250:           }
1.148     www      3251:         }
1.29      www      3252:        }
1.52      www      3253:    }
1.29      www      3254: 
1.52      www      3255: #
1.103     harris41 3256: # Gathered now: all privileges that could apply, and condition number
1.52      www      3257: # 
                   3258: #
                   3259: # Full or no access?
                   3260: #
1.29      www      3261: 
1.52      www      3262:     if ($thisallowed=~/F/) {
                   3263: 	return 'F';
                   3264:     }
1.29      www      3265: 
1.52      www      3266:     unless ($thisallowed) {
                   3267:         return '';
                   3268:     }
1.29      www      3269: 
1.52      www      3270: # Restrictions exist, deal with them
                   3271: #
                   3272: #   C:according to course preferences
                   3273: #   R:according to resource settings
                   3274: #   L:unless locked
                   3275: #   X:according to user session state
                   3276: #
                   3277: 
                   3278: # Possibly locked functionality, check all courses
1.54      www      3279: # Locks might take effect only after 10 minutes cache expiration for other
                   3280: # courses, and 2 minutes for current course
1.52      www      3281: 
                   3282:     my $envkey;
                   3283:     if ($thisallowed=~/L/) {
1.620     albertel 3284:         foreach $envkey (keys %env) {
1.54      www      3285:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3286:                my $courseid=$2;
                   3287:                my $roleid=$1.'.'.$2;
1.92      www      3288:                $courseid=~s/^\///;
1.54      www      3289:                my $expiretime=600;
1.620     albertel 3290:                if ($env{'request.role'} eq $roleid) {
1.54      www      3291: 		  $expiretime=120;
                   3292:                }
                   3293: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3294:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3295:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      3296: 		   &coursedescription($courseid);
                   3297:                }
1.620     albertel 3298:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3299:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3300: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3301:                        &log($env{'user.domain'},$env{'user.name'},
                   3302:                             $env{'user.home'},
1.57      www      3303:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3304:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3305:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3306: 		       return '';
                   3307:                    }
                   3308:                }
1.620     albertel 3309:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3310:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3311: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3312:                        &log($env{'user.domain'},$env{'user.name'},
                   3313:                             $env{'user.home'},
1.57      www      3314:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3315:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3316:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3317: 		       return '';
                   3318:                    }
                   3319:                }
                   3320: 	   }
1.29      www      3321:        }
1.52      www      3322:     }
                   3323:    
                   3324: #
                   3325: # Rest of the restrictions depend on selected course
                   3326: #
                   3327: 
1.620     albertel 3328:     unless ($env{'request.course.id'}) {
1.52      www      3329:        return '1';
                   3330:     }
1.29      www      3331: 
1.52      www      3332: #
                   3333: # Now user is definitely in a course
                   3334: #
1.53      www      3335: 
                   3336: 
                   3337: # Course preferences
                   3338: 
                   3339:    if ($thisallowed=~/C/) {
1.620     albertel 3340:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3341:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3342:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3343: 	   =~/\Q$rolecode\E/) {
1.673     albertel 3344:            &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
1.57      www      3345:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.620     albertel 3346:                 $env{'request.course.id'});
1.237     www      3347:            return '';
                   3348:        }
                   3349: 
1.620     albertel 3350:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3351: 	   =~/\Q$unamedom\E/) {
1.673     albertel 3352:            &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
1.237     www      3353:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.620     albertel 3354:                 $env{'request.course.id'});
1.54      www      3355:            return '';
                   3356:        }
1.53      www      3357:    }
                   3358: 
                   3359: # Resource preferences
                   3360: 
                   3361:    if ($thisallowed=~/R/) {
1.620     albertel 3362:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3363:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.673     albertel 3364: 	   &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3365: 		'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      3366:           return '';
1.54      www      3367:        }
1.53      www      3368:    }
1.30      www      3369: 
1.246     www      3370: # Restricted by state or randomout?
1.30      www      3371: 
1.52      www      3372:    if ($thisallowed=~/X/) {
1.620     albertel 3373:       if ($env{'acc.randomout'}) {
1.579     albertel 3374: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3375:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3376:             return ''; 
                   3377:          }
1.247     www      3378:       }
                   3379:       if (&condval($statecond)) {
1.52      www      3380: 	 return '2';
                   3381:       } else {
                   3382:          return '';
                   3383:       }
                   3384:    }
1.30      www      3385: 
1.52      www      3386:    return 'F';
1.232     www      3387: }
                   3388: 
                   3389: # --------------------------------------------------- Is a resource on the map?
                   3390: 
                   3391: sub is_on_map {
1.659     albertel 3392:     my $uri=&deversion(&declutter(shift));
1.232     www      3393:     my @uriparts=split(/\//,$uri);
                   3394:     my $filename=$uriparts[$#uriparts];
                   3395:     my $pathname=$uri;
1.289     bowersj2 3396:     $pathname=~s|/\Q$filename\E$||;
1.332     www      3397:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 3398:     #Trying to find the conditional for the file
1.620     albertel 3399:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3400: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3401:     if ($match) {
1.289     bowersj2 3402: 	return (1,$1);
                   3403:     } else {
1.434     www      3404: 	return (0,0);
1.289     bowersj2 3405:     }
1.12      www      3406: }
                   3407: 
1.427     www      3408: # --------------------------------------------------------- Get symb from alias
                   3409: 
                   3410: sub get_symb_from_alias {
                   3411:     my $symb=shift;
                   3412:     my ($map,$resid,$url)=&decode_symb($symb);
                   3413: # Already is a symb
                   3414:     if ($url) { return $symb; }
                   3415: # Must be an alias
                   3416:     my $aliassymb='';
                   3417:     my %bighash;
1.620     albertel 3418:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3419:                             &GDBM_READER(),0640)) {
                   3420:         my $rid=$bighash{'mapalias_'.$symb};
                   3421: 	if ($rid) {
                   3422: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3423: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3424: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3425: 	}
                   3426:         untie %bighash;
                   3427:     }
                   3428:     return $aliassymb;
                   3429: }
                   3430: 
1.12      www      3431: # ----------------------------------------------------------------- Define Role
                   3432: 
                   3433: sub definerole {
                   3434:   if (allowed('mcr','/')) {
                   3435:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3436:     foreach (split(':',$sysrole)) {
1.21      www      3437: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3438:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3439:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3440: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3441:                return "refused:s:$crole&$cqual"; 
                   3442:             }
                   3443:         }
1.191     harris41 3444:     }
1.392     www      3445:     foreach (split(':',$domrole)) {
1.21      www      3446: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3447:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3448:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3449: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3450:                return "refused:d:$crole&$cqual"; 
                   3451:             }
                   3452:         }
1.191     harris41 3453:     }
1.392     www      3454:     foreach (split(':',$courole)) {
1.21      www      3455: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3456:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3457:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3458: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3459:                return "refused:c:$crole&$cqual"; 
                   3460:             }
                   3461:         }
1.191     harris41 3462:     }
1.620     albertel 3463:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3464:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3465: 	        "rolesdef_$rolename=".
                   3466:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3467:     return reply($command,$env{'user.home'});
1.12      www      3468:   } else {
                   3469:     return 'refused';
                   3470:   }
1.105     harris41 3471: }
                   3472: 
                   3473: # ---------------- Make a metadata query against the network of library servers
                   3474: 
                   3475: sub metadata_query {
1.244     matthew  3476:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3477:     my %rhash;
1.244     matthew  3478:     my @server_list = (defined($server_array) ? @$server_array
                   3479:                                               : keys(%libserv) );
                   3480:     for my $server (@server_list) {
1.118     harris41 3481: 	unless ($custom or $customshow) {
                   3482: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3483: 	    $rhash{$server}=$reply;
                   3484: 	}
                   3485: 	else {
                   3486: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3487: 			     &escape($custom).':'.&escape($customshow),
                   3488: 			     $server);
                   3489: 	    $rhash{$server}=$reply;
                   3490: 	}
1.112     harris41 3491:     }
1.118     harris41 3492:     return \%rhash;
1.240     www      3493: }
                   3494: 
                   3495: # ----------------------------------------- Send log queries and wait for reply
                   3496: 
                   3497: sub log_query {
                   3498:     my ($uname,$udom,$query,%filters)=@_;
                   3499:     my $uhome=&homeserver($uname,$udom);
                   3500:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3501:     my $uhost=$hostname{$uhome};
1.241     www      3502:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3503:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3504:                        $uhome);
1.479     albertel 3505:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3506:     return get_query_reply($queryid);
                   3507: }
                   3508: 
1.508     raeburn  3509: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3510: 
                   3511: sub fetch_enrollment_query {
1.511     raeburn  3512:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3513:     my $homeserver;
1.547     raeburn  3514:     my $maxtries = 1;
1.508     raeburn  3515:     if ($context eq 'automated') {
                   3516:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3517:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3518:     } else {
                   3519:         $homeserver = &homeserver($cnum,$dom);
                   3520:     }
1.506     raeburn  3521:     my $host=$hostname{$homeserver};
                   3522:     my $cmd = '';
                   3523:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3524:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3525:     }
                   3526:     $cmd =~ s/%%$//;
                   3527:     $cmd = &escape($cmd);
                   3528:     my $query = 'fetchenrollment';
1.620     albertel 3529:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3530:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3531:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3532:         return 'error: '.$queryid;
                   3533:     }
1.506     raeburn  3534:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3535:     my $tries = 1;
                   3536:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3537:         $reply = &get_query_reply($queryid);
                   3538:         $tries ++;
                   3539:     }
1.526     raeburn  3540:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3541:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3542:     } else {
1.515     raeburn  3543:         my @responses = split/:/,$reply;
                   3544:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3545:             foreach (@responses) {
                   3546:                 my ($key,$value) = split/=/,$_;
                   3547:                 $$replyref{$key} = $value;
                   3548:             }
                   3549:         } else {
1.506     raeburn  3550:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3551:             foreach (@responses) {
                   3552:                 my ($key,$value) = split/=/,$_;
                   3553:                 $$replyref{$key} = $value;
                   3554:                 if ($value > 0) {
                   3555:                     foreach (@{$$affiliatesref{$key}}) {
                   3556:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3557:                         my $destname = $pathname.'/'.$filename;
                   3558:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3559:                         if ($xml_classlist =~ /^error/) {
                   3560:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3561:                         } else {
1.506     raeburn  3562:                             if ( open(FILE,">$destname") ) {
                   3563:                                 print FILE &unescape($xml_classlist);
                   3564:                                 close(FILE);
1.526     raeburn  3565:                             } else {
                   3566:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3567:                             }
                   3568:                         }
                   3569:                     }
                   3570:                 }
                   3571:             }
                   3572:         }
                   3573:         return 'ok';
                   3574:     }
                   3575:     return 'error';
                   3576: }
                   3577: 
1.242     www      3578: sub get_query_reply {
                   3579:     my $queryid=shift;
1.240     www      3580:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3581:     my $reply='';
                   3582:     for (1..100) {
                   3583: 	sleep 2;
                   3584:         if (-e $replyfile.'.end') {
1.448     albertel 3585: 	    if (open(my $fh,$replyfile)) {
1.240     www      3586:                $reply.=<$fh>;
1.448     albertel 3587:                close($fh);
1.240     www      3588: 	   } else { return 'error: reply_file_error'; }
1.242     www      3589:            return &unescape($reply);
                   3590: 	}
1.240     www      3591:     }
1.242     www      3592:     return 'timeout:'.$queryid;
1.240     www      3593: }
                   3594: 
                   3595: sub courselog_query {
1.241     www      3596: #
                   3597: # possible filters:
                   3598: # url: url or symb
                   3599: # username
                   3600: # domain
                   3601: # action: view, submit, grade
                   3602: # start: timestamp
                   3603: # end: timestamp
                   3604: #
1.240     www      3605:     my (%filters)=@_;
1.620     albertel 3606:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3607:     if ($filters{'url'}) {
                   3608: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3609:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3610:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3611:     }
1.620     albertel 3612:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3613:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3614:     return &log_query($cname,$cdom,'courselog',%filters);
                   3615: }
                   3616: 
                   3617: sub userlog_query {
                   3618:     my ($uname,$udom,%filters)=@_;
                   3619:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3620: }
                   3621: 
1.506     raeburn  3622: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3623: 
                   3624: sub auto_run {
1.508     raeburn  3625:     my ($cnum,$cdom) = @_;
                   3626:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3627:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3628:     return $response;
                   3629: }
                   3630:                                                                                    
                   3631: sub auto_get_sections {
1.508     raeburn  3632:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3633:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3634:     my @secs = ();
1.511     raeburn  3635:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3636:     unless ($response eq 'refused') {
                   3637:         @secs = split/:/,$response;
                   3638:     }
                   3639:     return @secs;
                   3640: }
                   3641:                                                                                    
                   3642: sub auto_new_course {
1.508     raeburn  3643:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3644:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3645:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3646:     return $response;
                   3647: }
                   3648:                                                                                    
                   3649: sub auto_validate_courseID {
1.508     raeburn  3650:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3651:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3652:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3653:     return $response;
                   3654: }
                   3655:                                                                                    
                   3656: sub auto_create_password {
1.508     raeburn  3657:     my ($cnum,$cdom,$authparam) = @_;
                   3658:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3659:     my $create_passwd = 0;
                   3660:     my $authchk = '';
1.511     raeburn  3661:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3662:     if ($response eq 'refused') {
                   3663:         $authchk = 'refused';
                   3664:     } else {
                   3665:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3666:     }
                   3667:     return ($authparam,$create_passwd,$authchk);
                   3668: }
                   3669: 
1.521     raeburn  3670: sub auto_instcode_format {
                   3671:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3672:     my $courses = '';
                   3673:     my $homeserver;
                   3674:     if ($caller eq 'global') {
1.584     raeburn  3675:         foreach my $tryserver (keys %libserv) {
                   3676:             if ($hostdom{$tryserver} eq $codedom) {
                   3677:                 $homeserver = $tryserver;
                   3678:                 last;
                   3679:             }
                   3680:         }
1.620     albertel 3681:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3682:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3683:         }
1.521     raeburn  3684:     } else {
                   3685:         $homeserver = &homeserver($caller,$codedom);
                   3686:     }
                   3687:     foreach (keys %{$instcodes}) {
                   3688:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3689:     }
                   3690:     chop($courses);
                   3691:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3692:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3693:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3694:         %{$codes} = &str2hash($codes_str);
                   3695:         @{$codetitles} = &str2array($codetitles_str);
                   3696:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3697:         %{$cat_order} = &str2hash($cat_order_str);
                   3698:         return 'ok';
                   3699:     }
                   3700:     return $response;
                   3701: }
                   3702: 
1.679     raeburn  3703: # ------------------------------------------------------- Course Group routines
                   3704: 
                   3705: sub get_coursegroups {
                   3706:     my ($cdom,$cnum,$curr_groups,$group) = @_;
                   3707:     my $numgroups = 0;
                   3708:     %{$curr_groups} = &dump('coursegroups',$cdom,$cnum,$group);
                   3709:     my ($tmp)=keys(%{$curr_groups});
                   3710:     if ($tmp eq 'error: 2 tie(GDBM) Failed while attempting dump') {
                   3711:         my %emptyhash = ();
                   3712:         if (&put('coursegroups',\%emptyhash,$cdom,$cnum) eq 'ok') {
                   3713:             %{$curr_groups} = &dump('coursegroups',$cdom,$cnum,$group);
                   3714:             $tmp=keys(%{$curr_groups});
                   3715:         }
                   3716:     }
                   3717:     if ($tmp=~/^error:/) {
                   3718:         &logthis('Error retrieving groups: '.$tmp.' in '.$cnum.':'.$cdom);
                   3719:     } else {
                   3720:         my @groups = keys(%{$curr_groups});
                   3721:         $numgroups = @groups;
                   3722:     }
                   3723:     return $numgroups;
                   3724: }
                   3725: 
                   3726: sub modify_coursegroup {
                   3727:     my ($cdom,$cnum,$groupsettings) = @_;
                   3728:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3729: }
                   3730: 
                   3731: sub modify_group_roles {
                   3732:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3733:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3734:     my $role = 'gr/'.&escape($userprivs);
                   3735:     my ($uname,$udom) = split(/:/,$user);
                   3736:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
                   3737:     return $result;
                   3738: }
                   3739: 
                   3740: sub modify_coursegroup_membership {
                   3741:     my ($cdom,$cnum,$membership) = @_;
                   3742:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3743:     return $result;
                   3744: }
                   3745: 
1.12      www      3746: # ------------------------------------------------------------------ Plain Text
                   3747: 
                   3748: sub plaintext {
1.22      www      3749:     my $short=shift;
1.676     albertel 3750:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      3751: }
                   3752: 
                   3753: # ----------------------------------------------------------------- Assign Role
                   3754: 
                   3755: sub assignrole {
1.357     www      3756:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      3757:     my $mrole;
                   3758:     if ($role =~ /^cr\//) {
1.393     www      3759:         my $cwosec=$url;
                   3760:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3761: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      3762:            &logthis('Refused custom assignrole: '.
                   3763:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3764: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3765:            return 'refused'; 
                   3766:         }
1.21      www      3767:         $mrole='cr';
1.678     raeburn  3768:     } elsif ($role =~ /^gr\//) {
                   3769:         my $cwogrp=$url;
                   3770:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3771:         unless (&allowed('mdg',$cwogrp)) {
                   3772:             &logthis('Refused group assignrole: '.
                   3773:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   3774:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   3775:             return 'refused';
                   3776:         }
                   3777:         $mrole='gr';
1.21      www      3778:     } else {
1.82      www      3779:         my $cwosec=$url;
1.83      www      3780:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      3781:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      3782:            &logthis('Refused assignrole: '.
                   3783:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3784: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3785:            return 'refused'; 
                   3786:         }
1.21      www      3787:         $mrole=$role;
                   3788:     }
1.620     albertel 3789:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3790:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      3791:     if ($end) { $command.='_'.$end; }
1.21      www      3792:     if ($start) {
                   3793: 	if ($end) { 
1.81      www      3794:            $command.='_'.$start; 
1.21      www      3795:         } else {
1.81      www      3796:            $command.='_0_'.$start;
1.21      www      3797:         }
                   3798:     }
1.357     www      3799: # actually delete
                   3800:     if ($deleteflag) {
1.373     www      3801: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      3802: # modify command to delete the role
1.620     albertel 3803:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      3804:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 3805: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      3806: # set start and finish to negative values for userrolelog
                   3807:            $start=-1;
                   3808:            $end=-1;
                   3809:         }
                   3810:     }
                   3811: # send command
1.349     www      3812:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      3813: # log new user role if status is ok
1.349     www      3814:     if ($answer eq 'ok') {
1.663     raeburn  3815: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.349     www      3816:     }
                   3817:     return $answer;
1.169     harris41 3818: }
                   3819: 
                   3820: # -------------------------------------------------- Modify user authentication
1.197     www      3821: # Overrides without validation
                   3822: 
1.169     harris41 3823: sub modifyuserauth {
                   3824:     my ($udom,$uname,$umode,$upass)=@_;
                   3825:     my $uhome=&homeserver($uname,$udom);
1.197     www      3826:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   3827:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 3828:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3829:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 3830:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   3831: 		     &escape($upass),$uhome);
1.620     albertel 3832:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      3833:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   3834:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   3835:     &log($udom,,$uname,$uhome,
1.620     albertel 3836:         'Authentication changed by '.$env{'user.domain'}.', '.
                   3837:                                      $env{'user.name'}.', '.$umode.
1.197     www      3838:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 3839:     unless ($reply eq 'ok') {
1.197     www      3840:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 3841: 	return 'error: '.$reply;
                   3842:     }   
1.170     harris41 3843:     return 'ok';
1.80      www      3844: }
                   3845: 
1.81      www      3846: # --------------------------------------------------------------- Modify a user
1.80      www      3847: 
1.81      www      3848: sub modifyuser {
1.206     matthew  3849:     my ($udom,    $uname, $uid,
                   3850:         $umode,   $upass, $first,
                   3851:         $middle,  $last,  $gene,
1.387     www      3852:         $forceid, $desiredhome, $email)=@_;
1.198     www      3853:     $udom=~s/\W//g;
                   3854:     $uname=~s/\W//g;
1.81      www      3855:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3856:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  3857: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   3858:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   3859:                                      ' desiredhome not specified'). 
1.620     albertel 3860:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3861:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 3862:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      3863: # ----------------------------------------------------------------- Create User
1.406     albertel 3864:     if (($uhome eq 'no_host') && 
                   3865: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      3866:         my $unhome='';
1.209     matthew  3867:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   3868:             $unhome = $desiredhome;
1.620     albertel 3869: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   3870: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  3871:         } else { # load balancing routine for determining $unhome
1.80      www      3872:             my $tryserver;
1.81      www      3873:             my $loadm=10000000;
1.80      www      3874:             foreach $tryserver (keys %libserv) {
                   3875: 	       if ($hostdom{$tryserver} eq $udom) {
                   3876:                   my $answer=reply('load',$tryserver);
                   3877:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   3878: 		      $loadm=$answer;
                   3879:                       $unhome=$tryserver;
                   3880:                   }
                   3881: 	       }
                   3882: 	    }
                   3883:         }
                   3884:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  3885: 	    return 'error: unable to find a home server for '.$uname.
                   3886:                    ' in domain '.$udom;
1.80      www      3887:         }
                   3888:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   3889:                          &escape($upass),$unhome);
                   3890: 	unless ($reply eq 'ok') {
                   3891:             return 'error: '.$reply;
                   3892:         }   
1.230     stredwic 3893:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      3894:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  3895: 	    return 'error: unable verify users home machine.';
1.80      www      3896:         }
1.209     matthew  3897:     }   # End of creation of new user
1.80      www      3898: # ---------------------------------------------------------------------- Add ID
                   3899:     if ($uid) {
                   3900:        $uid=~tr/A-Z/a-z/;
                   3901:        my %uidhash=&idrget($udom,$uname);
1.196     www      3902:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   3903:          && (!$forceid)) {
1.80      www      3904: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  3905: 	      return 'error: user id "'.$uid.'" does not match '.
                   3906:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      3907:           }
                   3908:        } else {
                   3909: 	  &idput($udom,($uname => $uid));
                   3910:        }
                   3911:     }
                   3912: # -------------------------------------------------------------- Add names, etc
1.313     matthew  3913:     my @tmp=&get('environment',
1.134     albertel 3914: 		   ['firstname','middlename','lastname','generation'],
                   3915: 		   $udom,$uname);
1.313     matthew  3916:     my %names;
                   3917:     if ($tmp[0] =~ m/^error:.*/) { 
                   3918:         %names=(); 
                   3919:     } else {
                   3920:         %names = @tmp;
                   3921:     }
1.388     www      3922: #
                   3923: # Make sure to not trash student environment if instructor does not bother
                   3924: # to supply name and email information
                   3925: #
                   3926:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  3927:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      3928:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  3929:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      3930:     if ($email) {
                   3931:        $email=~s/[^\w\@\.\-\,]//gs;
                   3932:        if ($email=~/\@/) { $names{'notification'} = $email;
                   3933: 			   $names{'critnotification'} = $email;
                   3934: 			   $names{'permanentemail'} = $email; }
                   3935:     }
1.134     albertel 3936:     my $reply = &put('environment', \%names, $udom,$uname);
                   3937:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      3938:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      3939:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3940:              $umode.', '.$first.', '.$middle.', '.
                   3941: 	     $last.', '.$gene.' by '.
1.620     albertel 3942:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 3943:     return 'ok';
1.80      www      3944: }
                   3945: 
1.81      www      3946: # -------------------------------------------------------------- Modify student
1.80      www      3947: 
1.81      www      3948: sub modifystudent {
                   3949:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  3950:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 3951:     if (!$cid) {
1.620     albertel 3952: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3953: 	    return 'not_in_class';
                   3954: 	}
1.80      www      3955:     }
                   3956: # --------------------------------------------------------------- Make the user
1.81      www      3957:     my $reply=&modifyuser
1.209     matthew  3958: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      3959:          $desiredhome,$email);
1.80      www      3960:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  3961:     # This will cause &modify_student_enrollment to get the uid from the
                   3962:     # students environment
                   3963:     $uid = undef if (!$forceid);
1.455     albertel 3964:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  3965: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  3966:     return $reply;
                   3967: }
                   3968: 
                   3969: sub modify_student_enrollment {
1.515     raeburn  3970:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 3971:     my ($cdom,$cnum,$chome);
                   3972:     if (!$cid) {
1.620     albertel 3973: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3974: 	    return 'not_in_class';
                   3975: 	}
1.620     albertel 3976: 	$cdom=$env{'course.'.$cid.'.domain'};
                   3977: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 3978:     } else {
                   3979: 	($cdom,$cnum)=split(/_/,$cid);
                   3980:     }
1.620     albertel 3981:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 3982:     if (!$chome) {
1.457     raeburn  3983: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  3984:     }
1.455     albertel 3985:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  3986:     # Make sure the user exists
1.81      www      3987:     my $uhome=&homeserver($uname,$udom);
                   3988:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3989: 	return 'error: no such user';
                   3990:     }
1.297     matthew  3991:     # Get student data if we were not given enough information
                   3992:     if (!defined($first)  || $first  eq '' || 
                   3993:         !defined($last)   || $last   eq '' || 
                   3994:         !defined($uid)    || $uid    eq '' || 
                   3995:         !defined($middle) || $middle eq '' || 
                   3996:         !defined($gene)   || $gene   eq '') {
1.294     matthew  3997:         # They did not supply us with enough data to enroll the student, so
                   3998:         # we need to pick up more information.
1.297     matthew  3999:         my %tmp = &get('environment',
1.294     matthew  4000:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4001:                        ,$udom,$uname);
                   4002: 
1.455     albertel 4003:         #foreach (keys(%tmp)) {
                   4004:         #    &logthis("key $_ = ".$tmp{$_});
                   4005:         #}
1.294     matthew  4006:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4007:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4008:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4009:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4010:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4011:     }
1.556     albertel 4012:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4013:     my $reply=cput('classlist',
                   4014: 		   {"$uname:$udom" => 
1.515     raeburn  4015: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4016: 		   $cdom,$cnum);
1.81      www      4017:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4018: 	return 'error: '.$reply;
1.652     albertel 4019:     } else {
                   4020: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4021:     }
1.297     matthew  4022:     # Add student role to user
1.83      www      4023:     my $uurl='/'.$cid;
1.81      www      4024:     $uurl=~s/\_/\//g;
                   4025:     if ($usec) {
                   4026: 	$uurl.='/'.$usec;
                   4027:     }
                   4028:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4029: }
                   4030: 
1.556     albertel 4031: sub format_name {
                   4032:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4033:     my $name;
                   4034:     if ($first ne 'lastname') {
                   4035: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4036:     } else {
                   4037: 	if ($lastname=~/\S/) {
                   4038: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4039: 	    $name=~s/\s+,/,/;
                   4040: 	} else {
                   4041: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4042: 	}
                   4043:     }
                   4044:     $name=~s/^\s+//;
                   4045:     $name=~s/\s+$//;
                   4046:     $name=~s/\s+/ /g;
                   4047:     return $name;
                   4048: }
                   4049: 
1.84      www      4050: # ------------------------------------------------- Write to course preferences
                   4051: 
                   4052: sub writecoursepref {
                   4053:     my ($courseid,%prefs)=@_;
                   4054:     $courseid=~s/^\///;
                   4055:     $courseid=~s/\_/\//g;
                   4056:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4057:     my $chome=homeserver($cnum,$cdomain);
                   4058:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4059: 	return 'error: no such course';
                   4060:     }
                   4061:     my $cstring='';
1.191     harris41 4062:     foreach (keys %prefs) {
1.84      www      4063: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4064:     }
1.84      www      4065:     $cstring=~s/\&$//;
                   4066:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4067: }
                   4068: 
                   4069: # ---------------------------------------------------------- Make/modify course
                   4070: 
                   4071: sub createcourse {
1.571     raeburn  4072:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4073:     $url=&declutter($url);
                   4074:     my $cid='';
1.264     matthew  4075:     unless (&allowed('ccc',$udom)) {
1.84      www      4076:         return 'refused';
                   4077:     }
                   4078: # ------------------------------------------------------------------- Create ID
1.674     www      4079:    my $uname=int(1+rand(9)).
                   4080:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4081:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4082:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4083: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4084:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4085:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4086:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4087:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4088:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4089:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4090:            return 'error: unable to generate unique course-ID';
                   4091:        } 
                   4092:    }
1.264     matthew  4093: # ------------------------------------------------ Check supplied server name
1.620     albertel 4094:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4095:     if (! exists($libserv{$course_server})) {
                   4096:         return 'error:bad server name '.$course_server;
                   4097:     }
1.84      www      4098: # ------------------------------------------------------------- Make the course
                   4099:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4100:                       $course_server);
1.84      www      4101:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4102:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4103:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4104: 	return 'error: no such course';
                   4105:     }
1.271     www      4106: # ----------------------------------------------------------------- Course made
1.516     raeburn  4107: # log existence
                   4108:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4109:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4110:     &flushcourselogs();
                   4111: # set toplevel url
1.271     www      4112:     my $topurl=$url;
                   4113:     unless ($nonstandard) {
                   4114: # ------------------------------------------ For standard courses, make top url
                   4115:         my $mapurl=&clutter($url);
1.278     www      4116:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4117:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4118: <map>
                   4119: <resource id="1" type="start"></resource>
                   4120: <resource id="2" src="$mapurl"></resource>
                   4121: <resource id="3" type="finish"></resource>
                   4122: <link index="1" from="1" to="2"></link>
                   4123: <link index="2" from="2" to="3"></link>
                   4124: </map>
                   4125: ENDINITMAP
                   4126:         $topurl=&declutter(
1.638     albertel 4127:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4128:                           );
                   4129:     }
                   4130: # ----------------------------------------------------------- Write preferences
1.84      www      4131:     &writecoursepref($udom.'_'.$uname,
                   4132:                      ('description' => $description,
1.271     www      4133:                       'url'         => $topurl));
1.84      www      4134:     return '/'.$udom.'/'.$uname;
                   4135: }
                   4136: 
1.21      www      4137: # ---------------------------------------------------------- Assign Custom Role
                   4138: 
                   4139: sub assigncustomrole {
1.357     www      4140:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4141:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4142:                        $end,$start,$deleteflag);
1.21      www      4143: }
                   4144: 
                   4145: # ----------------------------------------------------------------- Revoke Role
                   4146: 
                   4147: sub revokerole {
1.357     www      4148:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4149:     my $now=time;
1.357     www      4150:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4151: }
                   4152: 
                   4153: # ---------------------------------------------------------- Revoke Custom Role
                   4154: 
                   4155: sub revokecustomrole {
1.357     www      4156:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4157:     my $now=time;
1.357     www      4158:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4159:            $deleteflag);
1.17      www      4160: }
                   4161: 
1.533     banghart 4162: # ------------------------------------------------------------ Disk usage
1.535     albertel 4163: sub diskusage {
1.533     banghart 4164:     my ($udom,$uname,$directoryRoot)=@_;
                   4165:     $directoryRoot =~ s/\/$//;
1.535     albertel 4166:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4167:     return $listing;
1.512     banghart 4168: }
                   4169: 
1.566     banghart 4170: sub is_locked {
                   4171:     my ($file_name, $domain, $user) = @_;
                   4172:     my @check;
                   4173:     my $is_locked;
                   4174:     push @check, $file_name;
1.613     albertel 4175:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4176: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4177:     my ($tmp)=keys(%locked);
                   4178:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4179: 
1.566     banghart 4180:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4181:         $is_locked = 'true';
                   4182:     } else {
                   4183:         $is_locked = 'false';
                   4184:     }
                   4185: }
                   4186: 
1.559     banghart 4187: # ------------------------------------------------------------- Mark as Read Only
                   4188: 
                   4189: sub mark_as_readonly {
                   4190:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4191:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4192:     my ($tmp)=keys(%current_permissions);
                   4193:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4194:     foreach my $file (@{$files}) {
1.561     banghart 4195:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4196:     }
1.613     albertel 4197:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4198:     return;
                   4199: }
                   4200: 
1.572     banghart 4201: # ------------------------------------------------------------Save Selected Files
                   4202: 
                   4203: sub save_selected_files {
                   4204:     my ($user, $path, @files) = @_;
                   4205:     my $filename = $user."savedfiles";
1.573     banghart 4206:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4207:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4208:     foreach my $file (@files) {
1.620     albertel 4209:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4210:     }
                   4211:     foreach my $file (@other_files) {
1.574     banghart 4212:         print (OUT $file."\n");
1.572     banghart 4213:     }
1.574     banghart 4214:     close (OUT);
1.572     banghart 4215:     return 'ok';
                   4216: }
                   4217: 
1.574     banghart 4218: sub clear_selected_files {
                   4219:     my ($user) = @_;
                   4220:     my $filename = $user."savedfiles";
                   4221:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4222:     print (OUT undef);
                   4223:     close (OUT);
                   4224:     return ("ok");    
                   4225: }
                   4226: 
1.572     banghart 4227: sub files_in_path {
                   4228:     my ($user, $path) = @_;
                   4229:     my $filename = $user."savedfiles";
                   4230:     my %return_files;
1.574     banghart 4231:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4232:     while (my $line_in = <IN>) {
1.574     banghart 4233:         chomp ($line_in);
                   4234:         my @paths_and_file = split (m!/!, $line_in);
                   4235:         my $file_part = pop (@paths_and_file);
                   4236:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4237:         $path_part.='/';
                   4238:         my $path_and_file = $path_part.$file_part;
                   4239:         if ($path_part eq $path) {
                   4240:             $return_files{$file_part}= 'selected';
                   4241:         }
                   4242:     }
1.574     banghart 4243:     close (IN);
                   4244:     return (\%return_files);
1.572     banghart 4245: }
                   4246: 
                   4247: # called in portfolio select mode, to show files selected NOT in current directory
                   4248: sub files_not_in_path {
                   4249:     my ($user, $path) = @_;
                   4250:     my $filename = $user."savedfiles";
                   4251:     my @return_files;
                   4252:     my $path_part;
1.574     banghart 4253:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4254:     while (<IN>) {
                   4255:         #ok, I know it's clunky, but I want it to work
                   4256:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4257:         my $file_part = pop (@paths_and_file);
                   4258:         chomp ($file_part);
                   4259:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4260:         $path_part .= '/';
                   4261:         my $path_and_file = $path_part.$file_part;
                   4262:         if ($path_part ne $path) {
1.574     banghart 4263:             push (@return_files, ($path_and_file));
1.572     banghart 4264:         }
                   4265:     }
1.574     banghart 4266:     close (OUT);
                   4267:     return (@return_files);
1.572     banghart 4268: }
                   4269: 
1.561     banghart 4270: #--------------------------------------------------------------Get Marked as Read Only
                   4271: 
1.629     banghart 4272: 
1.561     banghart 4273: sub get_marked_as_readonly {
                   4274:     my ($domain,$user,$what) = @_;
1.613     albertel 4275:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4276:     my ($tmp)=keys(%current_permissions);
                   4277:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4278:     my @readonly_files;
1.629     banghart 4279:     my $cmp1=$what;
                   4280:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4281:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4282:         if (ref($value) eq "ARRAY"){
                   4283:             foreach my $stored_what (@{$value}) {
1.629     banghart 4284:                 my $cmp2=$stored_what;
                   4285:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4286:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4287:                     push(@readonly_files, $file_name);
1.563     banghart 4288:                 } elsif (!defined($what)) {
                   4289:                     push(@readonly_files, $file_name);
1.561     banghart 4290:                 }
                   4291:             }
                   4292:         } 
                   4293:     }
                   4294:     return @readonly_files;
                   4295: }
1.577     banghart 4296: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4297: 
1.577     banghart 4298: sub get_marked_as_readonly_hash {
                   4299:     my ($domain,$user,$what) = @_;
1.613     albertel 4300:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4301:     my ($tmp)=keys(%current_permissions);
                   4302:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4303: 
1.577     banghart 4304:     my %readonly_files;
                   4305:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4306:         if (ref($value) eq "ARRAY"){
                   4307:             foreach my $stored_what (@{$value}) {
                   4308:                 if ($stored_what eq $what) {
                   4309:                     $readonly_files{$file_name} = 'locked';
                   4310:                 } elsif (!defined($what)) {
                   4311:                     $readonly_files{$file_name} = 'locked';
                   4312:                 }
                   4313:             }
                   4314:         } 
                   4315:     }
                   4316:     return %readonly_files;
                   4317: }
1.559     banghart 4318: # ------------------------------------------------------------ Unmark as Read Only
                   4319: 
                   4320: sub unmark_as_readonly {
1.629     banghart 4321:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4322:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4323:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4324:     my $symb_crs = $what;
                   4325:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4326:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4327:     my ($tmp)=keys(%current_permissions);
                   4328:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4329:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4330:     foreach my $file (@readonly_files) {
                   4331: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4332: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4333:         my @new_locks;
                   4334:         my @del_keys;
                   4335:         if (ref($current_locks) eq "ARRAY"){
                   4336:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4337:                 my $compare=$locker;
                   4338:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4339:                 if ($compare ne $symb_crs) {
                   4340:                     push(@new_locks, $locker);
1.563     banghart 4341:                 }
                   4342:             }
1.650     albertel 4343:             if (scalar(@new_locks) > 0) {
1.563     banghart 4344:                 $current_permissions{$file} = \@new_locks;
                   4345:             } else {
                   4346:                 push(@del_keys, $file);
1.613     albertel 4347:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4348:                 delete($current_permissions{$file});
1.563     banghart 4349:             }
                   4350:         }
1.561     banghart 4351:     }
1.613     albertel 4352:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4353:     return;
                   4354: }
1.512     banghart 4355: 
1.17      www      4356: # ------------------------------------------------------------ Directory lister
                   4357: 
                   4358: sub dirlist {
1.253     stredwic 4359:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4360: 
1.18      www      4361:     $uri=~s/^\///;
                   4362:     $uri=~s/\/$//;
1.253     stredwic 4363:     my ($udom, $uname);
                   4364:     (undef,$udom,$uname)=split(/\//,$uri);
                   4365:     if(defined($userdomain)) {
                   4366:         $udom = $userdomain;
                   4367:     }
                   4368:     if(defined($username)) {
                   4369:         $uname = $username;
                   4370:     }
                   4371: 
                   4372:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4373:     if(defined($alternateDirectoryRoot)) {
                   4374:         $dirRoot = $alternateDirectoryRoot;
                   4375:         $dirRoot =~ s/\/$//;
                   4376:     }
                   4377: 
                   4378:     if($udom) {
                   4379:         if($uname) {
1.605     matthew  4380:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4381:                               homeserver($uname,$udom));
1.605     matthew  4382:             my @listing_results;
                   4383:             if ($listing eq 'unknown_cmd') {
                   4384:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4385:                                homeserver($uname,$udom));
                   4386:                 @listing_results = split(/:/,$listing);
                   4387:             } else {
                   4388:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4389:             }
                   4390:             return @listing_results;
1.253     stredwic 4391:         } elsif(!defined($alternateDirectoryRoot)) {
                   4392:             my $tryserver;
                   4393:             my %allusers=();
                   4394:             foreach $tryserver (keys %libserv) {
                   4395:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4396:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4397:                                       $udom, $tryserver);
1.605     matthew  4398:                     my @listing_results;
                   4399:                     if ($listing eq 'unknown_cmd') {
                   4400:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4401:                                        $udom, $tryserver);
                   4402:                         @listing_results = split(/:/,$listing);
                   4403:                     } else {
                   4404:                         @listing_results =
                   4405:                             map { &unescape($_); } split(/:/,$listing);
                   4406:                     }
                   4407:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4408:                         $listing_results[0] ne 'empty'       &&
                   4409:                         $listing_results[0] ne 'con_lost') {
                   4410:                         foreach (@listing_results) {
1.253     stredwic 4411:                             my ($entry,@stat)=split(/&/,$_);
                   4412:                             $allusers{$entry}=1;
                   4413:                         }
                   4414:                     }
1.191     harris41 4415:                 }
1.253     stredwic 4416:             }
                   4417:             my $alluserstr='';
                   4418:             foreach (sort keys %allusers) {
                   4419:                 $alluserstr.=$_.'&user:';
                   4420:             }
                   4421:             $alluserstr=~s/:$//;
                   4422:             return split(/:/,$alluserstr);
                   4423:         } else {
                   4424:             my @emptyResults = ();
                   4425:             push(@emptyResults, 'missing user name');
                   4426:             return split(':',@emptyResults);
                   4427:         }
                   4428:     } elsif(!defined($alternateDirectoryRoot)) {
                   4429:         my $tryserver;
                   4430:         my %alldom=();
                   4431:         foreach $tryserver (keys %libserv) {
                   4432:             $alldom{$hostdom{$tryserver}}=1;
                   4433:         }
                   4434:         my $alldomstr='';
                   4435:         foreach (sort keys %alldom) {
1.397     albertel 4436:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4437:         }
                   4438:         $alldomstr=~s/:$//;
                   4439:         return split(/:/,$alldomstr);       
                   4440:     } else {
                   4441:         my @emptyResults = ();
                   4442:         push(@emptyResults, 'missing domain');
                   4443:         return split(':',@emptyResults);
1.275     stredwic 4444:     }
                   4445: }
                   4446: 
                   4447: # --------------------------------------------- GetFileTimestamp
                   4448: # This function utilizes dirlist and returns the date stamp for
                   4449: # when it was last modified.  It will also return an error of -1
                   4450: # if an error occurs
                   4451: 
1.410     matthew  4452: ##
                   4453: ## FIXME: This subroutine assumes its caller knows something about the
                   4454: ## directory structure of the home server for the student ($root).
                   4455: ## Not a good assumption to make.  Since this is for looking up files
                   4456: ## in user directories, the full path should be constructed by lond, not
                   4457: ## whatever machine we request data from.
                   4458: ##
1.275     stredwic 4459: sub GetFileTimestamp {
                   4460:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4461:     $studentDomain=~s/\W//g;
                   4462:     $studentName=~s/\W//g;
                   4463:     my $subdir=$studentName.'__';
                   4464:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4465:     my $proname="$studentDomain/$subdir/$studentName";
                   4466:     $proname .= '/'.$filename;
1.375     matthew  4467:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4468:                                               $studentName, $root);
1.275     stredwic 4469:     my @stats = split('&', $fileStat);
                   4470:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4471:         # @stats contains first the filename, then the stat output
                   4472:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4473:     } else {
                   4474:         return -1;
1.253     stredwic 4475:     }
1.26      www      4476: }
                   4477: 
                   4478: # -------------------------------------------------------- Value of a Condition
                   4479: 
1.40      www      4480: sub directcondval {
                   4481:     my $number=shift;
1.620     albertel 4482:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4483: 	&Apache::lonuserstate::evalstate();
                   4484:     }
1.620     albertel 4485:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4486:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4487:     } else {
                   4488:        return 2;
                   4489:     }
                   4490: }
                   4491: 
1.26      www      4492: sub condval {
                   4493:     my $condidx=shift;
                   4494:     my $result=0;
1.54      www      4495:     my $allpathcond='';
1.191     harris41 4496:     foreach (split(/\|/,$condidx)) {
1.620     albertel 4497:        if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
1.54      www      4498: 	   $allpathcond.=
1.620     albertel 4499:                '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
1.54      www      4500:        }
1.191     harris41 4501:     }
1.54      www      4502:     $allpathcond=~s/\|$//;
1.620     albertel 4503:     if ($env{'request.course.id'}) {
1.54      www      4504:        if ($allpathcond) {
1.26      www      4505:           my $operand='|';
                   4506: 	  my @stack;
1.191     harris41 4507:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      4508:               if ($_ eq '(') {
                   4509:                  push @stack,($operand,$result)
                   4510:               } elsif ($_ eq ')') {
                   4511:                   my $before=pop @stack;
                   4512: 		  if (pop @stack eq '&') {
                   4513: 		      $result=$result>$before?$before:$result;
                   4514:                   } else {
                   4515:                       $result=$result>$before?$result:$before;
                   4516:                   }
                   4517:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   4518:                   $operand=$_;
                   4519:               } else {
1.40      www      4520:                   my $new=directcondval($_);
1.26      www      4521:                   if ($operand eq '&') {
                   4522:                      $result=$result>$new?$new:$result;
                   4523:                   } else {
                   4524:                      $result=$result>$new?$result:$new;
1.191     harris41 4525:                   }
1.26      www      4526:               }
1.191     harris41 4527:           }
1.26      www      4528:        }
                   4529:     }
                   4530:     return $result;
1.421     albertel 4531: }
                   4532: 
                   4533: # ---------------------------------------------------- Devalidate courseresdata
                   4534: 
                   4535: sub devalidatecourseresdata {
                   4536:     my ($coursenum,$coursedomain)=@_;
                   4537:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4538:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4539: }
                   4540: 
1.200     www      4541: # --------------------------------------------------- Course Resourcedata Query
                   4542: 
1.624     albertel 4543: sub get_courseresdata {
                   4544:     my ($coursenum,$coursedomain)=@_;
1.200     www      4545:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4546:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4547:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4548:     my %dumpreply;
1.417     albertel 4549:     unless (defined($cached)) {
1.624     albertel 4550: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4551: 	$result=\%dumpreply;
1.251     albertel 4552: 	my ($tmp) = keys(%dumpreply);
                   4553: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4554: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4555: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4556: 	    return $tmp;
1.416     albertel 4557: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4558: 	    $result=undef;
1.599     albertel 4559: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4560: 	}
                   4561:     }
1.624     albertel 4562:     return $result;
                   4563: }
                   4564: 
1.633     albertel 4565: sub devalidateuserresdata {
                   4566:     my ($uname,$udom)=@_;
                   4567:     my $hashid="$udom:$uname";
                   4568:     &devalidate_cache_new('userres',$hashid);
                   4569: }
                   4570: 
1.624     albertel 4571: sub get_userresdata {
                   4572:     my ($uname,$udom)=@_;
                   4573:     #most student don\'t have any data set, check if there is some data
                   4574:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4575: 
                   4576:     my $hashid="$udom:$uname";
                   4577:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4578:     if (!defined($cached)) {
                   4579: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4580: 	$result=\%resourcedata;
                   4581: 	&do_cache_new('userres',$hashid,$result,600);
                   4582:     }
                   4583:     my ($tmp)=keys(%$result);
                   4584:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4585: 	return $result;
                   4586:     }
                   4587:     #error 2 occurs when the .db doesn't exist
                   4588:     if ($tmp!~/error: 2 /) {
1.672     albertel 4589: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4590: 		 " Trying to get resource data for ".
                   4591: 		 $uname." at ".$udom.": ".
                   4592: 		 $tmp."</font>");
                   4593:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4594: 	#&EXT_cache_set($udom,$uname);
                   4595: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4596: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4597:     }
                   4598:     return $tmp;
                   4599: }
                   4600: 
                   4601: sub resdata {
                   4602:     my ($name,$domain,$type,@which)=@_;
                   4603:     my $result;
                   4604:     if ($type eq 'course') {
                   4605: 	$result=&get_courseresdata($name,$domain);
                   4606:     } elsif ($type eq 'user') {
                   4607: 	$result=&get_userresdata($name,$domain);
                   4608:     }
                   4609:     if (!ref($result)) { return $result; }    
1.251     albertel 4610:     foreach my $item (@which) {
1.417     albertel 4611: 	if (defined($result->{$item})) {
                   4612: 	    return $result->{$item};
1.251     albertel 4613: 	}
1.250     albertel 4614:     }
1.291     albertel 4615:     return undef;
1.200     www      4616: }
                   4617: 
1.379     matthew  4618: #
                   4619: # EXT resource caching routines
                   4620: #
                   4621: 
                   4622: sub clear_EXT_cache_status {
1.383     albertel 4623:     &delenv('cache.EXT.');
1.379     matthew  4624: }
                   4625: 
                   4626: sub EXT_cache_status {
                   4627:     my ($target_domain,$target_user) = @_;
1.383     albertel 4628:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4629:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4630:         # We know already the user has no data
                   4631:         return 1;
                   4632:     } else {
                   4633:         return 0;
                   4634:     }
                   4635: }
                   4636: 
                   4637: sub EXT_cache_set {
                   4638:     my ($target_domain,$target_user) = @_;
1.383     albertel 4639:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 4640:     #&appenv($cachename => time);
1.379     matthew  4641: }
                   4642: 
1.28      www      4643: # --------------------------------------------------------- Value of a Variable
1.58      www      4644: sub EXT {
1.395     albertel 4645:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 4646: 
1.68      www      4647:     unless ($varname) { return ''; }
1.218     albertel 4648:     #get real user name/domain, courseid and symb
                   4649:     my $courseid;
1.359     albertel 4650:     my $publicuser;
1.427     www      4651:     if ($symbparm) {
                   4652: 	$symbparm=&get_symb_from_alias($symbparm);
                   4653:     }
1.218     albertel 4654:     if (!($uname && $udom)) {
1.360     albertel 4655:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4656: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4657:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4658:     } else {
1.620     albertel 4659: 	$courseid=$env{'request.course.id'};
1.218     albertel 4660:     }
1.48      www      4661:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4662:     my $rest;
1.320     albertel 4663:     if (defined($therest[0])) {
1.48      www      4664:        $rest=join('.',@therest);
                   4665:     } else {
                   4666:        $rest='';
                   4667:     }
1.320     albertel 4668: 
1.57      www      4669:     my $qualifierrest=$qualifier;
                   4670:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4671:     my $spacequalifierrest=$space;
                   4672:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4673:     if ($realm eq 'user') {
1.48      www      4674: # --------------------------------------------------------------- user.resource
                   4675: 	if ($space eq 'resource') {
1.651     albertel 4676: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   4677: 		  || defined($Apache::lonhomework::parsing_a_task))
                   4678: 		 &&
                   4679: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 4680: 		return $Apache::lonhomework::history{$qualifierrest};
                   4681: 	    } else {
1.359     albertel 4682: 		my %restored;
1.620     albertel 4683: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 4684: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   4685: 		} else {
                   4686: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   4687: 		}
1.335     albertel 4688: 		return $restored{$qualifierrest};
                   4689: 	    }
1.48      www      4690: # ----------------------------------------------------------------- user.access
                   4691:         } elsif ($space eq 'access') {
1.218     albertel 4692: 	    # FIXME - not supporting calls for a specific user
1.48      www      4693:             return &allowed($qualifier,$rest);
                   4694: # ------------------------------------------ user.preferences, user.environment
                   4695:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 4696: 	    if (($uname eq $env{'user.name'}) &&
                   4697: 		($udom eq $env{'user.domain'})) {
                   4698: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 4699: 	    } else {
1.359     albertel 4700: 		my %returnhash;
                   4701: 		if (!$publicuser) {
                   4702: 		    %returnhash=&userenvironment($udom,$uname,
                   4703: 						 $qualifierrest);
                   4704: 		}
1.218     albertel 4705: 		return $returnhash{$qualifierrest};
                   4706: 	    }
1.48      www      4707: # ----------------------------------------------------------------- user.course
                   4708:         } elsif ($space eq 'course') {
1.218     albertel 4709: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4710:             return $env{join('.',('request.course',$qualifier))};
1.48      www      4711: # ------------------------------------------------------------------- user.role
                   4712:         } elsif ($space eq 'role') {
1.218     albertel 4713: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4714:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      4715:             if ($qualifier eq 'value') {
                   4716: 		return $role;
                   4717:             } elsif ($qualifier eq 'extent') {
                   4718:                 return $where;
                   4719:             }
                   4720: # ----------------------------------------------------------------- user.domain
                   4721:         } elsif ($space eq 'domain') {
1.218     albertel 4722:             return $udom;
1.48      www      4723: # ------------------------------------------------------------------- user.name
                   4724:         } elsif ($space eq 'name') {
1.218     albertel 4725:             return $uname;
1.48      www      4726: # ---------------------------------------------------- Any other user namespace
1.29      www      4727:         } else {
1.359     albertel 4728: 	    my %reply;
                   4729: 	    if (!$publicuser) {
                   4730: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   4731: 	    }
                   4732: 	    return $reply{$qualifierrest};
1.48      www      4733:         }
1.236     www      4734:     } elsif ($realm eq 'query') {
                   4735: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 4736:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   4737: 						[$spacequalifierrest]);
1.620     albertel 4738: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      4739:    } elsif ($realm eq 'request') {
1.48      www      4740: # ------------------------------------------------------------- request.browser
                   4741:         if ($space eq 'browser') {
1.430     www      4742: 	    if ($qualifier eq 'textremote') {
1.676     albertel 4743: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      4744: 		    return 1;
                   4745: 		} else {
                   4746: 		    return 0;
                   4747: 		}
                   4748: 	    } else {
1.620     albertel 4749: 		return $env{'browser.'.$qualifier};
1.430     www      4750: 	    }
1.57      www      4751: # ------------------------------------------------------------ request.filename
                   4752:         } else {
1.620     albertel 4753:             return $env{'request.'.$spacequalifierrest};
1.29      www      4754:         }
1.28      www      4755:     } elsif ($realm eq 'course') {
1.48      www      4756: # ---------------------------------------------------------- course.description
1.620     albertel 4757:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      4758:     } elsif ($realm eq 'resource') {
1.165     www      4759: 
1.395     albertel 4760: 	my $section;
1.620     albertel 4761: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 4762: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   4763: 	}
1.593     albertel 4764: 	my ($courselevelm,$courselevel);
1.539     albertel 4765: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4766: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      4767: 
1.218     albertel 4768: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      4769: 
1.60      www      4770: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 4771: 	    my $symbp=$symbparm;
1.409     www      4772: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 4773: 
                   4774: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   4775: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   4776: 
1.620     albertel 4777: 	    if (($env{'user.name'} eq $uname) &&
                   4778: 		($env{'user.domain'} eq $udom)) {
                   4779: 		$section=$env{'request.course.sec'};
1.218     albertel 4780: 	    } else {
1.539     albertel 4781: 		if (! defined($usection)) {
1.551     albertel 4782: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 4783: 		} else {
                   4784: 		    $section = $usection;
                   4785: 		}
1.218     albertel 4786: 	    }
                   4787: 
                   4788: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   4789: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   4790: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   4791: 
1.593     albertel 4792: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 4793: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 4794: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      4795: 
1.60      www      4796: # ----------------------------------------------------------- first, check user
1.624     albertel 4797: 
                   4798: 	    my $userreply=&resdata($uname,$udom,'user',
                   4799: 				       ($courselevelr,$courselevelm,
                   4800: 					$courselevel));
                   4801: 
                   4802: 	    if (defined($userreply)) { return $userreply; }
1.95      www      4803: 
1.594     albertel 4804: # ------------------------------------------------ second, check some of course
1.96      www      4805: 
1.624     albertel 4806: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4807: 				     $env{'course.'.$courseid.'.domain'},
                   4808: 				     'course',
                   4809: 				     ($seclevelr,$seclevelm,$seclevel,
                   4810: 				      $courselevelr));
1.287     albertel 4811: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      4812: 
1.60      www      4813: # ------------------------------------------------------ third, check map parms
1.218     albertel 4814: 	    my %parmhash=();
                   4815: 	    my $thisparm='';
                   4816: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 4817: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 4818: 		    &GDBM_READER(),0640)) {
1.218     albertel 4819: 		$thisparm=$parmhash{$symbparm};
                   4820: 		untie(%parmhash);
                   4821: 	    }
                   4822: 	    if ($thisparm) { return $thisparm; }
                   4823: 	}
1.594     albertel 4824: # ------------------------------------------ fourth, look in resource metadata
1.71      www      4825: 
1.218     albertel 4826: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 4827: 	my $filename;
                   4828: 	if (!$symbparm) { $symbparm=&symbread(); }
                   4829: 	if ($symbparm) {
1.409     www      4830: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 4831: 	} else {
1.620     albertel 4832: 	    $filename=$env{'request.filename'};
1.282     albertel 4833: 	}
                   4834: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 4835: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 4836: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 4837: 	if (defined($metadata)) { return $metadata; }
1.142     www      4838: 
1.594     albertel 4839: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 4840: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4841: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 4842: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4843: 				     $env{'course.'.$courseid.'.domain'},
                   4844: 				     'course',
                   4845: 				     ($courselevelm,$courselevel));
1.593     albertel 4846: 	    if (defined($coursereply)) { return $coursereply; }
                   4847: 	}
1.145     www      4848: # ------------------------------------------------------------------ Cascade up
1.218     albertel 4849: 	unless ($space eq '0') {
1.336     albertel 4850: 	    my @parts=split(/_/,$space);
                   4851: 	    my $id=pop(@parts);
                   4852: 	    my $part=join('_',@parts);
                   4853: 	    if ($part eq '') { $part='0'; }
                   4854: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 4855: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 4856: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 4857: 	}
1.395     albertel 4858: 	if ($recurse) { return undef; }
                   4859: 	my $pack_def=&packages_tab_default($filename,$varname);
                   4860: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      4861: 
1.48      www      4862: # ---------------------------------------------------- Any other user namespace
                   4863:     } elsif ($realm eq 'environment') {
                   4864: # ----------------------------------------------------------------- environment
1.620     albertel 4865: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   4866: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 4867: 	} else {
                   4868: 	    my %returnhash=&userenvironment($udom,$uname,
                   4869: 					    $spacequalifierrest);
                   4870: 	    return $returnhash{$spacequalifierrest};
                   4871: 	}
1.28      www      4872:     } elsif ($realm eq 'system') {
1.48      www      4873: # ----------------------------------------------------------------- system.time
                   4874: 	if ($space eq 'time') {
                   4875: 	    return time;
                   4876:         }
1.28      www      4877:     }
1.48      www      4878:     return '';
1.61      www      4879: }
                   4880: 
1.395     albertel 4881: sub packages_tab_default {
                   4882:     my ($uri,$varname)=@_;
                   4883:     my (undef,$part,$name)=split(/\./,$varname);
                   4884:     my $packages=&metadata($uri,'packages');
                   4885:     foreach my $package (split(/,/,$packages)) {
                   4886: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 4887: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   4888: 	    return $packagetab{"$pack_type&$name&default"};
                   4889: 	}
1.585     albertel 4890: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 4891: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   4892: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 4893: 	}
                   4894:     }
                   4895:     return undef;
                   4896: }
                   4897: 
1.334     albertel 4898: sub add_prefix_and_part {
                   4899:     my ($prefix,$part)=@_;
                   4900:     my $keyroot;
                   4901:     if (defined($prefix) && $prefix !~ /^__/) {
                   4902: 	# prefix that has a part already
                   4903: 	$keyroot=$prefix;
                   4904:     } elsif (defined($prefix)) {
                   4905: 	# prefix that is missing a part
                   4906: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   4907:     } else {
                   4908: 	# no prefix at all
                   4909: 	if (defined($part)) { $keyroot='_'.$part; }
                   4910:     }
                   4911:     return $keyroot;
                   4912: }
                   4913: 
1.71      www      4914: # ---------------------------------------------------------------- Get metadata
                   4915: 
1.599     albertel 4916: my %metaentry;
1.71      www      4917: sub metadata {
1.176     www      4918:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      4919:     $uri=&declutter($uri);
1.288     albertel 4920:     # if it is a non metadata possible uri return quickly
1.529     albertel 4921:     if (($uri eq '') || 
                   4922: 	(($uri =~ m|^/*adm/|) && 
                   4923: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 4924:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 4925: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 4926: 	return undef;
1.288     albertel 4927:     }
1.73      www      4928:     my $filename=$uri;
                   4929:     $uri=~s/\.meta$//;
1.172     www      4930: #
                   4931: # Is the metadata already cached?
1.177     www      4932: # Look at timestamp of caching
1.172     www      4933: # Everything is cached by the main uri, libraries are never directly cached
                   4934: #
1.428     albertel 4935:     if (!defined($liburi)) {
1.599     albertel 4936: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 4937: 	if (defined($cached)) { return $result->{':'.$what}; }
                   4938:     }
                   4939:     {
1.172     www      4940: #
                   4941: # Is this a recursive call for a library?
                   4942: #
1.599     albertel 4943: #	if (! exists($metacache{$uri})) {
                   4944: #	    $metacache{$uri}={};
                   4945: #	}
1.171     www      4946:         if ($liburi) {
                   4947: 	    $liburi=&declutter($liburi);
                   4948:             $filename=$liburi;
1.401     bowersj2 4949:         } else {
1.599     albertel 4950: 	    &devalidate_cache_new('meta',$uri);
                   4951: 	    undef(%metaentry);
1.401     bowersj2 4952: 	}
1.140     www      4953:         my %metathesekeys=();
1.73      www      4954:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 4955: 	my $metastring;
1.609     banghart 4956: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 4957: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 4958: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 4959: 	    $metastring=&getfile($file);
1.489     albertel 4960: 	}
1.208     albertel 4961:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      4962:         my $token;
1.140     www      4963:         undef %metathesekeys;
1.71      www      4964:         while ($token=$parser->get_token) {
1.339     albertel 4965: 	    if ($token->[0] eq 'S') {
                   4966: 		if (defined($token->[2]->{'package'})) {
1.172     www      4967: #
                   4968: # This is a package - get package info
                   4969: #
1.339     albertel 4970: 		    my $package=$token->[2]->{'package'};
                   4971: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4972: 		    if (defined($token->[2]->{'id'})) { 
                   4973: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   4974: 		    }
1.599     albertel 4975: 		    if ($metaentry{':packages'}) {
                   4976: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 4977: 		    } else {
1.599     albertel 4978: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 4979: 		    }
1.613     albertel 4980: 		    foreach (sort keys %packagetab) {
1.432     albertel 4981: 			my $part=$keyroot;
                   4982: 			$part=~s/^\_//;
                   4983: 			if ($_=~/^\Q$package\E\&/ || 
                   4984: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 4985: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 4986: 			    # ignore package.tab specified default values
                   4987:                             # here &package_tab_default() will fetch those
                   4988: 			    if ($subp eq 'default') { next; }
1.339     albertel 4989: 			    my $value=$packagetab{$_};
1.432     albertel 4990: 			    my $unikey;
                   4991: 			    if ($pack =~ /_0$/) {
                   4992: 				$unikey='parameter_0_'.$name;
                   4993: 				$part=0;
                   4994: 			    } else {
                   4995: 				$unikey='parameter'.$keyroot.'_'.$name;
                   4996: 			    }
1.339     albertel 4997: 			    if ($subp eq 'display') {
                   4998: 				$value.=' [Part: '.$part.']';
                   4999: 			    }
1.599     albertel 5000: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5001: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5002: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5003: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5004: 			    }
1.599     albertel 5005: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5006: 				$metaentry{':'.$unikey}=
                   5007: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5008: 			    }
1.339     albertel 5009: 			}
                   5010: 		    }
                   5011: 		} else {
1.172     www      5012: #
                   5013: # This is not a package - some other kind of start tag
1.339     albertel 5014: #
                   5015: 		    my $entry=$token->[1];
                   5016: 		    my $unikey;
                   5017: 		    if ($entry eq 'import') {
                   5018: 			$unikey='';
                   5019: 		    } else {
                   5020: 			$unikey=$entry;
                   5021: 		    }
                   5022: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5023: 
                   5024: 		    if (defined($token->[2]->{'id'})) { 
                   5025: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5026: 		    }
1.175     www      5027: 
1.339     albertel 5028: 		    if ($entry eq 'import') {
1.175     www      5029: #
                   5030: # Importing a library here
1.339     albertel 5031: #
                   5032: 			if ($depthcount<20) {
                   5033: 			    my $location=$parser->get_text('/import');
                   5034: 			    my $dir=$filename;
                   5035: 			    $dir=~s|[^/]*$||;
                   5036: 			    $location=&filelocation($dir,$location);
                   5037: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5038: 							       $location,$unikey,
                   5039: 							       $depthcount+1)))) {
1.599     albertel 5040: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 5041: 				$metathesekeys{$_}=1;
                   5042: 			    }
                   5043: 			}
                   5044: 		    } else { 
                   5045: 			
                   5046: 			if (defined($token->[2]->{'name'})) { 
                   5047: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5048: 			}
                   5049: 			$metathesekeys{$unikey}=1;
                   5050: 			foreach (@{$token->[3]}) {
1.599     albertel 5051: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 5052: 			}
                   5053: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5054: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5055: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5056: 		 # only ws inside the tag, and not in default, so use default
                   5057: 		 # as value
1.599     albertel 5058: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5059: 			} else {
1.321     albertel 5060: 		  # either something interesting inside the tag or default
                   5061:                   # uninteresting
1.599     albertel 5062: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5063: 			}
1.172     www      5064: # end of not-a-package not-a-library import
1.339     albertel 5065: 		    }
1.172     www      5066: # end of not-a-package start tag
1.339     albertel 5067: 		}
1.172     www      5068: # the next is the end of "start tag"
1.339     albertel 5069: 	    }
                   5070: 	}
1.483     albertel 5071: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   5072: 	foreach my $key (sort(keys(%packagetab))) {
                   5073: 	    #no specific packages #how's our extension
                   5074: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5075: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5076: 					 \%metathesekeys);
                   5077: 	}
1.599     albertel 5078: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 5079: 	    foreach my $key (sort(keys(%packagetab))) {
                   5080: 		#no specific packages well let's get default then
                   5081: 		if ($key!~/^default&/) { next; }
1.488     albertel 5082: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5083: 					     \%metathesekeys);
                   5084: 	    }
                   5085: 	}
1.338     www      5086: # are there custom rights to evaluate
1.599     albertel 5087: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5088: 
1.338     www      5089:     #
                   5090:     # Importing a rights file here
1.339     albertel 5091:     #
                   5092: 	    unless ($depthcount) {
1.599     albertel 5093: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5094: 		my $dir=$filename;
                   5095: 		$dir=~s|[^/]*$||;
                   5096: 		$location=&filelocation($dir,$location);
                   5097: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5098: 						   $location,'_rights',
                   5099: 						   $depthcount+1)))) {
1.599     albertel 5100: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 5101: 		    $metathesekeys{$_}=1;
                   5102: 		}
                   5103: 	    }
                   5104: 	}
1.599     albertel 5105: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   5106: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5107: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.623     albertel 5108: 	&do_cache_new('meta',$uri,\%metaentry,60*60*24);
1.177     www      5109: # this is the end of "was not already recently cached
1.71      www      5110:     }
1.599     albertel 5111:     return $metaentry{':'.$what};
1.261     albertel 5112: }
                   5113: 
1.488     albertel 5114: sub metadata_create_package_def {
1.483     albertel 5115:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5116:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5117:     if ($subp eq 'default') { next; }
                   5118:     
1.599     albertel 5119:     if (defined($metaentry{':packages'})) {
                   5120: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5121:     } else {
1.599     albertel 5122: 	$metaentry{':packages'}=$package;
1.483     albertel 5123:     }
                   5124:     my $value=$packagetab{$key};
                   5125:     my $unikey;
                   5126:     $unikey='parameter_0_'.$name;
1.599     albertel 5127:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5128:     $$metathesekeys{$unikey}=1;
1.599     albertel 5129:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5130: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5131:     }
1.599     albertel 5132:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5133: 	$metaentry{':'.$unikey}=
                   5134: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5135:     }
                   5136: }
                   5137: 
1.261     albertel 5138: sub metadata_generate_part0 {
                   5139:     my ($metadata,$metacache,$uri) = @_;
                   5140:     my %allnames;
                   5141:     foreach my $metakey (sort keys %$metadata) {
                   5142: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5143: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5144: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5145: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5146: 	    $allnames{$name}=$part;
                   5147: 	  }
                   5148: 	}
                   5149:     }
                   5150:     foreach my $name (keys(%allnames)) {
                   5151:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5152:       my $key=":parameter_0_$name";
1.261     albertel 5153:       $$metacache{"$key.part"}='0';
                   5154:       $$metacache{"$key.name"}=$name;
1.428     albertel 5155:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5156: 					   $allnames{$name}.'_'.$name.
                   5157: 					   '.type'};
1.428     albertel 5158:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5159: 			     '.display'};
1.644     www      5160:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5161:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5162:       $$metacache{"$key.display"}=$olddis;
                   5163:     }
1.71      www      5164: }
                   5165: 
1.301     www      5166: # ------------------------------------------------- Get the title of a resource
                   5167: 
                   5168: sub gettitle {
                   5169:     my $urlsymb=shift;
                   5170:     my $symb=&symbread($urlsymb);
1.534     albertel 5171:     if ($symb) {
1.620     albertel 5172: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5173: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5174: 	if (defined($cached)) { 
                   5175: 	    return $result;
                   5176: 	}
1.534     albertel 5177: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5178: 	my $title='';
                   5179: 	my %bighash;
1.620     albertel 5180: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5181: 		&GDBM_READER(),0640)) {
                   5182: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5183: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5184: 	    untie %bighash;
                   5185: 	}
                   5186: 	$title=~s/\&colon\;/\:/gs;
                   5187: 	if ($title) {
1.599     albertel 5188: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5189: 	}
                   5190: 	$urlsymb=$url;
                   5191:     }
                   5192:     my $title=&metadata($urlsymb,'title');
                   5193:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5194:     return $title;
1.301     www      5195: }
1.613     albertel 5196: 
1.614     albertel 5197: sub get_slot {
                   5198:     my ($which,$cnum,$cdom)=@_;
                   5199:     if (!$cnum || !$cdom) {
                   5200: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5201: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5202: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5203:     }
                   5204:     my %slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5205:     &Apache::lonhomework::showhash(%slotinfo);
                   5206:     my ($tmp)=keys(%slotinfo);
                   5207:     if ($tmp=~/^error:/) { return (); }
1.616     albertel 5208:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5209: 	return %{$slotinfo{$which}};
                   5210:     }
                   5211:     return $slotinfo{$which};
1.614     albertel 5212: }
1.31      www      5213: # ------------------------------------------------- Update symbolic store links
                   5214: 
                   5215: sub symblist {
                   5216:     my ($mapname,%newhash)=@_;
1.438     www      5217:     $mapname=&deversion(&declutter($mapname));
1.31      www      5218:     my %hash;
1.620     albertel 5219:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5220:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5221:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 5222: 	    foreach (keys %newhash) {
1.601     albertel 5223:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
                   5224: 						  $newhash{$_}->[0]);
1.191     harris41 5225:             }
1.31      www      5226:             if (untie(%hash)) {
                   5227: 		return 'ok';
                   5228:             }
                   5229:         }
                   5230:     }
                   5231:     return 'error';
1.212     www      5232: }
                   5233: 
                   5234: # --------------------------------------------------------------- Verify a symb
                   5235: 
                   5236: sub symbverify {
1.510     www      5237:     my ($symb,$thisurl)=@_;
                   5238:     my $thisfn=$thisurl;
                   5239: # wrapper not part of symbs
                   5240:     $thisfn=~s/^\/adm\/wrapper//;
1.439     www      5241:     $thisfn=&declutter($thisfn);
1.215     www      5242: # direct jump to resource in page or to a sequence - will construct own symbs
                   5243:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5244: # check URL part
1.409     www      5245:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5246: 
1.431     www      5247:     unless ($url eq $thisfn) { return 0; }
1.213     www      5248: 
1.216     www      5249:     $symb=&symbclean($symb);
1.510     www      5250:     $thisurl=&deversion($thisurl);
1.439     www      5251:     $thisfn=&deversion($thisfn);
1.213     www      5252: 
                   5253:     my %bighash;
                   5254:     my $okay=0;
1.431     www      5255: 
1.620     albertel 5256:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5257:                             &GDBM_READER(),0640)) {
1.510     www      5258:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5259:         unless ($ids) { 
1.510     www      5260:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5261:         }
                   5262:         if ($ids) {
                   5263: # ------------------------------------------------------------------- Has ID(s)
                   5264: 	    foreach (split(/\,/,$ids)) {
1.644     www      5265: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5266:                if (
                   5267:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5268:    eq $symb) { 
1.620     albertel 5269: 		   if (($env{'request.role.adv'}) ||
                   5270: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5271: 		       $okay=1; 
                   5272: 		   }
                   5273: 	       }
1.216     www      5274: 	   }
                   5275:         }
1.213     www      5276: 	untie(%bighash);
                   5277:     }
                   5278:     return $okay;
1.31      www      5279: }
                   5280: 
1.210     www      5281: # --------------------------------------------------------------- Clean-up symb
                   5282: 
                   5283: sub symbclean {
                   5284:     my $symb=shift;
1.568     albertel 5285:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5286: # remove version from map
                   5287:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5288: 
1.210     www      5289: # remove version from URL
                   5290:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5291: 
1.507     www      5292: # remove wrapper
                   5293: 
1.510     www      5294:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210     www      5295:     return $symb;
1.409     www      5296: }
                   5297: 
                   5298: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5299: 
                   5300: sub encode_symb {
                   5301:     my ($map,$resid,$url)=@_;
                   5302:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5303: }
1.409     www      5304: 
                   5305: sub decode_symb {
1.568     albertel 5306:     my $symb=shift;
                   5307:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5308:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5309:     return (&fixversion($map),$resid,&fixversion($url));
                   5310: }
                   5311: 
                   5312: sub fixversion {
                   5313:     my $fn=shift;
1.609     banghart 5314:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5315:     my %bighash;
                   5316:     my $uri=&clutter($fn);
1.620     albertel 5317:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5318: # is this cached?
1.599     albertel 5319:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5320:     if (defined($cached)) { return $result; }
                   5321: # unfortunately not cached, or expired
1.620     albertel 5322:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5323: 	    &GDBM_READER(),0640)) {
                   5324:  	if ($bighash{'version_'.$uri}) {
                   5325:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5326:  	    unless (($version eq 'mostrecent') || 
                   5327: 		    ($version==&getversion($uri))) {
1.440     www      5328:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5329:  	    }
                   5330:  	}
                   5331:  	untie %bighash;
1.413     www      5332:     }
1.599     albertel 5333:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5334: }
                   5335: 
                   5336: sub deversion {
                   5337:     my $url=shift;
                   5338:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5339:     return $url;
1.210     www      5340: }
                   5341: 
1.31      www      5342: # ------------------------------------------------------ Return symb list entry
                   5343: 
                   5344: sub symbread {
1.249     www      5345:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5346:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5347:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5348: # no filename provided? try from environment
1.44      www      5349:     unless ($thisfn) {
1.620     albertel 5350:         if ($env{'request.symb'}) {
                   5351: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5352: 	}
1.620     albertel 5353: 	$thisfn=$env{'request.filename'};
1.44      www      5354:     }
1.569     albertel 5355:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5356: # is that filename actually a symb? Verify, clean, and return
                   5357:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5358: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5359: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5360: 	}
1.242     www      5361:     }
1.44      www      5362:     $thisfn=declutter($thisfn);
1.31      www      5363:     my %hash;
1.37      www      5364:     my %bighash;
                   5365:     my $syval='';
1.620     albertel 5366:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5367:         my $targetfn = $thisfn;
1.609     banghart 5368:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5369:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5370:         }
1.620     albertel 5371:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5372:                       &GDBM_READER(),0640)) {
1.481     raeburn  5373: 	    $syval=$hash{$targetfn};
1.37      www      5374:             untie(%hash);
                   5375:         }
                   5376: # ---------------------------------------------------------- There was an entry
                   5377:         if ($syval) {
1.601     albertel 5378: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5379: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5380: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5381: 		    #return $env{$cache_str}='';
1.601     albertel 5382: 		#}    
                   5383: 		#$syval.=$1;
                   5384: 	    #}
1.37      www      5385:         } else {
                   5386: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5387:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5388:                             &GDBM_READER(),0640)) {
1.37      www      5389: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5390:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5391:               unless ($ids) { 
                   5392:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5393:               }
                   5394:               unless ($ids) {
                   5395: # alias?
                   5396: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5397:               }
1.37      www      5398:               if ($ids) {
                   5399: # ------------------------------------------------------------------- Has ID(s)
                   5400:                  my @possibilities=split(/\,/,$ids);
1.39      www      5401:                  if ($#possibilities==0) {
                   5402: # ----------------------------------------------- There is only one possibility
1.37      www      5403: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5404: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5405: 						    $resid,$thisfn);
1.249     www      5406:                  } elsif (!$donotrecurse) {
1.39      www      5407: # ------------------------------------------ There is more than one possibility
                   5408:                      my $realpossible=0;
1.191     harris41 5409:                      foreach (@possibilities) {
1.39      www      5410: 			 my $file=$bighash{'src_'.$_};
                   5411:                          if (&allowed('bre',$file)) {
                   5412:          		    my ($mapid,$resid)=split(/\./,$_);
                   5413:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5414: 				$realpossible++;
1.626     albertel 5415:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5416: 						    $resid,$thisfn);
1.39      www      5417:                             }
                   5418: 			 }
1.191     harris41 5419:                      }
1.39      www      5420: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5421:                  } else {
                   5422:                      $syval='';
1.37      www      5423:                  }
                   5424: 	      }
                   5425:               untie(%bighash)
1.481     raeburn  5426:            }
1.31      www      5427:         }
1.62      www      5428:         if ($syval) {
1.620     albertel 5429: 	    return $env{$cache_str}=$syval;
1.62      www      5430:         }
1.31      www      5431:     }
1.44      www      5432:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5433:     return $env{$cache_str}='';
1.31      www      5434: }
                   5435: 
                   5436: # ---------------------------------------------------------- Return random seed
                   5437: 
1.32      www      5438: sub numval {
                   5439:     my $txt=shift;
                   5440:     $txt=~tr/A-J/0-9/;
                   5441:     $txt=~tr/a-j/0-9/;
                   5442:     $txt=~tr/K-T/0-9/;
                   5443:     $txt=~tr/k-t/0-9/;
                   5444:     $txt=~tr/U-Z/0-5/;
                   5445:     $txt=~tr/u-z/0-5/;
                   5446:     $txt=~s/\D//g;
1.564     albertel 5447:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5448:     return int($txt);
1.368     albertel 5449: }
                   5450: 
1.484     albertel 5451: sub numval2 {
                   5452:     my $txt=shift;
                   5453:     $txt=~tr/A-J/0-9/;
                   5454:     $txt=~tr/a-j/0-9/;
                   5455:     $txt=~tr/K-T/0-9/;
                   5456:     $txt=~tr/k-t/0-9/;
                   5457:     $txt=~tr/U-Z/0-5/;
                   5458:     $txt=~tr/u-z/0-5/;
                   5459:     $txt=~s/\D//g;
                   5460:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5461:     my $total;
                   5462:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5463:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5464:     return int($total);
                   5465: }
                   5466: 
1.575     albertel 5467: sub numval3 {
                   5468:     use integer;
                   5469:     my $txt=shift;
                   5470:     $txt=~tr/A-J/0-9/;
                   5471:     $txt=~tr/a-j/0-9/;
                   5472:     $txt=~tr/K-T/0-9/;
                   5473:     $txt=~tr/k-t/0-9/;
                   5474:     $txt=~tr/U-Z/0-5/;
                   5475:     $txt=~tr/u-z/0-5/;
                   5476:     $txt=~s/\D//g;
                   5477:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5478:     my $total;
                   5479:     foreach my $val (@txts) { $total+=$val; }
                   5480:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5481:     return $total;
                   5482: }
                   5483: 
1.675     albertel 5484: sub digest {
                   5485:     my ($data)=@_;
                   5486:     my $digest=&Digest::MD5::md5($data);
                   5487:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5488:     my ($e,$f);
                   5489:     {
                   5490:         use integer;
                   5491:         $e=($a+$b);
                   5492:         $f=($c+$d);
                   5493:         if ($_64bit) {
                   5494:             $e=(($e<<32)>>32);
                   5495:             $f=(($f<<32)>>32);
                   5496:         }
                   5497:     }
                   5498:     if (wantarray) {
                   5499: 	return ($e,$f);
                   5500:     } else {
                   5501: 	my $g;
                   5502: 	{
                   5503: 	    use integer;
                   5504: 	    $g=($e+$f);
                   5505: 	    if ($_64bit) {
                   5506: 		$g=(($g<<32)>>32);
                   5507: 	    }
                   5508: 	}
                   5509: 	return $g;
                   5510:     }
                   5511: }
                   5512: 
1.368     albertel 5513: sub latest_rnd_algorithm_id {
1.675     albertel 5514:     return '64bit5';
1.366     albertel 5515: }
1.32      www      5516: 
1.503     albertel 5517: sub get_rand_alg {
                   5518:     my ($courseid)=@_;
                   5519:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5520:     if ($courseid) {
1.620     albertel 5521: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5522:     }
                   5523:     return &latest_rnd_algorithm_id();
                   5524: }
                   5525: 
1.562     albertel 5526: sub validCODE {
                   5527:     my ($CODE)=@_;
                   5528:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5529:     return 0;
                   5530: }
                   5531: 
1.491     albertel 5532: sub getCODE {
1.620     albertel 5533:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5534:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5535: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5536: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5537: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5538:     }
                   5539:     return undef;
                   5540: }
                   5541: 
1.31      www      5542: sub rndseed {
1.155     albertel 5543:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5544: 
                   5545:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5546:     if (!$symb) {
1.366     albertel 5547: 	unless ($symb=$wsymb) { return time; }
                   5548:     }
                   5549:     if (!$courseid) { $courseid=$wcourseid; }
                   5550:     if (!$domain) { $domain=$wdomain; }
                   5551:     if (!$username) { $username=$wusername }
1.503     albertel 5552:     my $which=&get_rand_alg();
1.491     albertel 5553:     if (defined(&getCODE())) {
1.675     albertel 5554: 	if ($which eq '64bit5') {
                   5555: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   5556: 	} elsif ($which eq '64bit4') {
1.575     albertel 5557: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5558: 	} else {
                   5559: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5560: 	}
1.675     albertel 5561:     } elsif ($which eq '64bit5') {
                   5562: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 5563:     } elsif ($which eq '64bit4') {
                   5564: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5565:     } elsif ($which eq '64bit3') {
                   5566: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5567:     } elsif ($which eq '64bit2') {
                   5568: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5569:     } elsif ($which eq '64bit') {
                   5570: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5571:     }
                   5572:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5573: }
                   5574: 
                   5575: sub rndseed_32bit {
                   5576:     my ($symb,$courseid,$domain,$username)=@_;
                   5577:     {
                   5578: 	use integer;
                   5579: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5580: 	my $symbseed=numval($symb) << 22;
                   5581: 	my $namechck=unpack("%32C*",$username) << 17;
                   5582: 	my $nameseed=numval($username) << 12;
                   5583: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5584: 	my $courseseed=unpack("%32C*",$courseid);
                   5585: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5586: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5587: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5588: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5589: 	return $num;
                   5590:     }
                   5591: }
                   5592: 
                   5593: sub rndseed_64bit {
                   5594:     my ($symb,$courseid,$domain,$username)=@_;
                   5595:     {
                   5596: 	use integer;
                   5597: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5598: 	my $symbseed=numval($symb) << 10;
                   5599: 	my $namechck=unpack("%32S*",$username);
                   5600: 	
                   5601: 	my $nameseed=numval($username) << 21;
                   5602: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5603: 	my $courseseed=unpack("%32S*",$courseid);
                   5604: 	
                   5605: 	my $num1=$symbchck+$symbseed+$namechck;
                   5606: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5607: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5608: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5609: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5610: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5611: 	return "$num1,$num2";
1.155     albertel 5612:     }
1.366     albertel 5613: }
                   5614: 
1.443     albertel 5615: sub rndseed_64bit2 {
                   5616:     my ($symb,$courseid,$domain,$username)=@_;
                   5617:     {
                   5618: 	use integer;
                   5619: 	# strings need to be an even # of cahracters long, it it is odd the
                   5620:         # last characters gets thrown away
                   5621: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5622: 	my $symbseed=numval($symb) << 10;
                   5623: 	my $namechck=unpack("%32S*",$username.' ');
                   5624: 	
                   5625: 	my $nameseed=numval($username) << 21;
1.501     albertel 5626: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5627: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5628: 	
                   5629: 	my $num1=$symbchck+$symbseed+$namechck;
                   5630: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5631: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5632: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   5633: 	return "$num1,$num2";
                   5634:     }
                   5635: }
                   5636: 
                   5637: sub rndseed_64bit3 {
                   5638:     my ($symb,$courseid,$domain,$username)=@_;
                   5639:     {
                   5640: 	use integer;
                   5641: 	# strings need to be an even # of cahracters long, it it is odd the
                   5642:         # last characters gets thrown away
                   5643: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5644: 	my $symbseed=numval2($symb) << 10;
                   5645: 	my $namechck=unpack("%32S*",$username.' ');
                   5646: 	
                   5647: 	my $nameseed=numval2($username) << 21;
1.443     albertel 5648: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5649: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5650: 	
                   5651: 	my $num1=$symbchck+$symbseed+$namechck;
                   5652: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5653: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 5654: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5655: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5656: 	
1.503     albertel 5657: 	return "$num1:$num2";
1.443     albertel 5658:     }
                   5659: }
                   5660: 
1.575     albertel 5661: sub rndseed_64bit4 {
                   5662:     my ($symb,$courseid,$domain,$username)=@_;
                   5663:     {
                   5664: 	use integer;
                   5665: 	# strings need to be an even # of cahracters long, it it is odd the
                   5666:         # last characters gets thrown away
                   5667: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5668: 	my $symbseed=numval3($symb) << 10;
                   5669: 	my $namechck=unpack("%32S*",$username.' ');
                   5670: 	
                   5671: 	my $nameseed=numval3($username) << 21;
                   5672: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5673: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5674: 	
                   5675: 	my $num1=$symbchck+$symbseed+$namechck;
                   5676: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5677: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5678: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5679: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5680: 	
                   5681: 	return "$num1:$num2";
                   5682:     }
                   5683: }
                   5684: 
1.675     albertel 5685: sub rndseed_64bit5 {
                   5686:     my ($symb,$courseid,$domain,$username)=@_;
                   5687:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   5688:     return "$num1:$num2";
                   5689: }
                   5690: 
1.366     albertel 5691: sub rndseed_CODE_64bit {
                   5692:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 5693:     {
1.366     albertel 5694: 	use integer;
1.443     albertel 5695: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 5696: 	my $symbseed=numval2($symb);
1.491     albertel 5697: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5698: 	my $CODEseed=numval(&getCODE());
1.443     albertel 5699: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 5700: 	my $num1=$symbseed+$CODEchck;
                   5701: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5702: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 5703: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 5704: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5705: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 5706: 	return "$num1:$num2";
1.366     albertel 5707:     }
                   5708: }
                   5709: 
1.575     albertel 5710: sub rndseed_CODE_64bit4 {
                   5711:     my ($symb,$courseid,$domain,$username)=@_;
                   5712:     {
                   5713: 	use integer;
                   5714: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   5715: 	my $symbseed=numval3($symb);
                   5716: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5717: 	my $CODEseed=numval3(&getCODE());
                   5718: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5719: 	my $num1=$symbseed+$CODEchck;
                   5720: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5721: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   5722: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   5723: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5724: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   5725: 	return "$num1:$num2";
                   5726:     }
                   5727: }
                   5728: 
1.675     albertel 5729: sub rndseed_CODE_64bit5 {
                   5730:     my ($symb,$courseid,$domain,$username)=@_;
                   5731:     my $code = &getCODE();
                   5732:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   5733:     return "$num1:$num2";
                   5734: }
                   5735: 
1.366     albertel 5736: sub setup_random_from_rndseed {
                   5737:     my ($rndseed)=@_;
1.503     albertel 5738:     if ($rndseed =~/([,:])/) {
                   5739: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 5740: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   5741:     } else {
                   5742: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 5743:     }
1.36      albertel 5744: }
                   5745: 
1.474     albertel 5746: sub latest_receipt_algorithm_id {
                   5747:     return 'receipt2';
                   5748: }
                   5749: 
1.480     www      5750: sub recunique {
                   5751:     my $fucourseid=shift;
                   5752:     my $unique;
1.620     albertel 5753:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5754: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      5755:     } else {
                   5756: 	$unique=$perlvar{'lonReceipt'};
                   5757:     }
                   5758:     return unpack("%32C*",$unique);
                   5759: }
                   5760: 
                   5761: sub recprefix {
                   5762:     my $fucourseid=shift;
                   5763:     my $prefix;
1.620     albertel 5764:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5765: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      5766:     } else {
                   5767: 	$prefix=$perlvar{'lonHostID'};
                   5768:     }
                   5769:     return unpack("%32C*",$prefix);
                   5770: }
                   5771: 
1.76      www      5772: sub ireceipt {
1.474     albertel 5773:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      5774:     my $cuname=unpack("%32C*",$funame);
                   5775:     my $cudom=unpack("%32C*",$fudom);
                   5776:     my $cucourseid=unpack("%32C*",$fucourseid);
                   5777:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      5778:     my $cunique=&recunique($fucourseid);
1.474     albertel 5779:     my $cpart=unpack("%32S*",$part);
1.480     www      5780:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 5781:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   5782: 	$env{'request.state'} eq 'construct') {
1.474     albertel 5783: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   5784: 			       " and ".($cpart%$cudom));
                   5785: 			       
                   5786: 	$return.= ($cunique%$cuname+
                   5787: 		   $cunique%$cudom+
                   5788: 		   $cusymb%$cuname+
                   5789: 		   $cusymb%$cudom+
                   5790: 		   $cucourseid%$cuname+
                   5791: 		   $cucourseid%$cudom+
                   5792: 		   $cpart%$cuname+
                   5793: 		   $cpart%$cudom);
                   5794:     } else {
                   5795: 	$return.= ($cunique%$cuname+
                   5796: 		   $cunique%$cudom+
                   5797: 		   $cusymb%$cuname+
                   5798: 		   $cusymb%$cudom+
                   5799: 		   $cucourseid%$cuname+
                   5800: 		   $cucourseid%$cudom);
                   5801:     }
                   5802:     return $return;
1.76      www      5803: }
                   5804: 
                   5805: sub receipt {
1.474     albertel 5806:     my ($part)=@_;
                   5807:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   5808:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      5809: }
1.260     ng       5810: 
1.36      albertel 5811: # ------------------------------------------------------------ Serves up a file
1.472     albertel 5812: # returns either the contents of the file or 
                   5813: # -1 if the file doesn't exist
1.481     raeburn  5814: #
                   5815: # if the target is a file that was uploaded via DOCS, 
                   5816: # a check will be made to see if a current copy exists on the local server,
                   5817: # if it does this will be served, otherwise a copy will be retrieved from
                   5818: # the home server for the course and stored in /home/httpd/html/userfiles on
                   5819: # the local server.   
1.472     albertel 5820: 
1.36      albertel 5821: sub getfile {
1.538     albertel 5822:     my ($file) = @_;
1.609     banghart 5823:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 5824:     &repcopy($file);
                   5825:     return &readfile($file);
                   5826: }
                   5827: 
                   5828: sub repcopy_userfile {
                   5829:     my ($file)=@_;
1.609     banghart 5830:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 5831:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 5832:     my ($cdom,$cnum,$filename) = 
                   5833: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   5834:     my ($info,$rtncode);
                   5835:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   5836:     if (-e "$file") {
                   5837: 	my @fileinfo = stat($file);
                   5838: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5839: 	if ($lwpresp ne 'ok') {
                   5840: 	    if ($rtncode eq '404') {
1.538     albertel 5841: 		unlink($file);
1.482     albertel 5842: 	    }
1.517     albertel 5843: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 5844: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5845: 	    #my $response=$ua->request($request);
                   5846: 	    #if ($response->is_success()) {
                   5847: 	#	return $response->content;
                   5848: 	#    } else {
                   5849: 	#	return -1;
                   5850: 	#    }
1.482     albertel 5851: 	    return -1;
                   5852: 	}
                   5853: 	if ($info < $fileinfo[9]) {
1.607     raeburn  5854: 	    return 'ok';
1.482     albertel 5855: 	}
                   5856: 	$info = '';
1.538     albertel 5857: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5858: 	if ($lwpresp ne 'ok') {
                   5859: 	    return -1;
                   5860: 	}
                   5861:     } else {
1.538     albertel 5862: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5863: 	if ($lwpresp ne 'ok') {
1.517     albertel 5864: 	    my $ua=new LWP::UserAgent;
1.538     albertel 5865: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5866: 	    my $response=$ua->request($request);
                   5867: 	    if ($response->is_success()) {
1.538     albertel 5868: 		$info=$response->content;
1.517     albertel 5869: 	    } else {
                   5870: 		return -1;
                   5871: 	    }
1.482     albertel 5872: 	}
                   5873: 	my @parts = ($cdom,$cnum); 
                   5874: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   5875: 	    push @parts, split(/\//,$1);
1.518     albertel 5876: 	}
1.538     albertel 5877: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 5878: 	foreach my $part (@parts) {
                   5879: 	    $path .= '/'.$part;
                   5880: 	    if (!-e $path) {
                   5881: 		mkdir($path,0770);
                   5882: 	    }
                   5883: 	}
                   5884:     }
1.538     albertel 5885:     open(FILE,">$file");
1.482     albertel 5886:     print FILE $info;
                   5887:     close(FILE);
1.607     raeburn  5888:     return 'ok';
1.481     raeburn  5889: }
                   5890: 
1.517     albertel 5891: sub tokenwrapper {
                   5892:     my $uri=shift;
1.552     albertel 5893:     $uri=~s|^http\://([^/]+)||;
                   5894:     $uri=~s|^/||;
1.620     albertel 5895:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 5896:     my $token=$1;
1.552     albertel 5897:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   5898:     if ($udom && $uname && $file) {
                   5899: 	$file=~s|(\?\.*)*$||;
1.620     albertel 5900:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 5901:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 5902:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   5903:                                '&tokenissued='.$perlvar{'lonHostID'};
                   5904:     } else {
                   5905:         return '/adm/notfound.html';
                   5906:     }
                   5907: }
                   5908: 
1.481     raeburn  5909: sub getuploaded {
                   5910:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   5911:     $uri=~s/^\///;
                   5912:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   5913:     my $ua=new LWP::UserAgent;
                   5914:     my $request=new HTTP::Request($reqtype,$uri);
                   5915:     my $response=$ua->request($request);
                   5916:     $$rtncode = $response->code;
1.482     albertel 5917:     if (! $response->is_success()) {
                   5918: 	return 'failed';
                   5919:     }      
                   5920:     if ($reqtype eq 'HEAD') {
1.486     www      5921: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 5922:     } elsif ($reqtype eq 'GET') {
                   5923: 	$$info = $response->content;
1.472     albertel 5924:     }
1.482     albertel 5925:     return 'ok';
1.36      albertel 5926: }
                   5927: 
1.481     raeburn  5928: sub readfile {
                   5929:     my $file = shift;
                   5930:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   5931:     my $fh;
                   5932:     open($fh,"<$file");
                   5933:     my $a='';
                   5934:     while (<$fh>) { $a .=$_; }
                   5935:     return $a;
                   5936: }
                   5937: 
1.36      albertel 5938: sub filelocation {
1.590     banghart 5939:     my ($dir,$file) = @_;
                   5940:     my $location;
                   5941:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
                   5942:     if ($file=~m:^/~:) { # is a contruction space reference
                   5943:         $location = $file;
                   5944:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 5945:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   5946: 	# is a correct contruction space reference
                   5947:         $location = $file;
1.609     banghart 5948:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 5949:         my ($udom,$uname,$filename)=
1.609     banghart 5950:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 5951:         my $home=&homeserver($uname,$udom);
                   5952:         my $is_me=0;
                   5953:         my @ids=&current_machine_ids();
                   5954:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   5955:         if ($is_me) {
                   5956:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   5957:   	      '/userfiles/'.$filename;
                   5958:         } else {
                   5959:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   5960:   	      $udom.'/'.$uname.'/'.$filename;
                   5961:         }
                   5962:     } else {
                   5963:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   5964:         $file=~s:^/res/:/:;
                   5965:         if ( !( $file =~ m:^/:) ) {
                   5966:             $location = $dir. '/'.$file;
                   5967:         } else {
                   5968:             $location = '/home/httpd/html/res'.$file;
                   5969:         }
1.59      albertel 5970:     }
1.590     banghart 5971:     $location=~s://+:/:g; # remove duplicate /
                   5972:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   5973:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   5974:     return $location;
1.46      www      5975: }
1.36      albertel 5976: 
1.46      www      5977: sub hreflocation {
                   5978:     my ($dir,$file)=@_;
1.460     albertel 5979:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 5980: 	$file=filelocation($dir,$file);
                   5981:     }
                   5982:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   5983: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   5984:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 5985: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 5986:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   5987: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   5988: 	    -/uploaded/$1/$2/-x;
1.46      www      5989:     }
1.462     albertel 5990:     return $file;
1.465     albertel 5991: }
                   5992: 
                   5993: sub current_machine_domains {
                   5994:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5995:     my @domains;
                   5996:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5997: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5998: 	if ($hostname eq $name) {
                   5999: 	    push(@domains,$hostdom{$id});
                   6000: 	}
                   6001:     }
                   6002:     return @domains;
                   6003: }
                   6004: 
                   6005: sub current_machine_ids {
                   6006:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6007:     my @ids;
                   6008:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6009: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6010: 	if ($hostname eq $name) {
                   6011: 	    push(@ids,$id);
                   6012: 	}
                   6013:     }
                   6014:     return @ids;
1.31      www      6015: }
                   6016: 
                   6017: # ------------------------------------------------------------- Declutters URLs
                   6018: 
                   6019: sub declutter {
                   6020:     my $thisfn=shift;
1.569     albertel 6021:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6022:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6023:     $thisfn=~s/^\///;
                   6024:     $thisfn=~s/^res\///;
1.235     www      6025:     $thisfn=~s/\?.+$//;
1.268     www      6026:     return $thisfn;
                   6027: }
                   6028: 
                   6029: # ------------------------------------------------------------- Clutter up URLs
                   6030: 
                   6031: sub clutter {
                   6032:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6033:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6034:        $thisfn='/res'.$thisfn; 
                   6035:     }
1.31      www      6036:     return $thisfn;
1.12      www      6037: }
                   6038: 
1.557     albertel 6039: sub freeze_escape {
                   6040:     my ($value)=@_;
                   6041:     if (ref($value)) {
                   6042: 	$value=&nfreeze($value);
                   6043: 	return '__FROZEN__'.&escape($value);
                   6044:     }
                   6045:     return &escape($value);
                   6046: }
                   6047: 
1.12      www      6048: # -------------------------------------------------------- Escape Special Chars
                   6049: 
                   6050: sub escape {
                   6051:     my $str=shift;
                   6052:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   6053:     return $str;
                   6054: }
                   6055: 
                   6056: # ----------------------------------------------------- Un-Escape Special Chars
                   6057: 
                   6058: sub unescape {
                   6059:     my $str=shift;
                   6060:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   6061:     return $str;
                   6062: }
1.11      www      6063: 
1.557     albertel 6064: sub thaw_unescape {
                   6065:     my ($value)=@_;
                   6066:     if ($value =~ /^__FROZEN__/) {
                   6067: 	substr($value,0,10,undef);
                   6068: 	$value=&unescape($value);
                   6069: 	return &thaw($value);
                   6070:     }
                   6071:     return &unescape($value);
                   6072: }
                   6073: 
1.436     albertel 6074: sub correct_line_ends {
                   6075:     my ($result)=@_;
                   6076:     $$result =~s/\r\n/\n/mg;
                   6077:     $$result =~s/\r/\n/mg;
1.415     albertel 6078: }
1.1       albertel 6079: # ================================================================ Main Program
                   6080: 
1.184     www      6081: sub goodbye {
1.204     albertel 6082:    &logthis("Starting Shut down");
1.443     albertel 6083: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6084:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6085: #converted
1.599     albertel 6086: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6087:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6088: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6089: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6090: #1.1 only
1.599     albertel 6091: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6092: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6093: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6094: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6095:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6096:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6097:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6098:    &flushcourselogs();
                   6099:    &logthis("Shutting down");
1.362     albertel 6100:    return DONE;
1.184     www      6101: }
                   6102: 
1.179     www      6103: BEGIN {
1.228     harris41 6104: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6105:     unless ($readit) {
1.217     harris41 6106: {
1.581     matthew  6107:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6108:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6109: 
                   6110:     while (my $configline=<$config>) {
1.484     albertel 6111:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6112: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6113:            chomp($varvalue);
1.1       albertel 6114:            $perlvar{$varname}=$varvalue;
                   6115:         }
                   6116:     }
1.448     albertel 6117:     close($config);
1.1       albertel 6118: }
1.227     harris41 6119: {
1.448     albertel 6120:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6121: 
                   6122:     while (my $configline=<$config>) {
                   6123:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6124: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6125:            chomp($varvalue);
                   6126:            $perlvar{$varname}=$varvalue;
                   6127:         }
                   6128:     }
1.448     albertel 6129:     close($config);
1.227     harris41 6130: }
1.1       albertel 6131: 
1.327     albertel 6132: # ------------------------------------------------------------ Read domain file
                   6133: {
                   6134:     %domaindescription = ();
                   6135:     %domain_auth_def = ();
                   6136:     %domain_auth_arg_def = ();
1.448     albertel 6137:     my $fh;
                   6138:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6139:        while (<$fh>) {
1.390     matthew  6140:            next if (/^(\#|\s*$)/);
                   6141: #           next if /^\#/;
1.327     albertel 6142:            chomp;
1.403     www      6143:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   6144: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   6145: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6146:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6147: 	   $domaindescription{$domain}=$domain_description;
                   6148: 	   $domain_lang_def{$domain}=$def_lang;
                   6149: 	   $domain_city{$domain}=$city;
                   6150: 	   $domain_longi{$domain}=$longi;
                   6151: 	   $domain_lati{$domain}=$lati;
                   6152: 
1.448     albertel 6153:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6154: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6155: 	}
1.327     albertel 6156:     }
1.448     albertel 6157:     close ($fh);
1.327     albertel 6158: }
                   6159: 
                   6160: 
1.1       albertel 6161: # ------------------------------------------------------------- Read hosts file
                   6162: {
1.448     albertel 6163:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6164: 
                   6165:     while (my $configline=<$config>) {
1.303     matthew  6166:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6167:        chomp($configline);
1.595     albertel 6168:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6169:        $name=~s/\s//g;
1.595     albertel 6170:        if ($id && $domain && $role && $name) {
1.252     albertel 6171: 	 $hostname{$id}=$name;
                   6172: 	 $hostdom{$id}=$domain;
                   6173: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6174:        }
1.1       albertel 6175:     }
1.448     albertel 6176:     close($config);
1.619     albertel 6177:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6178:     #&get_iphost();
1.1       albertel 6179: }
                   6180: 
1.598     albertel 6181: sub get_iphost {
                   6182:     if (%iphost) { return %iphost; }
1.653     albertel 6183:     my %name_to_ip;
1.598     albertel 6184:     foreach my $id (keys(%hostname)) {
                   6185: 	my $name=$hostname{$id};
1.653     albertel 6186: 	my $ip;
                   6187: 	if (!exists($name_to_ip{$name})) {
                   6188: 	    $ip = gethostbyname($name);
                   6189: 	    if (!$ip || length($ip) ne 4) {
                   6190: 		&logthis("Skipping host $id name $name no IP found\n");
                   6191: 		next;
                   6192: 	    }
                   6193: 	    $ip=inet_ntoa($ip);
                   6194: 	    $name_to_ip{$name} = $ip;
                   6195: 	} else {
                   6196: 	    $ip = $name_to_ip{$name};
1.598     albertel 6197: 	}
                   6198: 	push(@{$iphost{$ip}},$id);
                   6199:     }
                   6200:     return %iphost;
                   6201: }
                   6202: 
1.1       albertel 6203: # ------------------------------------------------------ Read spare server file
                   6204: {
1.448     albertel 6205:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6206: 
                   6207:     while (my $configline=<$config>) {
                   6208:        chomp($configline);
1.284     matthew  6209:        if ($configline) {
1.1       albertel 6210:           $spareid{$configline}=1;
                   6211:        }
                   6212:     }
1.448     albertel 6213:     close($config);
1.1       albertel 6214: }
1.11      www      6215: # ------------------------------------------------------------ Read permissions
                   6216: {
1.448     albertel 6217:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6218: 
                   6219:     while (my $configline=<$config>) {
1.448     albertel 6220: 	chomp($configline);
                   6221: 	if ($configline) {
                   6222: 	    my ($role,$perm)=split(/ /,$configline);
                   6223: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6224: 	}
1.11      www      6225:     }
1.448     albertel 6226:     close($config);
1.11      www      6227: }
                   6228: 
                   6229: # -------------------------------------------- Read plain texts for permissions
                   6230: {
1.448     albertel 6231:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6232: 
                   6233:     while (my $configline=<$config>) {
1.448     albertel 6234: 	chomp($configline);
                   6235: 	if ($configline) {
                   6236: 	    my ($short,$plain)=split(/:/,$configline);
                   6237: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6238: 	}
1.135     www      6239:     }
1.448     albertel 6240:     close($config);
1.135     www      6241: }
                   6242: 
                   6243: # ---------------------------------------------------------- Read package table
                   6244: {
1.448     albertel 6245:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6246: 
                   6247:     while (my $configline=<$config>) {
1.483     albertel 6248: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6249: 	chomp($configline);
                   6250: 	my ($short,$plain)=split(/:/,$configline);
                   6251: 	my ($pack,$name)=split(/\&/,$short);
                   6252: 	if ($plain ne '') {
                   6253: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6254: 	    $packagetab{$short}=$plain; 
                   6255: 	}
1.11      www      6256:     }
1.448     albertel 6257:     close($config);
1.329     matthew  6258: }
                   6259: 
                   6260: # ------------- set up temporary directory
                   6261: {
                   6262:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6263: 
1.11      www      6264: }
                   6265: 
1.599     albertel 6266: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6267: 
1.281     www      6268: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6269: $dumpcount=0;
1.22      www      6270: 
1.163     harris41 6271: &logtouch();
1.672     albertel 6272: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6273: $readit=1;
1.564     albertel 6274:     {
                   6275: 	use integer;
                   6276: 	my $test=(2**32)+1;
1.568     albertel 6277: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6278: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6279:     }
1.195     www      6280: }
1.1       albertel 6281: }
1.179     www      6282: 
1.1       albertel 6283: 1;
1.191     harris41 6284: __END__
                   6285: 
1.243     albertel 6286: =pod
                   6287: 
1.191     harris41 6288: =head1 NAME
                   6289: 
1.243     albertel 6290: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6291: 
                   6292: =head1 SYNOPSIS
                   6293: 
1.243     albertel 6294: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6295: 
                   6296:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6297: 
1.243     albertel 6298: Common parameters:
                   6299: 
                   6300: =over 4
                   6301: 
                   6302: =item *
                   6303: 
                   6304: $uname : an internal username (if $cname expecting a course Id specifically)
                   6305: 
                   6306: =item *
                   6307: 
                   6308: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6309: 
                   6310: =item *
                   6311: 
                   6312: $symb : a resource instance identifier
                   6313: 
                   6314: =item *
                   6315: 
                   6316: $namespace : the name of a .db file that contains the data needed or
                   6317: being set.
                   6318: 
                   6319: =back
                   6320: 
1.394     bowersj2 6321: =head1 OVERVIEW
1.191     harris41 6322: 
1.394     bowersj2 6323: lonnet provides subroutines which interact with the
                   6324: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6325: about classes, users, and resources.
1.243     albertel 6326: 
                   6327: For many of these objects you can also use this to store data about
                   6328: them or modify them in various ways.
1.191     harris41 6329: 
1.394     bowersj2 6330: =head2 Symbs
1.191     harris41 6331: 
1.394     bowersj2 6332: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6333: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6334: map, the resource number of the resource in the map, and the URL of
                   6335: the resource itself. The latter is somewhat redundant, but might help
                   6336: if maps change.
                   6337: 
                   6338: An example is
                   6339: 
                   6340:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6341: 
                   6342: The respective map entry is
                   6343: 
                   6344:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6345:   title="Problem 2">
                   6346:  </resource>
                   6347: 
                   6348: Symbs are used by the random number generator, as well as to store and
                   6349: restore data specific to a certain instance of for example a problem.
                   6350: 
                   6351: =head2 Storing And Retrieving Data
                   6352: 
                   6353: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6354: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6355: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6356: is is the non-critical message twin of cstore. These functions are for
                   6357: handlers to store a perl hash to a user's permanent data space in an
                   6358: easy manner, and to retrieve it again on another call. It is expected
                   6359: that a handler would use this once at the beginning to retrieve data,
                   6360: and then again once at the end to send only the new data back.
                   6361: 
                   6362: The data is stored in the user's data directory on the user's
                   6363: homeserver under the ID of the course.
                   6364: 
                   6365: The hash that is returned by restore will have all of the previous
                   6366: value for all of the elements of the hash.
                   6367: 
                   6368: Example:
                   6369: 
                   6370:  #creating a hash
                   6371:  my %hash;
                   6372:  $hash{'foo'}='bar';
                   6373: 
                   6374:  #storing it
                   6375:  &Apache::lonnet::cstore(\%hash);
                   6376: 
                   6377:  #changing a value
                   6378:  $hash{'foo'}='notbar';
                   6379: 
                   6380:  #adding a new value
                   6381:  $hash{'bar'}='foo';
                   6382:  &Apache::lonnet::cstore(\%hash);
                   6383: 
                   6384:  #retrieving the hash
                   6385:  my %history=&Apache::lonnet::restore();
                   6386: 
                   6387:  #print the hash
                   6388:  foreach my $key (sort(keys(%history))) {
                   6389:    print("\%history{$key} = $history{$key}");
                   6390:  }
                   6391: 
                   6392: Will print out:
1.191     harris41 6393: 
1.394     bowersj2 6394:  %history{1:foo} = bar
                   6395:  %history{1:keys} = foo:timestamp
                   6396:  %history{1:timestamp} = 990455579
                   6397:  %history{2:bar} = foo
                   6398:  %history{2:foo} = notbar
                   6399:  %history{2:keys} = foo:bar:timestamp
                   6400:  %history{2:timestamp} = 990455580
                   6401:  %history{bar} = foo
                   6402:  %history{foo} = notbar
                   6403:  %history{timestamp} = 990455580
                   6404:  %history{version} = 2
                   6405: 
                   6406: Note that the special hash entries C<keys>, C<version> and
                   6407: C<timestamp> were added to the hash. C<version> will be equal to the
                   6408: total number of versions of the data that have been stored. The
                   6409: C<timestamp> attribute will be the UNIX time the hash was
                   6410: stored. C<keys> is available in every historical section to list which
                   6411: keys were added or changed at a specific historical revision of a
                   6412: hash.
                   6413: 
                   6414: B<Warning>: do not store the hash that restore returns directly. This
                   6415: will cause a mess since it will restore the historical keys as if the
                   6416: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6417: 
1.394     bowersj2 6418: Calling convention:
1.191     harris41 6419: 
1.394     bowersj2 6420:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6421:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6422: 
1.394     bowersj2 6423: For more detailed information, see lonnet specific documentation.
1.191     harris41 6424: 
1.394     bowersj2 6425: =head1 RETURN MESSAGES
1.191     harris41 6426: 
1.394     bowersj2 6427: =over 4
1.191     harris41 6428: 
1.394     bowersj2 6429: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6430: 
1.394     bowersj2 6431: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6432: when the connection is brought back up
1.191     harris41 6433: 
1.394     bowersj2 6434: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6435: for later delivery
1.191     harris41 6436: 
1.394     bowersj2 6437: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6438: 
1.394     bowersj2 6439: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6440: that was requested
1.191     harris41 6441: 
1.243     albertel 6442: =back
1.191     harris41 6443: 
1.243     albertel 6444: =head1 PUBLIC SUBROUTINES
1.191     harris41 6445: 
1.243     albertel 6446: =head2 Session Environment Functions
1.191     harris41 6447: 
1.243     albertel 6448: =over 4
1.191     harris41 6449: 
1.394     bowersj2 6450: =item * 
                   6451: X<appenv()>
                   6452: B<appenv(%hash)>: the value of %hash is written to
                   6453: the user envirnoment file, and will be restored for each access this
1.620     albertel 6454: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6455: process
1.191     harris41 6456: 
                   6457: =item *
1.394     bowersj2 6458: X<delenv()>
                   6459: B<delenv($regexp)>: removes all items from the session
                   6460: environment file that matches the regular expression in $regexp. The
1.620     albertel 6461: values are also delted from the current processes %env.
1.191     harris41 6462: 
1.243     albertel 6463: =back
                   6464: 
                   6465: =head2 User Information
1.191     harris41 6466: 
1.243     albertel 6467: =over 4
1.191     harris41 6468: 
                   6469: =item *
1.394     bowersj2 6470: X<queryauthenticate()>
                   6471: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6472: authentication scheme
                   6473: 
                   6474: =item *
1.394     bowersj2 6475: X<authenticate()>
                   6476: B<authenticate($uname,$upass,$udom)>: try to
                   6477: authenticate user from domain's lib servers (first use the current
                   6478: one). C<$upass> should be the users password.
1.191     harris41 6479: 
                   6480: =item *
1.394     bowersj2 6481: X<homeserver()>
                   6482: B<homeserver($uname,$udom)>: find the server which has
                   6483: the user's directory and files (there must be only one), this caches
                   6484: the answer, and also caches if there is a borken connection.
1.191     harris41 6485: 
                   6486: =item *
1.394     bowersj2 6487: X<idget()>
                   6488: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6489: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6490: username, and only 1 username per ID in a specific domain) (returns
                   6491: hash: id=>name,id=>name)
1.191     harris41 6492: 
                   6493: =item *
1.394     bowersj2 6494: X<idrget()>
                   6495: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6496: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6497: 
                   6498: =item *
1.394     bowersj2 6499: X<idput()>
                   6500: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6501: 
                   6502: =item *
1.394     bowersj2 6503: X<rolesinit()>
                   6504: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6505: 
                   6506: =item *
1.551     albertel 6507: X<getsection()>
                   6508: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6509: course $cname, return section name/number or '' for "not in course"
                   6510: and '-1' for "no section"
                   6511: 
                   6512: =item *
1.394     bowersj2 6513: X<userenvironment()>
                   6514: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6515: passed in @what from the requested user's environment, returns a hash
                   6516: 
                   6517: =back
                   6518: 
                   6519: =head2 User Roles
                   6520: 
                   6521: =over 4
                   6522: 
                   6523: =item *
                   6524: 
                   6525: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6526: actions
                   6527:  F: full access
                   6528:  U,I,K: authentication modes (cxx only)
                   6529:  '': forbidden
                   6530:  1: user needs to choose course
                   6531:  2: browse allowed
                   6532: 
                   6533: =item *
                   6534: 
                   6535: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6536: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6537: and course level
                   6538: 
                   6539: =item *
                   6540: 
                   6541: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6542: explanation of a user role term
                   6543: 
                   6544: =back
                   6545: 
                   6546: =head2 User Modification
                   6547: 
                   6548: =over 4
                   6549: 
                   6550: =item *
                   6551: 
                   6552: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6553: user for the level given by URL.  Optional start and end dates (leave empty
                   6554: string or zero for "no date")
1.191     harris41 6555: 
                   6556: =item *
                   6557: 
1.243     albertel 6558: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6559: change a users, password, possible return values are: ok,
                   6560: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6561: refused
1.191     harris41 6562: 
                   6563: =item *
                   6564: 
1.243     albertel 6565: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6566: 
                   6567: =item *
                   6568: 
1.243     albertel 6569: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6570: modify user
1.191     harris41 6571: 
                   6572: =item *
                   6573: 
1.286     matthew  6574: modifystudent
                   6575: 
                   6576: modify a students enrollment and identification information.
                   6577: The course id is resolved based on the current users environment.  
                   6578: This means the envoking user must be a course coordinator or otherwise
                   6579: associated with a course.
                   6580: 
1.297     matthew  6581: This call is essentially a wrapper for lonnet::modifyuser and
                   6582: lonnet::modify_student_enrollment
1.286     matthew  6583: 
                   6584: Inputs: 
                   6585: 
                   6586: =over 4
                   6587: 
                   6588: =item B<$udom> Students loncapa domain
                   6589: 
                   6590: =item B<$uname> Students loncapa login name
                   6591: 
                   6592: =item B<$uid> Students id/student number
                   6593: 
                   6594: =item B<$umode> Students authentication mode
                   6595: 
                   6596: =item B<$upass> Students password
                   6597: 
                   6598: =item B<$first> Students first name
                   6599: 
                   6600: =item B<$middle> Students middle name
                   6601: 
                   6602: =item B<$last> Students last name
                   6603: 
                   6604: =item B<$gene> Students generation
                   6605: 
                   6606: =item B<$usec> Students section in course
                   6607: 
                   6608: =item B<$end> Unix time of the roles expiration
                   6609: 
                   6610: =item B<$start> Unix time of the roles start date
                   6611: 
                   6612: =item B<$forceid> If defined, allow $uid to be changed
                   6613: 
                   6614: =item B<$desiredhome> server to use as home server for student
                   6615: 
                   6616: =back
1.297     matthew  6617: 
                   6618: =item *
                   6619: 
                   6620: modify_student_enrollment
                   6621: 
                   6622: Change a students enrollment status in a class.  The environment variable
                   6623: 'role.request.course' must be defined for this function to proceed.
                   6624: 
                   6625: Inputs:
                   6626: 
                   6627: =over 4
                   6628: 
                   6629: =item $udom, students domain
                   6630: 
                   6631: =item $uname, students name
                   6632: 
                   6633: =item $uid, students user id
                   6634: 
                   6635: =item $first, students first name
                   6636: 
                   6637: =item $middle
                   6638: 
                   6639: =item $last
                   6640: 
                   6641: =item $gene
                   6642: 
                   6643: =item $usec
                   6644: 
                   6645: =item $end
                   6646: 
                   6647: =item $start
                   6648: 
                   6649: =back
                   6650: 
1.191     harris41 6651: 
                   6652: =item *
                   6653: 
1.243     albertel 6654: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   6655: custom role; give a custom role to a user for the level given by URL.  Specify
                   6656: name and domain of role author, and role name
1.191     harris41 6657: 
                   6658: =item *
                   6659: 
1.243     albertel 6660: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 6661: 
                   6662: =item *
                   6663: 
1.243     albertel 6664: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   6665: 
                   6666: =back
                   6667: 
                   6668: =head2 Course Infomation
                   6669: 
                   6670: =over 4
1.191     harris41 6671: 
                   6672: =item *
                   6673: 
1.631     albertel 6674: coursedescription($courseid) : returns a hash of information about the
                   6675: specified course id, including all environment settings for the
                   6676: course, the description of the course will be in the hash under the
                   6677: key 'description'
1.191     harris41 6678: 
                   6679: =item *
                   6680: 
1.624     albertel 6681: resdata($name,$domain,$type,@which) : request for current parameter
                   6682: setting for a specific $type, where $type is either 'course' or 'user',
                   6683: @what should be a list of parameters to ask about. This routine caches
                   6684: answers for 5 minutes.
1.243     albertel 6685: 
                   6686: =back
                   6687: 
                   6688: =head2 Course Modification
                   6689: 
                   6690: =over 4
1.191     harris41 6691: 
                   6692: =item *
                   6693: 
1.243     albertel 6694: writecoursepref($courseid,%prefs) : write preferences (environment
                   6695: database) for a course
1.191     harris41 6696: 
                   6697: =item *
                   6698: 
1.243     albertel 6699: createcourse($udom,$description,$url) : make/modify course
                   6700: 
                   6701: =back
                   6702: 
                   6703: =head2 Resource Subroutines
                   6704: 
                   6705: =over 4
1.191     harris41 6706: 
                   6707: =item *
                   6708: 
1.243     albertel 6709: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 6710: 
                   6711: =item *
                   6712: 
1.243     albertel 6713: repcopy($filename) : subscribes to the requested file, and attempts to
                   6714: replicate from the owning library server, Might return
1.607     raeburn  6715: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   6716: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 6717: resource. Expects the local filesystem pathname
                   6718: (/home/httpd/html/res/....)
                   6719: 
                   6720: =back
                   6721: 
                   6722: =head2 Resource Information
                   6723: 
                   6724: =over 4
1.191     harris41 6725: 
                   6726: =item *
                   6727: 
1.243     albertel 6728: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   6729: a vairety of different possible values, $varname should be a request
                   6730: string, and the other parameters can be used to specify who and what
                   6731: one is asking about.
                   6732: 
                   6733: Possible values for $varname are environment.lastname (or other item
                   6734: from the envirnment hash), user.name (or someother aspect about the
                   6735: user), resource.0.maxtries (or some other part and parameter of a
                   6736: resource)
1.204     albertel 6737: 
                   6738: =item *
                   6739: 
1.243     albertel 6740: directcondval($number) : get current value of a condition; reads from a state
                   6741: string
1.204     albertel 6742: 
                   6743: =item *
                   6744: 
1.243     albertel 6745: condval($condidx) : value of condition index based on state
1.204     albertel 6746: 
                   6747: =item *
                   6748: 
1.243     albertel 6749: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   6750: resource's metadata, $what should be either a specific key, or either
                   6751: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   6752: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   6753: 
                   6754: this function automatically caches all requests
1.191     harris41 6755: 
                   6756: =item *
                   6757: 
1.243     albertel 6758: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   6759: network of library servers; returns file handle of where SQL and regex results
                   6760: will be stored for query
1.191     harris41 6761: 
                   6762: =item *
                   6763: 
1.243     albertel 6764: symbread($filename) : return symbolic list entry (filename argument optional);
                   6765: returns the data handle
1.191     harris41 6766: 
                   6767: =item *
                   6768: 
1.243     albertel 6769: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 6770: a possible symb for the URL in $thisfn, and if is an encryypted
                   6771: resource that the user accessed using /enc/ returns a 1 on success, 0
                   6772: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 6773: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 6774: 
1.191     harris41 6775: 
                   6776: =item *
                   6777: 
1.243     albertel 6778: symbclean($symb) : removes versions numbers from a symb, returns the
                   6779: cleaned symb
1.191     harris41 6780: 
                   6781: =item *
                   6782: 
1.243     albertel 6783: is_on_map($uri) : checks if the $uri is somewhere on the current
                   6784: course map, user must be in a course for it to work.
1.191     harris41 6785: 
                   6786: =item *
                   6787: 
1.243     albertel 6788: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 6789: 
                   6790: =item *
                   6791: 
1.243     albertel 6792: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   6793: a random seed, all arguments are optional, if they aren't sent it uses the
                   6794: environment to derive them. Note: if symb isn't sent and it can't get one
                   6795: from &symbread it will use the current time as its return value
1.191     harris41 6796: 
                   6797: =item *
                   6798: 
1.243     albertel 6799: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   6800: unfakeable, receipt
1.191     harris41 6801: 
                   6802: =item *
                   6803: 
1.620     albertel 6804: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 6805: 
                   6806: =item *
                   6807: 
1.243     albertel 6808: countacc($url) : count the number of accesses to a given URL
1.191     harris41 6809: 
                   6810: =item *
                   6811: 
1.243     albertel 6812: 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
1.191     harris41 6813: 
                   6814: =item *
                   6815: 
1.243     albertel 6816: 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)
1.191     harris41 6817: 
                   6818: =item *
                   6819: 
1.243     albertel 6820: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 6821: 
                   6822: =item *
                   6823: 
1.243     albertel 6824: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   6825: forcing spreadsheet to reevaluate the resource scores next time.
                   6826: 
                   6827: =back
                   6828: 
                   6829: =head2 Storing/Retreiving Data
                   6830: 
                   6831: =over 4
1.191     harris41 6832: 
                   6833: =item *
                   6834: 
1.243     albertel 6835: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   6836: for this url; hashref needs to be given and should be a \%hashname; the
                   6837: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 6838: be derived from the env
1.191     harris41 6839: 
                   6840: =item *
                   6841: 
1.243     albertel 6842: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   6843: uses critical subroutine
1.191     harris41 6844: 
                   6845: =item *
                   6846: 
1.243     albertel 6847: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   6848: all args are optional
1.191     harris41 6849: 
                   6850: =item *
                   6851: 
1.243     albertel 6852: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   6853: works very similar to store/cstore, but all data is stored in a
                   6854: temporary location and can be reset using tmpreset, $storehash should
                   6855: be a hash reference, returns nothing on success
1.191     harris41 6856: 
                   6857: =item *
                   6858: 
1.243     albertel 6859: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   6860: similar to restore, but all data is stored in a temporary location and
                   6861: can be reset using tmpreset. Returns a hash of values on success,
                   6862: error string otherwise.
1.191     harris41 6863: 
                   6864: =item *
                   6865: 
1.243     albertel 6866: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   6867: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 6868: 
                   6869: =item *
                   6870: 
1.243     albertel 6871: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6872: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 6873: 
                   6874: =item *
                   6875: 
1.243     albertel 6876: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   6877: namesp ($udom and $uname are optional)
1.191     harris41 6878: 
                   6879: =item *
                   6880: 
1.243     albertel 6881: dump($namespace,$udom,$uname,$regexp) : 
                   6882: dumps the complete (or key matching regexp) namespace into a hash
                   6883: ($udom, $uname and $regexp are optional)
1.449     matthew  6884: 
                   6885: =item *
                   6886: 
                   6887: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   6888: $store can be a scalar, an array reference, or if the amount to be 
                   6889: incremented is > 1, a hash reference.
                   6890: 
                   6891: ($udom and $uname are optional)
1.191     harris41 6892: 
                   6893: =item *
                   6894: 
1.243     albertel 6895: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   6896: ($udom and $uname are optional)
1.191     harris41 6897: 
                   6898: =item *
                   6899: 
1.524     raeburn  6900: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   6901: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
                   6902: used in records written by &store and retrieved by &restore.  This function 
                   6903: was created for use in editing discussion posts, without incrementing the
                   6904: version number included in the key for a particular post. The colon 
                   6905: separated list of attribute names (e.g., the value associated with the key 
                   6906: 1:keys:$symb) is also generated and passed in the ampersand separated 
                   6907: items sent to lonnet::reply().  
                   6908: 
                   6909: =item *
                   6910: 
1.243     albertel 6911: cput($namespace,$storehash,$udom,$uname) : critical put
                   6912: ($udom and $uname are optional)
1.191     harris41 6913: 
                   6914: =item *
                   6915: 
1.243     albertel 6916: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6917: reference filled in from namesp (encrypts the return communication)
                   6918: ($udom and $uname are optional)
1.191     harris41 6919: 
                   6920: =item *
                   6921: 
1.243     albertel 6922: log($udom,$name,$home,$message) : write to permanent log for user; use
                   6923: critical subroutine
                   6924: 
                   6925: =back
                   6926: 
                   6927: =head2 Network Status Functions
                   6928: 
                   6929: =over 4
1.191     harris41 6930: 
                   6931: =item *
                   6932: 
                   6933: dirlist($uri) : return directory list based on URI
                   6934: 
                   6935: =item *
                   6936: 
1.243     albertel 6937: spareserver() : find server with least workload from spare.tab
                   6938: 
                   6939: =back
                   6940: 
                   6941: =head2 Apache Request
                   6942: 
                   6943: =over 4
1.191     harris41 6944: 
                   6945: =item *
                   6946: 
1.243     albertel 6947: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   6948: localhost, posts hash
                   6949: 
                   6950: =back
                   6951: 
                   6952: =head2 Data to String to Data
                   6953: 
                   6954: =over 4
1.191     harris41 6955: 
                   6956: =item *
                   6957: 
1.243     albertel 6958: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   6959: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 6960: 
                   6961: =item *
                   6962: 
1.243     albertel 6963: hashref2str($hashref) : convert a hashref into a string complete with
                   6964: escaping and '=' and '&' separators, supports elements that are
                   6965: arrayrefs and hashrefs
1.191     harris41 6966: 
                   6967: =item *
                   6968: 
1.243     albertel 6969: arrayref2str($arrayref) : convert an arrayref into a string complete
                   6970: with escaping and '&' separators, supports elements that are arrayrefs
                   6971: and hashrefs
1.191     harris41 6972: 
                   6973: =item *
                   6974: 
1.243     albertel 6975: str2hash($string) : convert string to hash using unescaping and
                   6976: splitting on '=' and '&', supports elements that are arrayrefs and
                   6977: hashrefs
1.191     harris41 6978: 
                   6979: =item *
                   6980: 
1.243     albertel 6981: str2array($string) : convert string to hash using unescaping and
                   6982: splitting on '&', supports elements that are arrayrefs and hashrefs
                   6983: 
                   6984: =back
                   6985: 
                   6986: =head2 Logging Routines
                   6987: 
                   6988: =over 4
                   6989: 
                   6990: These routines allow one to make log messages in the lonnet.log and
                   6991: lonnet.perm logfiles.
1.191     harris41 6992: 
                   6993: =item *
                   6994: 
1.243     albertel 6995: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 6996: 
                   6997: =item *
                   6998: 
1.243     albertel 6999: logthis() : append message to the normal lonnet.log file, it gets
                   7000: preiodically rolled over and deleted.
1.191     harris41 7001: 
                   7002: =item *
                   7003: 
1.243     albertel 7004: logperm() : append a permanent message to lonnet.perm.log, this log
                   7005: file never gets deleted by any automated portion of the system, only
                   7006: messages of critical importance should go in here.
                   7007: 
                   7008: =back
                   7009: 
                   7010: =head2 General File Helper Routines
                   7011: 
                   7012: =over 4
1.191     harris41 7013: 
                   7014: =item *
                   7015: 
1.481     raeburn  7016: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7017: (a) files in /uploaded
                   7018:   (i) If a local copy of the file exists - 
                   7019:       compares modification date of local copy with last-modified date for 
                   7020:       definitive version stored on home server for course. If local copy is 
                   7021:       stale, requests a new version from the home server and stores it. 
                   7022:       If the original has been removed from the home server, then local copy 
                   7023:       is unlinked.
                   7024:   (ii) If local copy does not exist -
                   7025:       requests the file from the home server and stores it. 
                   7026:   
                   7027:   If $caller is 'uploadrep':  
                   7028:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7029:     for request for files originally uploaded via DOCS. 
                   7030:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7031:   
                   7032:   Otherwise:
                   7033:      This indicates a call from the content generation phase of the request.
                   7034:      -  returns the entire contents of the file or -1.
                   7035:      
                   7036: (b) files in /res
                   7037:    - returns the entire contents of a file or -1; 
                   7038:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7039: 
                   7040: =item *
                   7041: 
1.243     albertel 7042: filelocation($dir,$file) : returns file system location of a file
                   7043: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7044: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7045: and a file of ../bob will become /a/bob)
1.191     harris41 7046: 
                   7047: =item *
                   7048: 
                   7049: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7050: filelocation except for hrefs
                   7051: 
                   7052: =item *
                   7053: 
                   7054: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7055: 
1.243     albertel 7056: =back
                   7057: 
1.608     albertel 7058: =head2 Usererfile file routines (/uploaded*)
                   7059: 
                   7060: =over 4
                   7061: 
                   7062: =item *
                   7063: 
                   7064: userfileupload(): main rotine for putting a file in a user or course's
                   7065:                   filespace, arguments are,
                   7066: 
1.620     albertel 7067:  formname - required - this is the name of the element in $env where the
1.608     albertel 7068:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7069:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7070:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7071:  coursedoc - if true, store the file in the course of the active role
                   7072:              of the current user
                   7073:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7074:          if undefined, it will be placed in "unknown"
                   7075: 
                   7076:  (This routine calls clean_filename() to remove any dangerous
                   7077:  characters from the filename, and then calls finuserfileupload() to
                   7078:  complete the transaction)
                   7079: 
                   7080:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7081:  and /adm/notfound.html if unsuccessful
                   7082: 
                   7083: =item *
                   7084: 
                   7085: clean_filename(): routine for cleaing a filename up for storage in
                   7086:                  userfile space, argument is:
                   7087: 
                   7088:  filename - proposed filename
                   7089: 
                   7090: returns: the new clean filename
                   7091: 
                   7092: =item *
                   7093: 
                   7094: finishuserfileupload(): routine that creaes and sends the file to
                   7095: userspace, probably shouldn't be called directly
                   7096: 
                   7097:   docuname: username or courseid of destination for the file
                   7098:   docudom: domain of user/course of destination for the file
                   7099:   formname: same as for userfileupload()
                   7100:   fname: filename (inculding subdirectories) for the file
                   7101: 
                   7102:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7103:  and /adm/notfound.html if unsuccessful
                   7104: 
                   7105: =item *
                   7106: 
                   7107: renameuserfile(): renames an existing userfile to a new name
                   7108: 
                   7109:   Args:
                   7110:    docuname: username or courseid of destination for the file
                   7111:    docudom: domain of user/course of destination for the file
                   7112:    old: current file name (including any subdirs under userfiles)
                   7113:    new: desired file name (including any subdirs under userfiles)
                   7114: 
                   7115: =item *
                   7116: 
                   7117: mkdiruserfile(): creates a directory is a userfiles dir
                   7118: 
                   7119:   Args:
                   7120:    docuname: username or courseid of destination for the file
                   7121:    docudom: domain of user/course of destination for the file
                   7122:    dir: dir to create (including any subdirs under userfiles)
                   7123: 
                   7124: =item *
                   7125: 
                   7126: removeuserfile(): removes a file that exists in userfiles
                   7127: 
                   7128:   Args:
                   7129:    docuname: username or courseid of destination for the file
                   7130:    docudom: domain of user/course of destination for the file
                   7131:    fname: filname to delete (including any subdirs under userfiles)
                   7132: 
                   7133: =item *
                   7134: 
                   7135: removeuploadedurl(): convience function for removeuserfile()
                   7136: 
                   7137:   Args:
                   7138:    url:  a full /uploaded/... url to delete
                   7139: 
                   7140: =back
                   7141: 
1.243     albertel 7142: =head2 HTTP Helper Routines
                   7143: 
                   7144: =over 4
                   7145: 
1.191     harris41 7146: =item *
                   7147: 
                   7148: escape() : unpack non-word characters into CGI-compatible hex codes
                   7149: 
                   7150: =item *
                   7151: 
                   7152: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7153: 
1.243     albertel 7154: =back
                   7155: 
                   7156: =head1 PRIVATE SUBROUTINES
                   7157: 
                   7158: =head2 Underlying communication routines (Shouldn't call)
                   7159: 
                   7160: =over 4
                   7161: 
                   7162: =item *
                   7163: 
                   7164: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7165: 
                   7166: =item *
                   7167: 
                   7168: reply() : uses subreply to send a message to remote machine, logs all failures
                   7169: 
                   7170: =item *
                   7171: 
                   7172: critical() : passes a critical message to another server; if cannot
                   7173: get through then place message in connection buffer directory and
                   7174: returns con_delayed, if incapable of saving message, returns
                   7175: con_failed
                   7176: 
                   7177: =item *
                   7178: 
                   7179: reconlonc() : tries to reconnect lonc client processes.
                   7180: 
                   7181: =back
                   7182: 
                   7183: =head2 Resource Access Logging
                   7184: 
                   7185: =over 4
                   7186: 
                   7187: =item *
                   7188: 
                   7189: flushcourselogs() : flush (save) buffer logs and access logs
                   7190: 
                   7191: =item *
                   7192: 
                   7193: courselog($what) : save message for course in hash
                   7194: 
                   7195: =item *
                   7196: 
                   7197: courseacclog($what) : save message for course using &courselog().  Perform
                   7198: special processing for specific resource types (problems, exams, quizzes, etc).
                   7199: 
1.191     harris41 7200: =item *
                   7201: 
                   7202: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7203: as a PerlChildExitHandler
1.243     albertel 7204: 
                   7205: =back
                   7206: 
                   7207: =head2 Other
                   7208: 
                   7209: =over 4
                   7210: 
                   7211: =item *
                   7212: 
                   7213: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7214: 
                   7215: =back
                   7216: 
                   7217: =cut

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