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

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

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