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

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

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