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

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

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