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

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

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