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

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

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