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

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

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