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

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

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