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

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

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