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

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

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