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

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

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