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

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

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