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

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

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