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

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

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