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

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

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