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

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

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