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

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

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