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

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

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