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

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

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