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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.297   ! matthew     4: # $Id: lonnet.pm,v 1.296 2002/10/10 14:34:05 www 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: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
                     29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
                     30: # 11/8,11/16,11/18,11/22,11/23,12/22,
                     31: # 01/06,01/13,02/24,02/28,02/29,
                     32: # 03/01,03/02,03/06,03/07,03/13,
                     33: # 04/05,05/29,05/31,06/01,
                     34: # 06/05,06/26 Gerd Kortemeyer
                     35: # 06/26 Ben Tyszka
                     36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
                     37: # 08/14 Ben Tyszka
                     38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
                     39: # 10/04 Gerd Kortemeyer
                     40: # 10/04 Guy Albertelli
                     41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
                     42: # 10/30,10/31,
                     43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
                     44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
                     45: # 05/01/01 Guy Albertelli
                     46: # 05/01,06/01,09/01 Gerd Kortemeyer
                     47: # 09/01 Guy Albertelli
                     48: # 09/01,10/01,11/01 Gerd Kortemeyer
                     49: # YEAR=2001
                     50: # 02/27/01 Scott Harrison
                     51: # 3/2 Gerd Kortemeyer
                     52: # 3/15,3/19 Scott Harrison
                     53: # 3/19,3/20 Gerd Kortemeyer
                     54: # 3/22,3/27,4/2,4/16,4/17 Scott Harrison
                     55: # 5/26,5/28 Gerd Kortemeyer
                     56: # 5/30 H. K. Ng
                     57: # 6/1 Gerd Kortemeyer
                     58: # July Guy Albertelli
                     59: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
                     60: # 10/2 Gerd Kortemeyer
                     61: # 10/5,10/10,11/13,11/15 Scott Harrison
1.179     www        62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
1.182     matthew    63: # 12/5 Matthew Hall
1.184     www        64: # 12/5 Guy Albertelli
1.190     www        65: # 12/6,12/7,12/12 Gerd Kortemeyer
1.191     harris41   66: # 12/18 Scott Harrison
1.195     www        67: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
1.196     www        68: # YEAR=2002
1.200     www        69: # 1/4,2/4,2/7 Gerd Kortemeyer
1.171     www        70: #
1.169     harris41   71: ###
                     72: 
1.1       albertel   73: package Apache::lonnet;
                     74: 
                     75: use strict;
                     76: use Apache::File;
1.8       www        77: use LWP::UserAgent();
1.15      www        78: use HTTP::Headers;
1.11      www        79: use vars 
1.231     stredwic   80: qw(%perlvar %hostname %homecache %badServerCache %hostip %spareid %hostdom 
1.192     www        81:    %libserv %pr %prp %metacache %packagetab 
1.188     www        82:    %courselogs %accesshash $processmarker $dumpcount 
1.245     www        83:    %coursedombuf %coursehombuf %courseresdatacache %domaindescription);
1.1       albertel   84: use IO::Socket;
1.31      www        85: use GDBM_File;
1.8       www        86: use Apache::Constants qw(:common :http);
1.208     albertel   87: use HTML::LCParser;
1.88      www        88: use Fcntl qw(:flock);
1.294     matthew    89: use Apache::loncoursedata;
                     90: 
1.195     www        91: my $readit;
1.1       albertel   92: 
                     93: # --------------------------------------------------------------------- Logging
                     94: 
1.163     harris41   95: sub logtouch {
                     96:     my $execdir=$perlvar{'lonDaemons'};
                     97:     unless (-e "$execdir/logs/lonnet.log") {
                     98: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                     99: 	close $fh;
                    100:     }
                    101:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    102:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    103: }
                    104: 
1.1       albertel  105: sub logthis {
                    106:     my $message=shift;
                    107:     my $execdir=$perlvar{'lonDaemons'};
                    108:     my $now=time;
                    109:     my $local=localtime($now);
1.162     harris41  110:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                    111:     print $fh "$local ($$): $message\n";
1.1       albertel  112:     return 1;
                    113: }
                    114: 
                    115: sub logperm {
                    116:     my $message=shift;
                    117:     my $execdir=$perlvar{'lonDaemons'};
                    118:     my $now=time;
                    119:     my $local=localtime($now);
1.162     harris41  120:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
                    121:     print $fh "$now:$message:$local\n";
1.1       albertel  122:     return 1;
                    123: }
                    124: 
                    125: # -------------------------------------------------- Non-critical communication
                    126: sub subreply {
                    127:     my ($cmd,$server)=@_;
                    128:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    129:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    130:                                      Type    => SOCK_STREAM,
                    131:                                      Timeout => 10)
                    132:        or return "con_lost";
                    133:     print $client "$cmd\n";
                    134:     my $answer=<$client>;
1.9       www       135:     if (!$answer) { $answer="con_lost"; }
1.1       albertel  136:     chomp($answer);
                    137:     return $answer;
                    138: }
                    139: 
                    140: sub reply {
                    141:     my ($cmd,$server)=@_;
1.205     www       142:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  143:     my $answer=subreply($cmd,$server);
1.203     www       144:     if ($answer eq 'con_lost') {
1.233     albertel  145:        #sleep 5; 
                    146:        #$answer=subreply($cmd,$server);
                    147:        #if ($answer eq 'con_lost') {
                    148: 	#   &logthis("Second attempt con_lost on $server");
                    149:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
                    150:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    151:         #                                    Type    => SOCK_STREAM,
                    152:         #                                    Timeout => 10)
                    153:         #              or return "con_lost";
                    154:         #   &logthis("Killing socket");
                    155:         #   print $client "close_connection_exit\n";
                    156:            #sleep 5;
                    157:         #   $answer=subreply($cmd,$server);       
                    158:        #}   
1.203     www       159:     }
1.65      www       160:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       161:        &logthis("<font color=blue>WARNING:".
                    162:                 " $cmd to $server returned $answer</font>");
                    163:     }
1.1       albertel  164:     return $answer;
                    165: }
                    166: 
                    167: # ----------------------------------------------------------- Send USR1 to lonc
                    168: 
                    169: sub reconlonc {
                    170:     my $peerfile=shift;
                    171:     &logthis("Trying to reconnect for $peerfile");
                    172:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                    173:     if (my $fh=Apache::File->new("$loncfile")) {
                    174: 	my $loncpid=<$fh>;
                    175:         chomp($loncpid);
                    176:         if (kill 0 => $loncpid) {
                    177: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    178:             kill USR1 => $loncpid;
                    179:             sleep 1;
                    180:             if (-e "$peerfile") { return; }
                    181:             &logthis("$peerfile still not there, give it another try");
                    182:             sleep 5;
                    183:             if (-e "$peerfile") { return; }
1.12      www       184:             &logthis(
                    185:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  186:         } else {
1.12      www       187: 	    &logthis(
                    188:                "<font color=blue>WARNING:".
                    189:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  190:         }
                    191:     } else {
1.12      www       192:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  193:     }
                    194: }
                    195: 
                    196: # ------------------------------------------------------ Critical communication
1.12      www       197: 
1.1       albertel  198: sub critical {
                    199:     my ($cmd,$server)=@_;
1.89      www       200:     unless ($hostname{$server}) {
                    201:         &logthis("<font color=blue>WARNING:".
                    202:                " Critical message to unknown server ($server)</font>");
                    203:         return 'no_such_host';
                    204:     }
1.1       albertel  205:     my $answer=reply($cmd,$server);
                    206:     if ($answer eq 'con_lost') {
                    207:         my $pingreply=reply('ping',$server);
                    208: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
                    209:         my $pongreply=reply('pong',$server);
                    210:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
                    211:         $answer=reply($cmd,$server);
                    212:         if ($answer eq 'con_lost') {
                    213:             my $now=time;
                    214:             my $middlename=$cmd;
1.5       www       215:             $middlename=substr($middlename,0,16);
1.1       albertel  216:             $middlename=~s/\W//g;
                    217:             my $dfilename=
                    218:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
                    219:             {
                    220:              my $dfh;
                    221:              if ($dfh=Apache::File->new(">$dfilename")) {
1.7       www       222:                 print $dfh "$cmd\n";
1.1       albertel  223: 	     }
                    224:             }
                    225:             sleep 2;
                    226:             my $wcmd='';
                    227:             {
                    228: 	     my $dfh;
                    229:              if ($dfh=Apache::File->new("$dfilename")) {
                    230:                 $wcmd=<$dfh>;
                    231: 	     }
                    232:             }
                    233:             chomp($wcmd);
1.7       www       234:             if ($wcmd eq $cmd) {
1.12      www       235: 		&logthis("<font color=blue>WARNING: ".
                    236:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  237:                 &logperm("D:$server:$cmd");
                    238: 	        return 'con_delayed';
                    239:             } else {
1.12      www       240:                 &logthis("<font color=red>CRITICAL:"
                    241:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  242:                 &logperm("F:$server:$cmd");
                    243:                 return 'con_failed';
                    244:             }
                    245:         }
                    246:     }
                    247:     return $answer;
                    248: }
                    249: 
1.5       www       250: # ---------------------------------------------------------- Append Environment
                    251: 
                    252: sub appenv {
1.6       www       253:     my %newenv=@_;
1.191     harris41  254:     foreach (keys %newenv) {
1.35      www       255: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    256:             &logthis("<font color=blue>WARNING: ".
1.151     www       257:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    258:                 .'</font>');
1.35      www       259: 	    delete($newenv{$_});
                    260:         } else {
                    261:             $ENV{$_}=$newenv{$_};
                    262:         }
1.191     harris41  263:     }
1.95      www       264: 
                    265:     my $lockfh;
                    266:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       267:        return 'error: '.$!;
1.95      www       268:     }
                    269:     unless (flock($lockfh,LOCK_EX)) {
                    270:          &logthis("<font color=blue>WARNING: ".
                    271:                   'Could not obtain exclusive lock in appenv: '.$!);
                    272:          $lockfh->close();
                    273:          return 'error: '.$!;
                    274:     }
                    275: 
1.6       www       276:     my @oldenv;
                    277:     {
                    278:      my $fh;
                    279:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       280: 	return 'error: '.$!;
1.6       www       281:      }
                    282:      @oldenv=<$fh>;
1.89      www       283:      $fh->close();
1.6       www       284:     }
                    285:     for (my $i=0; $i<=$#oldenv; $i++) {
                    286:         chomp($oldenv[$i]);
1.9       www       287:         if ($oldenv[$i] ne '') {
                    288:            my ($name,$value)=split(/=/,$oldenv[$i]);
1.24      www       289:            unless (defined($newenv{$name})) {
                    290: 	      $newenv{$name}=$value;
                    291: 	   }
1.9       www       292:         }
1.6       www       293:     }
                    294:     {
                    295:      my $fh;
                    296:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    297: 	return 'error';
                    298:      }
                    299:      my $newname;
1.93      www       300:      foreach $newname (keys %newenv) {
1.6       www       301: 	 print $fh "$newname=$newenv{$newname}\n";
                    302:      }
1.86      albertel  303:      $fh->close();
1.56      www       304:     }
1.95      www       305: 
                    306:     $lockfh->close();
1.56      www       307:     return 'ok';
                    308: }
                    309: # ----------------------------------------------------- Delete from Environment
                    310: 
                    311: sub delenv {
                    312:     my $delthis=shift;
                    313:     my %newenv=();
                    314:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    315:         &logthis("<font color=blue>WARNING: ".
                    316:                 "Attempt to delete from environment ".$delthis);
                    317:         return 'error';
                    318:     }
                    319:     my @oldenv;
                    320:     {
                    321:      my $fh;
                    322:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
                    323: 	return 'error';
                    324:      }
1.89      www       325:      unless (flock($fh,LOCK_SH)) {
                    326:          &logthis("<font color=blue>WARNING: ".
                    327:                   'Could not obtain shared lock in delenv: '.$!);
                    328:          $fh->close();
                    329:          return 'error: '.$!;
                    330:      }
1.56      www       331:      @oldenv=<$fh>;
1.89      www       332:      $fh->close();
1.56      www       333:     }
                    334:     {
                    335:      my $fh;
                    336:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    337: 	return 'error';
                    338:      }
1.89      www       339:      unless (flock($fh,LOCK_EX)) {
                    340:          &logthis("<font color=blue>WARNING: ".
                    341:                   'Could not obtain exclusive lock in delenv: '.$!);
                    342:          $fh->close();
                    343:          return 'error: '.$!;
                    344:      }
1.191     harris41  345:      foreach (@oldenv) {
1.56      www       346: 	 unless ($_=~/^$delthis/) { print $fh $_; }
1.191     harris41  347:      }
1.87      www       348:      $fh->close();
1.5       www       349:     }
                    350:     return 'ok';
1.283     www       351: }
                    352: 
                    353: # ------------------------------------------ Fight off request when overloaded
                    354: 
                    355: sub overloaderror {
                    356:     my ($r,$checkserver)=@_;
                    357:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    358:     my $loadavg;
                    359:     if ($checkserver eq $perlvar{'lonHostID'}) {
                    360:        my $loadfile=Apache::File->new('/proc/loadavg');
                    361:        $loadavg=<$loadfile>;
                    362:        $loadavg =~ s/\s.*//g;
1.285     matthew   363:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.283     www       364:     } else {
                    365:        $loadavg=&reply('load',$checkserver);
                    366:     }
1.285     matthew   367:     my $overload=$loadavg-100;
1.283     www       368:     if ($overload>0) {
1.285     matthew   369: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       370:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
                    371:         return 413;
                    372:     }    
                    373:     return '';
1.5       www       374: }
1.1       albertel  375: 
                    376: # ------------------------------ Find server with least workload from spare.tab
1.11      www       377: 
1.1       albertel  378: sub spareserver {
1.284     matthew   379:     my $loadpercent = shift;
1.1       albertel  380:     my $tryserver;
                    381:     my $spareserver='';
1.284     matthew   382:     my $lowestserver=$loadpercent; 
1.1       albertel  383:     foreach $tryserver (keys %spareid) {
                    384:        my $answer=reply('load',$tryserver);
                    385:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    386: 	   $spareserver="http://$hostname{$tryserver}";
                    387:            $lowestserver=$answer;
                    388:        }
                    389:     }    
                    390:     return $spareserver;
1.202     matthew   391: }
                    392: 
                    393: # --------------------------------------------- Try to change a user's password
                    394: 
                    395: sub changepass {
                    396:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    397:     $currentpass = &escape($currentpass);
                    398:     $newpass     = &escape($newpass);
                    399:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    400: 		       $server);
                    401:     if (! $answer) {
                    402: 	&logthis("No reply on password change request to $server ".
                    403: 		 "by $uname in domain $udom.");
                    404:     } elsif ($answer =~ "^ok") {
                    405:         &logthis("$uname in $udom successfully changed their password ".
                    406: 		 "on $server.");
                    407:     } elsif ($answer =~ "^pwchange_failure") {
                    408: 	&logthis("$uname in $udom was unable to change their password ".
                    409: 		 "on $server.  The action was blocked by either lcpasswd ".
                    410: 		 "or pwchange");
                    411:     } elsif ($answer =~ "^non_authorized") {
                    412:         &logthis("$uname in $udom did not get their password correct when ".
                    413: 		 "attempting to change it on $server.");
                    414:     } elsif ($answer =~ "^auth_mode_error") {
                    415:         &logthis("$uname in $udom attempted to change their password despite ".
                    416: 		 "not being locally or internally authenticated on $server.");
                    417:     } elsif ($answer =~ "^unknown_user") {
                    418:         &logthis("$uname in $udom attempted to change their password ".
                    419: 		 "on $server but were unable to because $server is not ".
                    420: 		 "their home server.");
                    421:     } elsif ($answer =~ "^refused") {
                    422: 	&logthis("$server refused to change $uname in $udom password because ".
                    423: 		 "it was sent an unencrypted request to change the password.");
                    424:     }
                    425:     return $answer;
1.1       albertel  426: }
                    427: 
1.169     harris41  428: # ----------------------- Try to determine user's current authentication scheme
                    429: 
                    430: sub queryauthenticate {
                    431:     my ($uname,$udom)=@_;
                    432:     if (($perlvar{'lonRole'} eq 'library') && 
                    433:         ($udom eq $perlvar{'lonDefDomain'})) {
                    434: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    435: 			 $perlvar{'lonHostID'});
                    436: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    437: 	    if (length($answer)) {
                    438: 		return $answer;
                    439: 	    }
                    440: 	    else {
                    441: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    442: 		return 'no_host';
                    443: 	    }
                    444: 	}
                    445:     }
                    446: 
                    447:     my $tryserver;
                    448:     foreach $tryserver (keys %libserv) {
                    449: 	if ($hostdom{$tryserver} eq $udom) {
                    450:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    451: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    452: 	       if (length($answer)) {
                    453: 		   return $answer;
                    454: 	       }
                    455: 	       else {
                    456: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    457: 		   return 'no_host';
                    458: 	       }
                    459: 	   }
                    460:        }
                    461:     }
                    462:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    463:     return 'no_host';
                    464: }
                    465: 
1.1       albertel  466: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       467: 
1.1       albertel  468: sub authenticate {
                    469:     my ($uname,$upass,$udom)=@_;
1.12      www       470:     $upass=escape($upass);
1.199     www       471:     $uname=~s/\W//g;
1.1       albertel  472:     if (($perlvar{'lonRole'} eq 'library') && 
                    473:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       474:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       475:         if ($answer =~ /authorized/) {
1.9       www       476:               if ($answer eq 'authorized') {
                    477:                  &logthis("User $uname at $udom authorized by local server"); 
                    478:                  return $perlvar{'lonHostID'}; 
                    479:               }
                    480:               if ($answer eq 'non_authorized') {
                    481:                  &logthis("User $uname at $udom rejected by local server"); 
                    482:                  return 'no_host'; 
                    483:               }
1.2       www       484: 	}
1.1       albertel  485:     }
                    486: 
                    487:     my $tryserver;
                    488:     foreach $tryserver (keys %libserv) {
                    489: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       490:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  491:            if ($answer =~ /authorized/) {
1.9       www       492:               if ($answer eq 'authorized') {
                    493:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    494:                  return $tryserver; 
                    495:               }
                    496:               if ($answer eq 'non_authorized') {
                    497:                  &logthis("User $uname at $udom rejected by $tryserver");
                    498:                  return 'no_host';
                    499:               } 
1.1       albertel  500: 	   }
                    501:        }
1.9       www       502:     }
                    503:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  504:     return 'no_host';
                    505: }
                    506: 
                    507: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       508: 
1.1       albertel  509: sub homeserver {
1.230     stredwic  510:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  511:     my $index="$uname:$udom";
1.221     matthew   512:     if ($homecache{$index}) { 
                    513:         return "$homecache{$index}"; 
                    514:     }
1.1       albertel  515:     my $tryserver;
                    516:     foreach $tryserver (keys %libserv) {
1.230     stredwic  517:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  518: 		 exists($badServerCache{$tryserver}));
1.1       albertel  519: 	if ($hostdom{$tryserver} eq $udom) {
                    520:            my $answer=reply("home:$udom:$uname",$tryserver);
                    521:            if ($answer eq 'found') { 
1.221     matthew   522:               $homecache{$index}=$tryserver;
1.1       albertel  523:               return $tryserver; 
1.231     stredwic  524:            } elsif ($answer eq 'no_host') {
                    525: 	       $badServerCache{$tryserver}=1;
1.221     matthew   526:            }
1.1       albertel  527:        }
                    528:     }    
                    529:     return 'no_host';
1.70      www       530: }
                    531: 
                    532: # ------------------------------------- Find the usernames behind a list of IDs
                    533: 
                    534: sub idget {
                    535:     my ($udom,@ids)=@_;
                    536:     my %returnhash=();
                    537:     
                    538:     my $tryserver;
                    539:     foreach $tryserver (keys %libserv) {
                    540:        if ($hostdom{$tryserver} eq $udom) {
                    541: 	  my $idlist=join('&',@ids);
                    542:           $idlist=~tr/A-Z/a-z/; 
                    543: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    544:           my @answer=();
1.76      www       545:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       546: 	      @answer=split(/\&/,$reply);
                    547:           }                    ;
                    548:           my $i;
                    549:           for ($i=0;$i<=$#ids;$i++) {
                    550:               if ($answer[$i]) {
                    551: 		  $returnhash{$ids[$i]}=$answer[$i];
                    552:               } 
                    553:           }
                    554:        }
                    555:     }    
                    556:     return %returnhash;
                    557: }
                    558: 
                    559: # ------------------------------------- Find the IDs behind a list of usernames
                    560: 
                    561: sub idrget {
                    562:     my ($udom,@unames)=@_;
                    563:     my %returnhash=();
1.191     harris41  564:     foreach (@unames) {
1.70      www       565:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  566:     }
1.70      www       567:     return %returnhash;
                    568: }
                    569: 
                    570: # ------------------------------- Store away a list of names and associated IDs
                    571: 
                    572: sub idput {
                    573:     my ($udom,%ids)=@_;
                    574:     my %servers=();
1.191     harris41  575:     foreach (keys %ids) {
1.70      www       576:         my $uhom=&homeserver($_,$udom);
                    577:         if ($uhom ne 'no_host') {
                    578:             my $id=&escape($ids{$_});
                    579:             $id=~tr/A-Z/a-z/;
                    580:             my $unam=&escape($_);
                    581: 	    if ($servers{$uhom}) {
                    582: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    583:             } else {
                    584:                 $servers{$uhom}=$id.'='.$unam;
                    585:             }
                    586:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    587:         }
1.191     harris41  588:     }
                    589:     foreach (keys %servers) {
1.70      www       590:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  591:     }
1.70      www       592: }
                    593: 
                    594: # ------------------------------------- Find the section of student in a course
                    595: 
                    596: sub usection {
                    597:     my ($udom,$unam,$courseid)=@_;
                    598:     $courseid=~s/\_/\//g;
                    599:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  600:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    601:                         &homeserver($unam,$udom)))) {
1.70      www       602:         my ($key,$value)=split(/\=/,$_);
                    603:         $key=&unescape($key);
                    604:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                    605:             my $section=$1;
                    606:             if ($key eq $courseid.'_st') { $section=''; }
                    607: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    608:             my $now=time;
                    609:             my $notactive=0;
                    610:             if ($start) {
                    611: 		if ($now<$start) { $notactive=1; }
                    612:             }
                    613:             if ($end) {
                    614:                 if ($now>$end) { $notactive=1; }
                    615:             } 
                    616:             unless ($notactive) { return $section; }
                    617:         }
1.191     harris41  618:     }
1.70      www       619:     return '-1';
                    620: }
                    621: 
                    622: # ------------------------------------- Read an entry from a user's environment
                    623: 
                    624: sub userenvironment {
                    625:     my ($udom,$unam,@what)=@_;
                    626:     my %returnhash=();
                    627:     my @answer=split(/\&/,
                    628:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    629:                       &homeserver($unam,$udom)));
                    630:     my $i;
                    631:     for ($i=0;$i<=$#what;$i++) {
                    632: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    633:     }
                    634:     return %returnhash;
1.1       albertel  635: }
                    636: 
1.263     www       637: # -------------------------------------------------------------------- New chat
                    638: 
                    639: sub chatsend {
                    640:     my ($newentry,$anon)=@_;
                    641:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    642:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                    643:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                    644:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
                    645: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
                    646: 		   &escape($newentry)),$chome);
1.292     www       647: }
                    648: 
                    649: # ------------------------------------------ Find current version of a resource
                    650: 
                    651: sub getversion {
                    652:     my $fname=&clutter(shift);
                    653:     unless ($fname=~/^\/res\//) { return -1; }
                    654:     return &currentversion(&filelocation('',$fname));
                    655: }
                    656: 
                    657: sub currentversion {
                    658:     my $fname=shift;
                    659:     my $author=$fname;
                    660:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    661:     my ($udom,$uname)=split(/\//,$author);
                    662:     my $home=homeserver($uname,$udom);
                    663:     if ($home eq 'no_host') { 
                    664:         return -1; 
                    665:     }
                    666:     my $answer=reply("currentversion:$fname",$home);
                    667:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    668: 	return -1;
                    669:     }
                    670:     return $answer;
1.263     www       671: }
                    672: 
1.1       albertel  673: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       674: 
1.1       albertel  675: sub subscribe {
                    676:     my $fname=shift;
                    677:     my $author=$fname;
                    678:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    679:     my ($udom,$uname)=split(/\//,$author);
                    680:     my $home=homeserver($uname,$udom);
1.290     www       681:     if ($home eq 'no_host') { 
1.1       albertel  682:         return 'not_found'; 
                    683:     }
                    684:     my $answer=reply("sub:$fname",$home);
1.64      www       685:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    686: 	$answer.=' by '.$home;
                    687:     }
1.1       albertel  688:     return $answer;
                    689: }
                    690:     
1.8       www       691: # -------------------------------------------------------------- Replicate file
                    692: 
                    693: sub repcopy {
                    694:     my $filename=shift;
1.23      www       695:     $filename=~s/\/+/\//g;
1.214     www       696:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8       www       697:     my $transname="$filename.in.transfer";
1.17      www       698:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www       699:     my $remoteurl=subscribe($filename);
1.64      www       700:     if ($remoteurl =~ /^con_lost by/) {
                    701: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       702:            return HTTP_SERVICE_UNAVAILABLE;
                    703:     } elsif ($remoteurl eq 'not_found') {
                    704: 	   &logthis("Subscribe returned not_found: $filename");
                    705: 	   return HTTP_NOT_FOUND;
1.64      www       706:     } elsif ($remoteurl =~ /^rejected by/) {
                    707: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       708:            return FORBIDDEN;
1.20      www       709:     } elsif ($remoteurl eq 'directory') {
                    710:            return OK;
1.8       www       711:     } else {
1.290     www       712:         my $author=$filename;
                    713:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    714:         my ($udom,$uname)=split(/\//,$author);
                    715:         my $home=homeserver($uname,$udom);
                    716:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www       717:            my @parts=split(/\//,$filename);
                    718:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                    719:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                    720:                &logthis("Malconfiguration for replication: $filename");
                    721: 	       return HTTP_BAD_REQUEST;
                    722:            }
                    723:            my $count;
                    724:            for ($count=5;$count<$#parts;$count++) {
                    725:                $path.="/$parts[$count]";
                    726:                if ((-e $path)!=1) {
                    727: 		   mkdir($path,0777);
                    728:                }
                    729:            }
                    730:            my $ua=new LWP::UserAgent;
                    731:            my $request=new HTTP::Request('GET',"$remoteurl");
                    732:            my $response=$ua->request($request,$transname);
                    733:            if ($response->is_error()) {
                    734: 	       unlink($transname);
                    735:                my $message=$response->status_line;
1.12      www       736:                &logthis("<font color=blue>WARNING:"
                    737:                        ." LWP get: $message: $filename</font>");
1.8       www       738:                return HTTP_SERVICE_UNAVAILABLE;
                    739:            } else {
1.16      www       740: 	       if ($remoteurl!~/\.meta$/) {
                    741:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                    742:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                    743:                   if ($mresponse->is_error()) {
                    744: 		      unlink($filename.'.meta');
                    745:                       &logthis(
                    746:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                    747:                   }
                    748: 	       }
1.8       www       749:                rename($transname,$filename);
                    750:                return OK;
                    751:            }
1.290     www       752:        }
1.8       www       753:     }
                    754: }
                    755: 
1.15      www       756: # --------------------------------------------------------- Server Side Include
                    757: 
                    758: sub ssi {
                    759: 
1.23      www       760:     my ($fn,%form)=@_;
1.15      www       761: 
                    762:     my $ua=new LWP::UserAgent;
1.23      www       763:     
                    764:     my $request;
                    765:     
                    766:     if (%form) {
                    767:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel  768:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www       769:     } else {
                    770:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                    771:     }
                    772: 
1.15      www       773:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                    774:     my $response=$ua->request($request);
                    775: 
                    776:     return $response->content;
                    777: }
1.254     www       778: 
                    779: # ------- Add a token to a remote URI's query string to vouch for access rights
                    780: 
                    781: sub tokenwrapper {
                    782:     my $uri=shift;
1.259     www       783:     $uri=~s/^http\:\/\/([^\/]+)//;
                    784:     $uri=~s/^\///;
                    785:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
                    786:     my $token=$1;
                    787:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
                    788: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
                    789:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
                    790:                (($uri=~/\?/)?'&':'?').'token='.$token;
                    791:     } else {
                    792: 	return '/adm/notfound.html';
                    793:     }
1.254     www       794: }
                    795:     
1.257     www       796: # --------------- Take an uploaded file and put it into the userfiles directory
1.259     www       797: # input: name of form element, coursedoc=1 means this is for the course
1.257     www       798: # output: url of file in userspace
                    799: 
                    800: sub userfileupload {
1.259     www       801:     my ($formname,$coursedoc)=@_;
1.257     www       802:     my $fname=$ENV{'form.'.$formname.'.filename'};
                    803:     $fname=~s/\\/\//g;
                    804:     $fname=~s/^.*\/([^\/]+)$/$1/;
                    805:     unless ($fname) { return 'error: no uploaded file'; }
                    806:     chop($ENV{'form.'.$formname});
1.258     www       807: # Create the directory if not present
1.259     www       808:     my $docuname='';
                    809:     my $docudom='';
                    810:     my $docuhome='';
                    811:     if ($coursedoc) {
                    812: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    813: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                    814: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                    815:     } else {
                    816:         $docuname=$ENV{'user.name'};
                    817:         $docudom=$ENV{'user.domain'};
                    818:         $docuhome=$ENV{'user.home'};
                    819:     }
1.271     www       820:     return 
                    821:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
                    822: }
                    823: 
                    824: sub finishuserfileupload {
                    825:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1.259     www       826:     my $path=$docudom.'/'.$docuname.'/';
1.258     www       827:     my $filepath=$perlvar{'lonDocRoot'};
1.259     www       828:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www       829:     my $count;
                    830:     for ($count=4;$count<=$#parts;$count++) {
                    831:         $filepath.="/$parts[$count]";
                    832:         if ((-e $filepath)!=1) {
                    833: 	    mkdir($filepath,0777);
                    834:         }
                    835:     }
                    836: # Save the file
                    837:     {
                    838:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
                    839:        print $fh $ENV{'form.'.$formname};
                    840:     }
1.259     www       841: # Notify homeserver to grep it
                    842: #
1.295     www       843:     
                    844:     my $fetchresult= 
                    845:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
                    846:     if ($fetchresult eq 'ok') {
1.259     www       847: #
1.258     www       848: # Return the URL to it
1.263     www       849:         return '/uploaded/'.$path.$fname;
                    850:     } else {
1.295     www       851:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
                    852:          ' to host '.$docuhome.': '.$fetchresult);
1.263     www       853:         return '/adm/notfound.html';
                    854:     }    
1.257     www       855: }
1.15      www       856: 
1.14      www       857: # ------------------------------------------------------------------------- Log
                    858: 
                    859: sub log {
                    860:     my ($dom,$nam,$hom,$what)=@_;
1.47      www       861:     return critical("log:$dom:$nam:$what",$hom);
1.157     www       862: }
                    863: 
                    864: # ------------------------------------------------------------------ Course Log
                    865: 
                    866: sub flushcourselogs {
                    867:     &logthis('Flushing course log buffers');
1.191     harris41  868:     foreach (keys %courselogs) {
1.157     www       869:         my $crsid=$_;
1.188     www       870:         if (&reply('log:'.$coursedombuf{$crsid}.':'.
                    871: 		          &escape($courselogs{$crsid}),
                    872: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www       873: 	    delete $courselogs{$crsid};
                    874:         } else {
                    875:             &logthis('Failed to flush log buffer for '.$crsid);
                    876:             if (length($courselogs{$crsid})>40000) {
                    877:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                    878:                         " exceeded maximum size, deleting.</font>");
                    879:                delete $courselogs{$crsid};
                    880:             }
                    881:         }        
1.191     harris41  882:     }
1.185     www       883:     &logthis('Flushing access logs');
1.191     harris41  884:     foreach (keys %accesshash) {
1.185     www       885:         my $entry=$_;
                    886:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
                    887:         my %temphash=($entry => $accesshash{$entry});
1.266     albertel  888:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
1.185     www       889: 	    delete $accesshash{$entry};
                    890:         }
1.191     harris41  891:     }
1.186     www       892:     $dumpcount++;
1.157     www       893: }
                    894: 
                    895: sub courselog {
                    896:     my $what=shift;
1.158     www       897:     $what=time.':'.$what;
1.157     www       898:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www       899:     $coursedombuf{$ENV{'request.course.id'}}=
                    900:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
                    901:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    902:     $coursehombuf{$ENV{'request.course.id'}}=
                    903:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.157     www       904:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                    905: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                    906:     } else {
                    907: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                    908:     }
                    909:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                    910: 	&flushcourselogs();
                    911:     }
1.158     www       912: }
                    913: 
                    914: sub courseacclog {
                    915:     my $fnsymb=shift;
                    916:     unless ($ENV{'request.course.id'}) { return ''; }
                    917:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.192     www       918:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
1.187     www       919:         $what.=':POST';
1.191     harris41  920: 	foreach (keys %ENV) {
1.158     www       921:             if ($_=~/^form\.(.*)/) {
                    922: 		$what.=':'.$1.'='.$ENV{$_};
                    923:             }
1.191     harris41  924:         }
1.158     www       925:     }
                    926:     &courselog($what);
1.149     www       927: }
                    928: 
1.185     www       929: sub countacc {
                    930:     my $url=&declutter(shift);
                    931:     unless ($ENV{'request.course.id'}) { return ''; }
                    932:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www       933:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.185     www       934:     if (defined($accesshash{$key})) {
                    935: 	$accesshash{$key}++;
                    936:     } else {
                    937:         $accesshash{$key}=1;
                    938:     }
                    939: }
                    940:     
1.149     www       941: # ----------------------------------------------------------- Check out an item
                    942: 
                    943: sub checkout {
                    944:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                    945:     my $now=time;
                    946:     my $lonhost=$perlvar{'lonHostID'};
                    947:     my $infostr=&escape(
1.234     www       948:                  'CHECKOUTTOKEN&'.
1.149     www       949:                  $tuname.'&'.
                    950:                  $tudom.'&'.
                    951:                  $tcrsid.'&'.
                    952:                  $symb.'&'.
                    953: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                    954:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www       955:     if ($token=~/^error\:/) { 
                    956:         &logthis("<font color=blue>WARNING: ".
                    957:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                    958:                  "</font>");
                    959:         return ''; 
                    960:     }
                    961: 
1.149     www       962:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                    963:     $token=~tr/a-z/A-Z/;
                    964: 
1.153     www       965:     my %infohash=('resource.0.outtoken' => $token,
                    966:                   'resource.0.checkouttime' => $now,
                    967:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www       968: 
                    969:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                    970:        return '';
1.151     www       971:     } else {
                    972:         &logthis("<font color=blue>WARNING: ".
                    973:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                    974:                  "</font>");
1.149     www       975:     }    
                    976: 
                    977:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                    978:                          &escape('Checkout '.$infostr.' - '.
                    979:                                                  $token)) ne 'ok') {
                    980: 	return '';
1.151     www       981:     } else {
                    982:         &logthis("<font color=blue>WARNING: ".
                    983:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                    984:                  "</font>");
1.149     www       985:     }
1.151     www       986:     return $token;
1.149     www       987: }
                    988: 
                    989: # ------------------------------------------------------------ Check in an item
                    990: 
                    991: sub checkin {
                    992:     my $token=shift;
1.150     www       993:     my $now=time;
                    994:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                    995:     $lonhost=~tr/A-Z/a-z/;
                    996:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                    997:     $dtoken=~s/\W/\_/g;
1.234     www       998:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www       999:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1000: 
1.154     www      1001:     unless (($tuname) && ($tudom)) {
                   1002:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1003:         return '';
                   1004:     }
                   1005:     
                   1006:     unless (&allowed('mgr',$tcrsid)) {
                   1007:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   1008:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                   1009:         return '';
                   1010:     }
                   1011: 
1.153     www      1012:     my %infohash=('resource.0.intoken' => $token,
                   1013:                   'resource.0.checkintime' => $now,
                   1014:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1015: 
                   1016:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1017:        return '';
                   1018:     }    
                   1019: 
                   1020:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1021:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1022: 	return '';
                   1023:     }
                   1024: 
                   1025:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1026: }
                   1027: 
                   1028: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1029: 
                   1030: sub expirespread {
                   1031:     my ($uname,$udom,$stype,$usymb)=@_;
                   1032:     my $cid=$ENV{'request.course.id'}; 
                   1033:     if ($cid) {
                   1034:        my $now=time;
                   1035:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   1036:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                   1037:                             $ENV{'course.'.$cid.'.num'}.
                   1038: 	        	    ':nohist_expirationdates:'.
                   1039:                             &escape($key).'='.$now,
                   1040:                             $ENV{'course.'.$cid.'.home'})
                   1041:     }
                   1042:     return 'ok';
1.14      www      1043: }
                   1044: 
1.109     www      1045: # ----------------------------------------------------- Devalidate Spreadsheets
                   1046: 
                   1047: sub devalidate {
                   1048:     my $symb=shift;
                   1049:     my $cid=$ENV{'request.course.id'}; 
                   1050:     if ($cid) {
                   1051: 	my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
                   1052:         my $status=
1.133     albertel 1053: 	    &del('nohist_calculatedsheet',
                   1054: 		 [$key.'studentcalc'],
                   1055: 		 $ENV{'course.'.$cid.'.domain'},
                   1056: 		 $ENV{'course.'.$cid.'.num'})
                   1057: 		.' '.
                   1058: 	    &del('nohist_calculatedsheets_'.$cid,
                   1059: 		 [$key.'assesscalc:'.$symb]);
1.109     www      1060:         unless ($status eq 'ok ok') {
                   1061:            &logthis('Could not devalidate spreadsheet '.
                   1062:                     $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
                   1063: 		    $symb.': '.$status);
1.133     albertel 1064:         }
1.109     www      1065:     }
                   1066: }
                   1067: 
1.265     albertel 1068: sub get_scalar {
                   1069:     my ($string,$end) = @_;
                   1070:     my $value;
                   1071:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1072: 	$value = $1;
                   1073:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1074: 	$value = $1;
                   1075:     }
                   1076:     return &unescape($value);
                   1077: }
                   1078: 
                   1079: sub array2str {
                   1080:   my (@array) = @_;
                   1081:   my $result=&arrayref2str(\@array);
                   1082:   $result=~s/^__ARRAY_REF__//;
                   1083:   $result=~s/__END_ARRAY_REF__$//;
                   1084:   return $result;
                   1085: }
                   1086: 
1.204     albertel 1087: sub arrayref2str {
                   1088:   my ($arrayref) = @_;
1.265     albertel 1089:   my $result='__ARRAY_REF__';
1.204     albertel 1090:   foreach my $elem (@$arrayref) {
1.265     albertel 1091:     if(ref($elem) eq 'ARRAY') {
                   1092:       $result.=&arrayref2str($elem).'&';
                   1093:     } elsif(ref($elem) eq 'HASH') {
                   1094:       $result.=&hashref2str($elem).'&';
                   1095:     } elsif(ref($elem)) {
                   1096:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 1097:     } else {
                   1098:       $result.=&escape($elem).'&';
                   1099:     }
                   1100:   }
                   1101:   $result=~s/\&$//;
1.265     albertel 1102:   $result .= '__END_ARRAY_REF__';
1.204     albertel 1103:   return $result;
                   1104: }
                   1105: 
1.168     albertel 1106: sub hash2str {
1.204     albertel 1107:   my (%hash) = @_;
                   1108:   my $result=&hashref2str(\%hash);
1.265     albertel 1109:   $result=~s/^__HASH_REF__//;
                   1110:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 1111:   return $result;
                   1112: }
                   1113: 
                   1114: sub hashref2str {
                   1115:   my ($hashref)=@_;
1.265     albertel 1116:   my $result='__HASH_REF__';
1.204     albertel 1117:   foreach (keys(%$hashref)) {
                   1118:     if (ref($_) eq 'ARRAY') {
1.265     albertel 1119:       $result.=&arrayref2str($_).'=';
1.204     albertel 1120:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 1121:       $result.=&hashref2str($_).'=';
1.204     albertel 1122:     } elsif (ref($_)) {
1.265     albertel 1123:       $result.='=';
                   1124:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 1125:     } else {
1.265     albertel 1126: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 1127:     }
                   1128: 
1.265     albertel 1129:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   1130:       $result.=&arrayref2str($hashref->{$_}).'&';
                   1131:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   1132:       $result.=&hashref2str($hashref->{$_}).'&';
                   1133:     } elsif(ref($hashref->{$_})) {
                   1134:        $result.='&';
                   1135:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 1136:     } else {
1.265     albertel 1137:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 1138:     }
                   1139:   }
1.168     albertel 1140:   $result=~s/\&$//;
1.265     albertel 1141:   $result .= '__END_HASH_REF__';
1.168     albertel 1142:   return $result;
                   1143: }
                   1144: 
                   1145: sub str2hash {
1.265     albertel 1146:     my ($string)=@_;
                   1147:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   1148:     return %$hash;
                   1149: }
                   1150: 
                   1151: sub str2hashref {
1.168     albertel 1152:   my ($string) = @_;
1.265     albertel 1153: 
                   1154:   my %hash;
                   1155: 
                   1156:   if($string !~ /^__HASH_REF__/) {
                   1157:       if (! ($string eq '' || !defined($string))) {
                   1158: 	  $hash{'error'}='Not hash reference';
                   1159:       }
                   1160:       return (\%hash, $string);
                   1161:   }
                   1162: 
                   1163:   $string =~ s/^__HASH_REF__//;
                   1164: 
                   1165:   while($string !~ /^__END_HASH_REF__/) {
                   1166:       #key
                   1167:       my $key='';
                   1168:       if($string =~ /^__HASH_REF__/) {
                   1169:           ($key, $string)=&str2hashref($string);
                   1170:           if(defined($key->{'error'})) {
                   1171:               $hash{'error'}='Bad data';
                   1172:               return (\%hash, $string);
                   1173:           }
                   1174:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1175:           ($key, $string)=&str2arrayref($string);
                   1176:           if($key->[0] eq 'Array reference error') {
                   1177:               $hash{'error'}='Bad data';
                   1178:               return (\%hash, $string);
                   1179:           }
                   1180:       } else {
                   1181:           $string =~ s/^(.*?)=//;
1.267     albertel 1182: 	  $key=&unescape($1);
1.265     albertel 1183:       }
                   1184:       $string =~ s/^=//;
                   1185: 
                   1186:       #value
                   1187:       my $value='';
                   1188:       if($string =~ /^__HASH_REF__/) {
                   1189:           ($value, $string)=&str2hashref($string);
                   1190:           if(defined($value->{'error'})) {
                   1191:               $hash{'error'}='Bad data';
                   1192:               return (\%hash, $string);
                   1193:           }
                   1194:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1195:           ($value, $string)=&str2arrayref($string);
                   1196:           if($value->[0] eq 'Array reference error') {
                   1197:               $hash{'error'}='Bad data';
                   1198:               return (\%hash, $string);
                   1199:           }
                   1200:       } else {
                   1201: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   1202:       }
                   1203:       $string =~ s/^&//;
                   1204: 
                   1205:       $hash{$key}=$value;
1.204     albertel 1206:   }
1.265     albertel 1207: 
                   1208:   $string =~ s/^__END_HASH_REF__//;
                   1209: 
                   1210:   return (\%hash, $string);
1.204     albertel 1211: }
                   1212: 
                   1213: sub str2array {
1.265     albertel 1214:     my ($string)=@_;
                   1215:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   1216:     return @$array;
                   1217: }
                   1218: 
                   1219: sub str2arrayref {
1.204     albertel 1220:   my ($string) = @_;
1.265     albertel 1221:   my @array;
                   1222: 
                   1223:   if($string !~ /^__ARRAY_REF__/) {
                   1224:       if (! ($string eq '' || !defined($string))) {
                   1225: 	  $array[0]='Array reference error';
                   1226:       }
                   1227:       return (\@array, $string);
                   1228:   }
                   1229: 
                   1230:   $string =~ s/^__ARRAY_REF__//;
                   1231: 
                   1232:   while($string !~ /^__END_ARRAY_REF__/) {
                   1233:       my $value='';
                   1234:       if($string =~ /^__HASH_REF__/) {
                   1235:           ($value, $string)=&str2hashref($string);
                   1236:           if(defined($value->{'error'})) {
                   1237:               $array[0] ='Array reference error';
                   1238:               return (\@array, $string);
                   1239:           }
                   1240:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1241:           ($value, $string)=&str2arrayref($string);
                   1242:           if($value->[0] eq 'Array reference error') {
                   1243:               $array[0] ='Array reference error';
                   1244:               return (\@array, $string);
                   1245:           }
                   1246:       } else {
                   1247: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   1248:       }
                   1249:       $string =~ s/^&//;
                   1250: 
                   1251:       push(@array, $value);
1.191     harris41 1252:   }
1.265     albertel 1253: 
                   1254:   $string =~ s/^__END_ARRAY_REF__//;
                   1255: 
                   1256:   return (\@array, $string);
1.168     albertel 1257: }
                   1258: 
1.167     albertel 1259: # -------------------------------------------------------------------Temp Store
                   1260: 
1.168     albertel 1261: sub tmpreset {
                   1262:   my ($symb,$namespace,$domain,$stuname) = @_;
                   1263:   if (!$symb) {
                   1264:     $symb=&symbread();
                   1265:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
                   1266:   }
                   1267:   $symb=escape($symb);
                   1268: 
                   1269:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1270:   $namespace=~s/\//\_/g;
                   1271:   $namespace=~s/\W//g;
                   1272: 
                   1273:   #FIXME needs to do something for /pub resources
                   1274:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1275:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1276:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1277:   my %hash;
                   1278:   if (tie(%hash,'GDBM_File',
                   1279: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1280: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1281:     foreach my $key (keys %hash) {
1.180     albertel 1282:       if ($key=~ /:$symb/) {
1.168     albertel 1283: 	delete($hash{$key});
                   1284:       }
                   1285:     }
                   1286:   }
                   1287: }
                   1288: 
1.167     albertel 1289: sub tmpstore {
1.168     albertel 1290:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1291: 
                   1292:   if (!$symb) {
                   1293:     $symb=&symbread();
                   1294:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1295:   }
                   1296:   $symb=escape($symb);
                   1297: 
                   1298:   if (!$namespace) {
                   1299:     # I don't think we would ever want to store this for a course.
                   1300:     # it seems this will only be used if we don't have a course.
                   1301:     #$namespace=$ENV{'request.course.id'};
                   1302:     #if (!$namespace) {
                   1303:       $namespace=$ENV{'request.state'};
                   1304:     #}
                   1305:   }
                   1306:   $namespace=~s/\//\_/g;
                   1307:   $namespace=~s/\W//g;
                   1308: #FIXME needs to do something for /pub resources
                   1309:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1310:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1311:   my $now=time;
                   1312:   my %hash;
                   1313:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1314:   if (tie(%hash,'GDBM_File',
                   1315: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1316: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1317:     $hash{"version:$symb"}++;
                   1318:     my $version=$hash{"version:$symb"};
                   1319:     my $allkeys=''; 
                   1320:     foreach my $key (keys(%$storehash)) {
                   1321:       $allkeys.=$key.':';
                   1322:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                   1323:     }
                   1324:     $hash{"$version:$symb:timestamp"}=$now;
                   1325:     $allkeys.='timestamp';
                   1326:     $hash{"$version:keys:$symb"}=$allkeys;
                   1327:     if (untie(%hash)) {
                   1328:       return 'ok';
                   1329:     } else {
                   1330:       return "error:$!";
                   1331:     }
                   1332:   } else {
                   1333:     return "error:$!";
                   1334:   }
                   1335: }
1.167     albertel 1336: 
1.168     albertel 1337: # -----------------------------------------------------------------Temp Restore
1.167     albertel 1338: 
1.168     albertel 1339: sub tmprestore {
                   1340:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 1341: 
1.168     albertel 1342:   if (!$symb) {
                   1343:     $symb=&symbread();
                   1344:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1345:   }
                   1346:   $symb=escape($symb);
                   1347: 
                   1348:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1349:   #FIXME needs to do something for /pub resources
                   1350:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1351:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1352: 
                   1353:   my %returnhash;
                   1354:   $namespace=~s/\//\_/g;
                   1355:   $namespace=~s/\W//g;
                   1356:   my %hash;
                   1357:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1358:   if (tie(%hash,'GDBM_File',
                   1359: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1360: 	  &GDBM_READER(),0640)) {
1.168     albertel 1361:     my $version=$hash{"version:$symb"};
                   1362:     $returnhash{'version'}=$version;
                   1363:     my $scope;
                   1364:     for ($scope=1;$scope<=$version;$scope++) {
                   1365:       my $vkeys=$hash{"$scope:keys:$symb"};
                   1366:       my @keys=split(/:/,$vkeys);
                   1367:       my $key;
                   1368:       $returnhash{"$scope:keys"}=$vkeys;
                   1369:       foreach $key (@keys) {
                   1370: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                   1371: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel 1372:       }
                   1373:     }
1.168     albertel 1374:     if (!(untie(%hash))) {
                   1375:       return "error:$!";
                   1376:     }
                   1377:   } else {
                   1378:     return "error:$!";
                   1379:   }
                   1380:   return %returnhash;
1.167     albertel 1381: }
                   1382: 
1.9       www      1383: # ----------------------------------------------------------------------- Store
                   1384: 
                   1385: sub store {
1.124     www      1386:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1387:     my $home='';
                   1388: 
1.168     albertel 1389:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1390: 
1.213     www      1391:     $symb=&symbclean($symb);
1.122     albertel 1392:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1393: 
                   1394:     &devalidate($symb);
                   1395: 
                   1396:     $symb=escape($symb);
1.187     www      1397:     if (!$namespace) { 
                   1398:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1399:           return ''; 
                   1400:        } 
                   1401:     }
1.122     albertel 1402:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1403:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1404:     if (!$home) { $home=$ENV{'user.home'}; }
1.12      www      1405:     my $namevalue='';
1.191     harris41 1406:     foreach (keys %$storehash) {
1.122     albertel 1407:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1408:     }
1.12      www      1409:     $namevalue=~s/\&$//;
1.187     www      1410:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      1411:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      1412: }
                   1413: 
1.47      www      1414: # -------------------------------------------------------------- Critical Store
                   1415: 
                   1416: sub cstore {
1.124     www      1417:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1418:     my $home='';
                   1419: 
1.168     albertel 1420:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1421: 
1.213     www      1422:     $symb=&symbclean($symb);
1.122     albertel 1423:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1424: 
                   1425:     &devalidate($symb);
                   1426: 
                   1427:     $symb=escape($symb);
1.187     www      1428:     if (!$namespace) { 
                   1429:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1430:           return ''; 
                   1431:        } 
                   1432:     }
1.122     albertel 1433:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1434:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1435:     if (!$home) { $home=$ENV{'user.home'}; }
                   1436: 
1.47      www      1437:     my $namevalue='';
1.191     harris41 1438:     foreach (keys %$storehash) {
1.122     albertel 1439:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1440:     }
1.47      www      1441:     $namevalue=~s/\&$//;
1.187     www      1442:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      1443:     return critical
                   1444:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      1445: }
                   1446: 
1.9       www      1447: # --------------------------------------------------------------------- Restore
                   1448: 
                   1449: sub restore {
1.124     www      1450:     my ($symb,$namespace,$domain,$stuname) = @_;
                   1451:     my $home='';
                   1452: 
1.168     albertel 1453:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1454: 
1.122     albertel 1455:     if (!$symb) {
                   1456:       unless ($symb=escape(&symbread())) { return ''; }
                   1457:     } else {
1.213     www      1458:       $symb=&escape(&symbclean($symb));
1.122     albertel 1459:     }
1.188     www      1460:     if (!$namespace) { 
                   1461:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1462:           return ''; 
                   1463:        } 
                   1464:     }
1.122     albertel 1465:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1466:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1467:     if (!$home) { $home=$ENV{'user.home'}; }
                   1468:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   1469: 
1.12      www      1470:     my %returnhash=();
1.191     harris41 1471:     foreach (split(/\&/,$answer)) {
1.12      www      1472: 	my ($name,$value)=split(/\=/,$_);
                   1473:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 1474:     }
1.75      www      1475:     my $version;
                   1476:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 1477:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      1478:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 1479:        }
1.75      www      1480:     }
1.13      www      1481:     return %returnhash;
1.34      www      1482: }
                   1483: 
                   1484: # ---------------------------------------------------------- Course Description
                   1485: 
                   1486: sub coursedescription {
                   1487:     my $courseid=shift;
                   1488:     $courseid=~s/^\///;
1.49      www      1489:     $courseid=~s/\_/\//g;
1.34      www      1490:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 1491:     my $chome=&homeserver($cnum,$cdomain);
1.34      www      1492:     if ($chome ne 'no_host') {
1.129     albertel 1493:        my %returnhash=&dump('environment',$cdomain,$cnum);
                   1494:        if (!exists($returnhash{'con_lost'})) {
1.96      www      1495:            my $normalid=$cdomain.'_'.$cnum;
1.53      www      1496:            my %envhash=();
1.129     albertel 1497:            $returnhash{'home'}= $chome;
                   1498: 	   $returnhash{'domain'} = $cdomain;
                   1499: 	   $returnhash{'num'} = $cnum;
1.130     albertel 1500:            while (my ($name,$value) = each %returnhash) {
1.53      www      1501:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 1502:            }
1.270     www      1503:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      1504:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      1505: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.54      www      1506:            $envhash{'course.'.$normalid.'.last_cache'}=time;
1.60      www      1507:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   1508:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   1509:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.53      www      1510:            &appenv(%envhash);
1.34      www      1511:            return %returnhash;
                   1512:        }
                   1513:     }
                   1514:     return ();
1.9       www      1515: }
1.1       albertel 1516: 
1.103     harris41 1517: # -------------------------------------------------------- Get user privileges
1.11      www      1518: 
                   1519: sub rolesinit {
                   1520:     my ($domain,$username,$authhost)=@_;
                   1521:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      1522:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      1523:     my %allroles=();
                   1524:     my %thesepriv=();
                   1525:     my $now=time;
1.21      www      1526:     my $userroles="user.login.time=$now\n";
1.11      www      1527:     my $thesestr;
                   1528: 
                   1529:     if ($rolesdump ne '') {
1.191     harris41 1530:         foreach (split(/&/,$rolesdump)) {
1.21      www      1531: 	  if ($_!~/^rolesdef\&/) {
1.11      www      1532:             my ($area,$role)=split(/=/,$_);
1.21      www      1533:             $area=~s/\_\w\w$//;
1.11      www      1534:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      1535:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   1536:                         $tstart.'.'.$tend."\n";
1.11      www      1537:             if ($tend!=0) {
                   1538: 	        if ($tend<$now) {
                   1539: 	            $trole='';
                   1540:                 } 
                   1541:             }
                   1542:             if ($tstart!=0) {
                   1543:                 if ($tstart>$now) {
                   1544:                    $trole='';        
                   1545:                 }
                   1546:             }
                   1547:             if (($area ne '') && ($trole ne '')) {
1.50      www      1548: 	       my $spec=$trole.'.'.$area;
1.12      www      1549:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   1550:                if ($trole =~ /^cr\//) {
                   1551: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   1552:                    my $homsvr=homeserver($rauthor,$rdomain);
                   1553:                    if ($hostname{$homsvr} ne '') {
                   1554:                       my $roledef=
1.21      www      1555: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
1.12      www      1556:                                 $homsvr);
                   1557:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
                   1558:                          my ($syspriv,$dompriv,$coursepriv)=
1.21      www      1559: 			     split(/\_/,unescape($roledef));
1.50      www      1560:  	                 $allroles{'cm./'}.=':'.$syspriv;
                   1561:                          $allroles{$spec.'./'}.=':'.$syspriv;
1.12      www      1562:                          if ($tdomain ne '') {
1.50      www      1563:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   1564:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
1.12      www      1565:                              if ($trest ne '') {
1.50      www      1566: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
                   1567: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
1.12      www      1568:                              }
                   1569: 	                 }
                   1570:                       }
1.11      www      1571:                    }
1.12      www      1572:                } else {
1.50      www      1573: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   1574: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
1.12      www      1575:                    if ($tdomain ne '') {
1.50      www      1576:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   1577:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1.12      www      1578:                       if ($trest ne '') {
1.50      www      1579: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   1580: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
1.12      www      1581:                       }
                   1582: 	           }
1.11      www      1583: 	       }
1.12      www      1584:             }
                   1585:           } 
1.191     harris41 1586:         }
1.125     www      1587:         my $adv=0;
1.128     www      1588:         my $author=0;
1.191     harris41 1589:         foreach (keys %allroles) {
1.11      www      1590:             %thesepriv=();
1.146     www      1591:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      1592:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 1593:             foreach (split(/:/,$allroles{$_})) {
1.11      www      1594:                 if ($_ ne '') {
1.103     harris41 1595: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      1596:                     if ($restrictions eq '') {
1.103     harris41 1597: 			$thesepriv{$privilege}='F';
1.11      www      1598:                     } else {
1.103     harris41 1599:                         if ($thesepriv{$privilege} ne 'F') {
                   1600: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      1601:                         }
                   1602:                     }
                   1603:                 }
1.191     harris41 1604:             }
1.11      www      1605:             $thesestr='';
1.191     harris41 1606:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      1607:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 1608:         }
1.128     www      1609:         $userroles.='user.adv='.$adv."\n".
                   1610: 	            'user.author='.$author."\n";
1.126     www      1611:         $ENV{'user.adv'}=$adv;
1.11      www      1612:     }
                   1613:     return $userroles;  
                   1614: }
                   1615: 
1.12      www      1616: # --------------------------------------------------------------- get interface
                   1617: 
                   1618: sub get {
1.131     albertel 1619:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1620:    my $items='';
1.191     harris41 1621:    foreach (@$storearr) {
1.12      www      1622:        $items.=escape($_).'&';
1.191     harris41 1623:    }
1.12      www      1624:    $items=~s/\&$//;
1.131     albertel 1625:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1626:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1627:    my $uhome=&homeserver($uname,$udomain);
                   1628: 
1.133     albertel 1629:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1630:    my @pairs=split(/\&/,$rep);
1.273     albertel 1631:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1632:      return @pairs;
                   1633:    }
1.15      www      1634:    my %returnhash=();
1.42      www      1635:    my $i=0;
1.191     harris41 1636:    foreach (@$storearr) {
1.42      www      1637:       $returnhash{$_}=unescape($pairs[$i]);
                   1638:       $i++;
1.191     harris41 1639:    }
1.15      www      1640:    return %returnhash;
1.27      www      1641: }
                   1642: 
                   1643: # --------------------------------------------------------------- del interface
                   1644: 
                   1645: sub del {
1.133     albertel 1646:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      1647:    my $items='';
1.191     harris41 1648:    foreach (@$storearr) {
1.27      www      1649:        $items.=escape($_).'&';
1.191     harris41 1650:    }
1.27      www      1651:    $items=~s/\&$//;
1.133     albertel 1652:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1653:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1654:    my $uhome=&homeserver($uname,$udomain);
                   1655: 
                   1656:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1657: }
                   1658: 
                   1659: # -------------------------------------------------------------- dump interface
                   1660: 
                   1661: sub dump {
1.193     www      1662:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 1663:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1664:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1665:    my $uhome=&homeserver($uname,$udomain);
1.193     www      1666:    if ($regexp) {
                   1667:        $regexp=&escape($regexp);
                   1668:    } else {
                   1669:        $regexp='.';
                   1670:    }
                   1671:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      1672:    my @pairs=split(/\&/,$rep);
                   1673:    my %returnhash=();
1.191     harris41 1674:    foreach (@pairs) {
1.12      www      1675:       my ($key,$value)=split(/=/,$_);
1.29      www      1676:       $returnhash{unescape($key)}=unescape($value);
1.191     harris41 1677:    }
1.12      www      1678:    return %returnhash;
                   1679: }
                   1680: 
                   1681: # --------------------------------------------------------------- put interface
                   1682: 
                   1683: sub put {
1.134     albertel 1684:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   1685:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1686:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1687:    my $uhome=&homeserver($uname,$udomain);
1.12      www      1688:    my $items='';
1.191     harris41 1689:    foreach (keys %$storehash) {
1.134     albertel 1690:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 1691:    }
1.12      www      1692:    $items=~s/\&$//;
1.134     albertel 1693:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      1694: }
                   1695: 
                   1696: # ------------------------------------------------------ critical put interface
                   1697: 
                   1698: sub cput {
1.134     albertel 1699:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   1700:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1701:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1702:    my $uhome=&homeserver($uname,$udomain);
1.47      www      1703:    my $items='';
1.191     harris41 1704:    foreach (keys %$storehash) {
1.134     albertel 1705:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1706:    }
1.47      www      1707:    $items=~s/\&$//;
1.134     albertel 1708:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      1709: }
                   1710: 
                   1711: # -------------------------------------------------------------- eget interface
                   1712: 
                   1713: sub eget {
1.133     albertel 1714:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1715:    my $items='';
1.191     harris41 1716:    foreach (@$storearr) {
1.12      www      1717:        $items.=escape($_).'&';
1.191     harris41 1718:    }
1.12      www      1719:    $items=~s/\&$//;
1.133     albertel 1720:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1721:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1722:    my $uhome=&homeserver($uname,$udomain);
                   1723:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      1724:    my @pairs=split(/\&/,$rep);
                   1725:    my %returnhash=();
1.42      www      1726:    my $i=0;
1.191     harris41 1727:    foreach (@$storearr) {
1.42      www      1728:       $returnhash{$_}=unescape($pairs[$i]);
                   1729:       $i++;
1.191     harris41 1730:    }
1.12      www      1731:    return %returnhash;
                   1732: }
                   1733: 
1.103     harris41 1734: # ------------------------------------------------- Check for a user privilege
1.12      www      1735: 
                   1736: sub allowed {
                   1737:     my ($priv,$uri)=@_;
1.152     www      1738: 
                   1739:     my $orguri=$uri;
1.52      www      1740:     $uri=&declutter($uri);
1.29      www      1741: 
1.54      www      1742: # Free bre access to adm and meta resources
1.29      www      1743: 
1.54      www      1744:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      1745: 	return 'F';
1.159     www      1746:     }
                   1747: 
                   1748: # Free bre to public access
                   1749: 
                   1750:     if ($priv eq 'bre') {
1.238     www      1751:         my $copyright=&metadata($uri,'copyright');
                   1752: 	if ($copyright eq 'public') { return 'F'; }
                   1753:         if ($copyright eq 'priv') {
                   1754:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   1755: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
                   1756: 		return '';
                   1757:             }
                   1758:         }
                   1759:         if ($copyright eq 'domain') {
                   1760:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   1761: 	    unless (($ENV{'user.domain'} eq $1) ||
                   1762:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
                   1763: 		return '';
                   1764:             }
1.262     matthew  1765:         }
                   1766:         if ($ENV{'request.role'}=~ /li\.\//) {
                   1767:             # Library role, so allow browsing of resources in this domain.
                   1768:             return 'F';
1.238     www      1769:         }
1.14      www      1770:     }
1.264     matthew  1771:     # Domain coordinator is trying to create a course
                   1772:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
                   1773:         # uri is the requested domain in this case.
                   1774:         # comparison to 'request.role.domain' shows if the user has selected
                   1775:         # a role of dc for the domain in question. 
                   1776:         return 'F' if ($uri eq $ENV{'request.role.domain'});
                   1777:     }
1.29      www      1778: 
1.52      www      1779:     my $thisallowed='';
                   1780:     my $statecond=0;
                   1781:     my $courseprivid='';
                   1782: 
                   1783: # Course
                   1784: 
                   1785:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   1786:        $thisallowed.=$1;
                   1787:     }
1.29      www      1788: 
1.52      www      1789: # Domain
                   1790: 
                   1791:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   1792:        =~/$priv\&([^\:]*)/) {
1.12      www      1793:        $thisallowed.=$1;
                   1794:     }
1.52      www      1795: 
                   1796: # Course: uri itself is a course
1.66      www      1797:     my $courseuri=$uri;
                   1798:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      1799:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      1800: 
1.83      www      1801:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      1802:        =~/$priv\&([^\:]*)/) {
1.12      www      1803:        $thisallowed.=$1;
                   1804:     }
1.29      www      1805: 
1.52      www      1806: # Full access at system, domain or course-wide level? Exit.
1.29      www      1807: 
                   1808:     if ($thisallowed=~/F/) {
                   1809: 	return 'F';
                   1810:     }
                   1811: 
1.52      www      1812: # If this is generating or modifying users, exit with special codes
1.29      www      1813: 
1.166     www      1814:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      1815: 	return $thisallowed;
                   1816:     }
                   1817: #
1.103     harris41 1818: # Gathered so far: system, domain and course wide privileges
1.52      www      1819: #
                   1820: # Course: See if uri or referer is an individual resource that is part of 
                   1821: # the course
                   1822: 
                   1823:     if ($ENV{'request.course.id'}) {
1.232     www      1824: 
1.52      www      1825:        $courseprivid=$ENV{'request.course.id'};
                   1826:        if ($ENV{'request.course.sec'}) {
                   1827:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   1828:        }
                   1829:        $courseprivid=~s/\_/\//;
                   1830:        my $checkreferer=1;
1.232     www      1831:        my ($match,$cond)=&is_on_map($uri);
                   1832:        if ($match) {
                   1833:            $statecond=$cond;
1.52      www      1834:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1835:                =~/$priv\&([^\:]*)/) {
                   1836:                $thisallowed.=$1;
                   1837:                $checkreferer=0;
                   1838:            }
1.29      www      1839:        }
1.83      www      1840:        
1.148     www      1841:        if ($checkreferer) {
1.152     www      1842: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      1843:             unless ($refuri) {
1.191     harris41 1844:                 foreach (keys %ENV) {
1.148     www      1845: 		    if ($_=~/^httpref\..*\*/) {
                   1846: 			my $pattern=$_;
1.156     www      1847:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      1848:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   1849:                         $pattern=~s/\//\\\//g;
1.152     www      1850:                         if ($orguri=~/$pattern/) {
1.148     www      1851: 			    $refuri=$ENV{$_};
                   1852:                         }
                   1853:                     }
1.191     harris41 1854:                 }
1.148     www      1855:             }
1.232     www      1856: 
1.148     www      1857:          if ($refuri) { 
1.152     www      1858: 	  $refuri=&declutter($refuri);
1.232     www      1859:           my ($match,$cond)=&is_on_map($refuri);
                   1860:             if ($match) {
                   1861:               my $refstatecond=$cond;
1.52      www      1862:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1863:                   =~/$priv\&([^\:]*)/) {
                   1864:                   $thisallowed.=$1;
1.53      www      1865:                   $uri=$refuri;
                   1866:                   $statecond=$refstatecond;
1.52      www      1867:               }
                   1868:           }
1.148     www      1869:         }
1.29      www      1870:        }
1.52      www      1871:    }
1.29      www      1872: 
1.52      www      1873: #
1.103     harris41 1874: # Gathered now: all privileges that could apply, and condition number
1.52      www      1875: # 
                   1876: #
                   1877: # Full or no access?
                   1878: #
1.29      www      1879: 
1.52      www      1880:     if ($thisallowed=~/F/) {
                   1881: 	return 'F';
                   1882:     }
1.29      www      1883: 
1.52      www      1884:     unless ($thisallowed) {
                   1885:         return '';
                   1886:     }
1.29      www      1887: 
1.52      www      1888: # Restrictions exist, deal with them
                   1889: #
                   1890: #   C:according to course preferences
                   1891: #   R:according to resource settings
                   1892: #   L:unless locked
                   1893: #   X:according to user session state
                   1894: #
                   1895: 
                   1896: # Possibly locked functionality, check all courses
1.54      www      1897: # Locks might take effect only after 10 minutes cache expiration for other
                   1898: # courses, and 2 minutes for current course
1.52      www      1899: 
                   1900:     my $envkey;
                   1901:     if ($thisallowed=~/L/) {
                   1902:         foreach $envkey (keys %ENV) {
1.54      www      1903:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   1904:                my $courseid=$2;
                   1905:                my $roleid=$1.'.'.$2;
1.92      www      1906:                $courseid=~s/^\///;
1.54      www      1907:                my $expiretime=600;
                   1908:                if ($ENV{'request.role'} eq $roleid) {
                   1909: 		  $expiretime=120;
                   1910:                }
                   1911: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   1912:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   1913:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   1914: 		   &coursedescription($courseid);
                   1915:                }
                   1916:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   1917:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   1918: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      1919:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      1920:                             $ENV{'user.home'},
1.57      www      1921:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      1922:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1923:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1924: 		       return '';
                   1925:                    }
                   1926:                }
1.54      www      1927:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   1928:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   1929: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      1930:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      1931:                             $ENV{'user.home'},
1.57      www      1932:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      1933:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1934:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1935: 		       return '';
                   1936:                    }
                   1937:                }
                   1938: 	   }
1.29      www      1939:        }
1.52      www      1940:     }
                   1941:    
                   1942: #
                   1943: # Rest of the restrictions depend on selected course
                   1944: #
                   1945: 
                   1946:     unless ($ENV{'request.course.id'}) {
                   1947:        return '1';
                   1948:     }
1.29      www      1949: 
1.52      www      1950: #
                   1951: # Now user is definitely in a course
                   1952: #
1.53      www      1953: 
                   1954: 
                   1955: # Course preferences
                   1956: 
                   1957:    if ($thisallowed=~/C/) {
1.54      www      1958:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237     www      1959:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54      www      1960:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      1961: 	   =~/$rolecode/) {
1.57      www      1962:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1963:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237     www      1964:                 $ENV{'request.course.id'});
                   1965:            return '';
                   1966:        }
                   1967: 
                   1968:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
                   1969: 	   =~/$unamedom/) {
                   1970:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1971:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54      www      1972:                 $ENV{'request.course.id'});
                   1973:            return '';
                   1974:        }
1.53      www      1975:    }
                   1976: 
                   1977: # Resource preferences
                   1978: 
                   1979:    if ($thisallowed=~/R/) {
1.54      www      1980:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
                   1981:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
                   1982:        if (-e $filename) {
                   1983:            my @content;
                   1984:            {
                   1985: 	     my $fh=Apache::File->new($filename);
                   1986:              @content=<$fh>;
                   1987: 	   }
                   1988:            if (join('',@content)=~
                   1989:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
1.57      www      1990: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1991:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.54      www      1992:            return '';
                   1993: 
                   1994:            }
                   1995:        }
1.53      www      1996:    }
1.30      www      1997: 
1.246     www      1998: # Restricted by state or randomout?
1.30      www      1999: 
1.52      www      2000:    if ($thisallowed=~/X/) {
1.247     www      2001:       if ($ENV{'acc.randomout'}) {
1.249     www      2002:          my $symb=&symbread($uri,1);
1.248     www      2003:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
                   2004:             return ''; 
                   2005:          }
1.247     www      2006:       }
                   2007:       if (&condval($statecond)) {
1.52      www      2008: 	 return '2';
                   2009:       } else {
                   2010:          return '';
                   2011:       }
                   2012:    }
1.30      www      2013: 
1.52      www      2014:    return 'F';
1.232     www      2015: }
                   2016: 
                   2017: # --------------------------------------------------- Is a resource on the map?
                   2018: 
                   2019: sub is_on_map {
                   2020:     my $uri=&declutter(shift);
                   2021:     my @uriparts=split(/\//,$uri);
                   2022:     my $filename=$uriparts[$#uriparts];
                   2023:     my $pathname=$uri;
1.289     bowersj2 2024:     $pathname=~s|/\Q$filename\E$||;
                   2025:     #Trying to find the conditional for the file
1.232     www      2026:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 2027: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      2028:     if ($match) {
1.289     bowersj2 2029: 	return (1,$1);
                   2030:     } else {
                   2031: 	return (0,0);
                   2032:     }
1.12      www      2033: }
                   2034: 
                   2035: # ----------------------------------------------------------------- Define Role
                   2036: 
                   2037: sub definerole {
                   2038:   if (allowed('mcr','/')) {
                   2039:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.191     harris41 2040:     foreach (split('/',$sysrole)) {
1.21      www      2041: 	my ($crole,$cqual)=split(/\&/,$_);
                   2042:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   2043:         if ($pr{'cr:s'}=~/$crole\&/) {
                   2044: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   2045:                return "refused:s:$crole&$cqual"; 
                   2046:             }
                   2047:         }
1.191     harris41 2048:     }
                   2049:     foreach (split('/',$domrole)) {
1.21      www      2050: 	my ($crole,$cqual)=split(/\&/,$_);
                   2051:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   2052:         if ($pr{'cr:d'}=~/$crole\&/) {
                   2053: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   2054:                return "refused:d:$crole&$cqual"; 
                   2055:             }
                   2056:         }
1.191     harris41 2057:     }
                   2058:     foreach (split('/',$courole)) {
1.21      www      2059: 	my ($crole,$cqual)=split(/\&/,$_);
                   2060:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   2061:         if ($pr{'cr:c'}=~/$crole\&/) {
                   2062: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   2063:                return "refused:c:$crole&$cqual"; 
                   2064:             }
                   2065:         }
1.191     harris41 2066:     }
1.12      www      2067:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2068:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      2069: 	        "rolesdef_$rolename=".
                   2070:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      2071:     return reply($command,$ENV{'user.home'});
                   2072:   } else {
                   2073:     return 'refused';
                   2074:   }
1.105     harris41 2075: }
                   2076: 
                   2077: # ---------------- Make a metadata query against the network of library servers
                   2078: 
                   2079: sub metadata_query {
1.244     matthew  2080:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 2081:     my %rhash;
1.244     matthew  2082:     my @server_list = (defined($server_array) ? @$server_array
                   2083:                                               : keys(%libserv) );
                   2084:     for my $server (@server_list) {
1.118     harris41 2085: 	unless ($custom or $customshow) {
                   2086: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   2087: 	    $rhash{$server}=$reply;
                   2088: 	}
                   2089: 	else {
                   2090: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   2091: 			     &escape($custom).':'.&escape($customshow),
                   2092: 			     $server);
                   2093: 	    $rhash{$server}=$reply;
                   2094: 	}
1.112     harris41 2095:     }
1.118     harris41 2096:     return \%rhash;
1.240     www      2097: }
                   2098: 
                   2099: # ----------------------------------------- Send log queries and wait for reply
                   2100: 
                   2101: sub log_query {
                   2102:     my ($uname,$udom,$query,%filters)=@_;
                   2103:     my $uhome=&homeserver($uname,$udom);
                   2104:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   2105:     my $uhost=$hostname{$uhome};
1.241     www      2106:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      2107:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   2108:                        $uhome);
                   2109:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242     www      2110:     return get_query_reply($queryid);
                   2111: }
                   2112: 
                   2113: sub get_query_reply {
                   2114:     my $queryid=shift;
1.240     www      2115:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   2116:     my $reply='';
                   2117:     for (1..100) {
                   2118: 	sleep 2;
                   2119:         if (-e $replyfile.'.end') {
                   2120: 	    if (my $fh=Apache::File->new($replyfile)) {
                   2121:                $reply.=<$fh>;
                   2122:                $fh->close;
                   2123: 	   } else { return 'error: reply_file_error'; }
1.242     www      2124:            return &unescape($reply);
                   2125: 	}
1.240     www      2126:     }
1.242     www      2127:     return 'timeout:'.$queryid;
1.240     www      2128: }
                   2129: 
                   2130: sub courselog_query {
1.241     www      2131: #
                   2132: # possible filters:
                   2133: # url: url or symb
                   2134: # username
                   2135: # domain
                   2136: # action: view, submit, grade
                   2137: # start: timestamp
                   2138: # end: timestamp
                   2139: #
1.240     www      2140:     my (%filters)=@_;
                   2141:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241     www      2142:     if ($filters{'url'}) {
                   2143: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   2144:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   2145:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   2146:     }
1.240     www      2147:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   2148:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   2149:     return &log_query($cname,$cdom,'courselog',%filters);
                   2150: }
                   2151: 
                   2152: sub userlog_query {
                   2153:     my ($uname,$udom,%filters)=@_;
                   2154:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      2155: }
                   2156: 
                   2157: # ------------------------------------------------------------------ Plain Text
                   2158: 
                   2159: sub plaintext {
1.22      www      2160:     my $short=shift;
                   2161:     return $prp{$short};
1.12      www      2162: }
                   2163: 
                   2164: # ----------------------------------------------------------------- Assign Role
                   2165: 
                   2166: sub assignrole {
1.21      www      2167:     my ($udom,$uname,$url,$role,$end,$start)=@_;
                   2168:     my $mrole;
                   2169:     if ($role =~ /^cr\//) {
1.104     www      2170: 	unless (&allowed('ccr',$url)) {
                   2171:            &logthis('Refused custom assignrole: '.
                   2172:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2173: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2174:            return 'refused'; 
                   2175:         }
1.21      www      2176:         $mrole='cr';
                   2177:     } else {
1.82      www      2178:         my $cwosec=$url;
1.83      www      2179:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.104     www      2180:         unless (&allowed('c'.$role,$cwosec)) { 
                   2181:            &logthis('Refused assignrole: '.
                   2182:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2183: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2184:            return 'refused'; 
                   2185:         }
1.21      www      2186:         $mrole=$role;
                   2187:     }
                   2188:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2189:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      2190:     if ($end) { $command.='_'.$end; }
1.21      www      2191:     if ($start) {
                   2192: 	if ($end) { 
1.81      www      2193:            $command.='_'.$start; 
1.21      www      2194:         } else {
1.81      www      2195:            $command.='_0_'.$start;
1.21      www      2196:         }
                   2197:     }
                   2198:     return &reply($command,&homeserver($uname,$udom));
1.169     harris41 2199: }
                   2200: 
                   2201: # -------------------------------------------------- Modify user authentication
1.197     www      2202: # Overrides without validation
                   2203: 
1.169     harris41 2204: sub modifyuserauth {
                   2205:     my ($udom,$uname,$umode,$upass)=@_;
                   2206:     my $uhome=&homeserver($uname,$udom);
1.197     www      2207:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   2208:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272     matthew  2209:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2210:              ' in domain '.$ENV{'request.role.domain'});  
1.169     harris41 2211:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   2212: 		     &escape($upass),$uhome);
1.197     www      2213:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   2214:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   2215:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   2216:     &log($udom,,$uname,$uhome,
                   2217:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   2218:                                      $ENV{'user.name'}.', '.$umode.
                   2219:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 2220:     unless ($reply eq 'ok') {
1.197     www      2221:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 2222: 	return 'error: '.$reply;
                   2223:     }   
1.170     harris41 2224:     return 'ok';
1.80      www      2225: }
                   2226: 
1.81      www      2227: # --------------------------------------------------------------- Modify a user
1.80      www      2228: 
1.81      www      2229: sub modifyuser {
1.206     matthew  2230:     my ($udom,    $uname, $uid,
                   2231:         $umode,   $upass, $first,
                   2232:         $middle,  $last,  $gene,
                   2233:         $forceid, $desiredhome)=@_;
1.198     www      2234:     $udom=~s/\W//g;
                   2235:     $uname=~s/\W//g;
1.81      www      2236:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2237:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  2238: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   2239:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   2240:                                      ' desiredhome not specified'). 
1.272     matthew  2241:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2242:              ' in domain '.$ENV{'request.role.domain'});
1.230     stredwic 2243:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      2244: # ----------------------------------------------------------------- Create User
1.81      www      2245:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
1.80      www      2246:         my $unhome='';
1.209     matthew  2247:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   2248:             $unhome = $desiredhome;
                   2249: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80      www      2250: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209     matthew  2251:         } else { # load balancing routine for determining $unhome
1.80      www      2252:             my $tryserver;
1.81      www      2253:             my $loadm=10000000;
1.80      www      2254:             foreach $tryserver (keys %libserv) {
                   2255: 	       if ($hostdom{$tryserver} eq $udom) {
                   2256:                   my $answer=reply('load',$tryserver);
                   2257:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   2258: 		      $loadm=$answer;
                   2259:                       $unhome=$tryserver;
                   2260:                   }
                   2261: 	       }
                   2262: 	    }
                   2263:         }
                   2264:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  2265: 	    return 'error: unable to find a home server for '.$uname.
                   2266:                    ' in domain '.$udom;
1.80      www      2267:         }
                   2268:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   2269:                          &escape($upass),$unhome);
                   2270: 	unless ($reply eq 'ok') {
                   2271:             return 'error: '.$reply;
                   2272:         }   
1.230     stredwic 2273:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      2274:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
                   2275: 	    return 'error: verify home';
                   2276:         }
1.209     matthew  2277:     }   # End of creation of new user
1.80      www      2278: # ---------------------------------------------------------------------- Add ID
                   2279:     if ($uid) {
                   2280:        $uid=~tr/A-Z/a-z/;
                   2281:        my %uidhash=&idrget($udom,$uname);
1.196     www      2282:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   2283:          && (!$forceid)) {
1.80      www      2284: 	  unless ($uid eq $uidhash{$uname}) {
                   2285: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
                   2286:           }
                   2287:        } else {
                   2288: 	  &idput($udom,($uname => $uid));
                   2289:        }
                   2290:     }
                   2291: # -------------------------------------------------------------- Add names, etc
1.134     albertel 2292:     my %names=&get('environment',
                   2293: 		   ['firstname','middlename','lastname','generation'],
                   2294: 		   $udom,$uname);
1.207     albertel 2295:     if ($names{'firstname'} =~ m/^error:.*/) { %names=(); }
1.134     albertel 2296:     if ($first)  { $names{'firstname'}  = $first; }
                   2297:     if ($middle) { $names{'middlename'} = $middle; }
                   2298:     if ($last)   { $names{'lastname'}   = $last; }
                   2299:     if ($gene)   { $names{'generation'} = $gene; }
                   2300:     my $reply = &put('environment', \%names, $udom,$uname);
                   2301:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      2302:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2303:              $umode.', '.$first.', '.$middle.', '.
                   2304: 	     $last.', '.$gene.' by '.
                   2305:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 2306:     return 'ok';
1.80      www      2307: }
                   2308: 
1.81      www      2309: # -------------------------------------------------------------- Modify student
1.80      www      2310: 
1.81      www      2311: sub modifystudent {
                   2312:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.209     matthew  2313:         $end,$start,$forceid,$desiredhome)=@_;
1.81      www      2314:     my $cid='';
                   2315:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      2316: 	return 'not_in_class';
                   2317:     }
                   2318: # --------------------------------------------------------------- Make the user
1.81      www      2319:     my $reply=&modifyuser
1.209     matthew  2320: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
                   2321:          $desiredhome);
1.80      www      2322:     unless ($reply eq 'ok') { return $reply; }
1.297   ! matthew  2323:     # This will cause &modify_student_enrollment to get the uid from the
        !          2324:     # students environment
        !          2325:     $uid = undef if (!$forceid);
        !          2326:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
        !          2327:                                         $last,$gene,$usec,$end,$start);
        !          2328:     return $reply;
        !          2329: }
        !          2330: 
        !          2331: sub modify_student_enrollment {
        !          2332:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
        !          2333:     # Get the course id from the environment
        !          2334:     my $cid='';
        !          2335:     unless ($cid=$ENV{'request.course.id'}) {
        !          2336: 	return 'not_in_class';
        !          2337:     }
        !          2338:     # Make sure the user exists
1.81      www      2339:     my $uhome=&homeserver($uname,$udom);
                   2340:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2341: 	return 'error: no such user';
                   2342:     }
1.297   ! matthew  2343:     #
        !          2344:     # Get student data if we were not given enough information
        !          2345:     if (!defined($first)  || $first  eq '' || 
        !          2346:         !defined($last)   || $last   eq '' || 
        !          2347:         !defined($uid)    || $uid    eq '' || 
        !          2348:         !defined($middle) || $middle eq '' || 
        !          2349:         !defined($gene)   || $gene   eq '') {
1.294     matthew  2350:         # They did not supply us with enough data to enroll the student, so
                   2351:         # we need to pick up more information.
1.297   ! matthew  2352:         my %tmp = &get('environment',
1.294     matthew  2353:                        ['firstname','middlename','lastname', 'generation','id']
1.297   ! matthew  2354:                        ,$udom,$uname);
        !          2355: 
        !          2356:         foreach (keys(%tmp)) {
        !          2357:             &logthis("key $_ = ".$tmp{$_});
        !          2358:         }
1.294     matthew  2359:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   2360:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   2361:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297   ! matthew  2362:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  2363:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   2364:     }
                   2365:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
                   2366:                                                            $first,$middle);
1.297   ! matthew  2367:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      2368: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   2369:                       &escape($uname.':'.$udom).'='.
1.294     matthew  2370:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
1.81      www      2371: 	              $ENV{'course.'.$cid.'.home'});
                   2372:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   2373: 	return 'error: '.$reply;
                   2374:     }
1.297   ! matthew  2375:     # Add student role to user
1.83      www      2376:     my $uurl='/'.$cid;
1.81      www      2377:     $uurl=~s/\_/\//g;
                   2378:     if ($usec) {
                   2379: 	$uurl.='/'.$usec;
                   2380:     }
                   2381:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      2382: }
                   2383: 
1.84      www      2384: # ------------------------------------------------- Write to course preferences
                   2385: 
                   2386: sub writecoursepref {
                   2387:     my ($courseid,%prefs)=@_;
                   2388:     $courseid=~s/^\///;
                   2389:     $courseid=~s/\_/\//g;
                   2390:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   2391:     my $chome=homeserver($cnum,$cdomain);
                   2392:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   2393: 	return 'error: no such course';
                   2394:     }
                   2395:     my $cstring='';
1.191     harris41 2396:     foreach (keys %prefs) {
1.84      www      2397: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 2398:     }
1.84      www      2399:     $cstring=~s/\&$//;
                   2400:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   2401: }
                   2402: 
                   2403: # ---------------------------------------------------------- Make/modify course
                   2404: 
                   2405: sub createcourse {
1.271     www      2406:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84      www      2407:     $url=&declutter($url);
                   2408:     my $cid='';
1.264     matthew  2409:     unless (&allowed('ccc',$udom)) {
1.84      www      2410:         return 'refused';
                   2411:     }
                   2412: # ------------------------------------------------------------------- Create ID
                   2413:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2414:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   2415: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 2416:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      2417:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2418:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2419:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 2420:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      2421:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2422:            return 'error: unable to generate unique course-ID';
                   2423:        } 
                   2424:    }
1.264     matthew  2425: # ------------------------------------------------ Check supplied server name
                   2426:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
                   2427:     if (! exists($libserv{$course_server})) {
                   2428:         return 'error:bad server name '.$course_server;
                   2429:     }
1.84      www      2430: # ------------------------------------------------------------- Make the course
                   2431:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  2432:                       $course_server);
1.84      www      2433:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 2434:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      2435:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2436: 	return 'error: no such course';
                   2437:     }
1.271     www      2438: # ----------------------------------------------------------------- Course made
                   2439:     my $topurl=$url;
                   2440:     unless ($nonstandard) {
                   2441: # ------------------------------------------ For standard courses, make top url
                   2442:         my $mapurl=&clutter($url);
1.278     www      2443:         if ($mapurl eq '/res/') { $mapurl=''; }
1.271     www      2444:         $ENV{'form.initmap'}=(<<ENDINITMAP);
                   2445: <map>
                   2446: <resource id="1" type="start"></resource>
                   2447: <resource id="2" src="$mapurl"></resource>
                   2448: <resource id="3" type="finish"></resource>
                   2449: <link index="1" from="1" to="2"></link>
                   2450: <link index="2" from="2" to="3"></link>
                   2451: </map>
                   2452: ENDINITMAP
                   2453:         $topurl=&declutter(
                   2454:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   2455:                           );
                   2456:     }
                   2457: # ----------------------------------------------------------- Write preferences
1.84      www      2458:     &writecoursepref($udom.'_'.$uname,
                   2459:                      ('description' => $description,
1.271     www      2460:                       'url'         => $topurl));
1.84      www      2461:     return '/'.$udom.'/'.$uname;
                   2462: }
                   2463: 
1.21      www      2464: # ---------------------------------------------------------- Assign Custom Role
                   2465: 
                   2466: sub assigncustomrole {
                   2467:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
                   2468:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
                   2469:                        $end,$start);
                   2470: }
                   2471: 
                   2472: # ----------------------------------------------------------------- Revoke Role
                   2473: 
                   2474: sub revokerole {
                   2475:     my ($udom,$uname,$url,$role)=@_;
                   2476:     my $now=time;
                   2477:     return &assignrole($udom,$uname,$url,$role,$now);
                   2478: }
                   2479: 
                   2480: # ---------------------------------------------------------- Revoke Custom Role
                   2481: 
                   2482: sub revokecustomrole {
                   2483:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
                   2484:     my $now=time;
                   2485:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
1.17      www      2486: }
                   2487: 
                   2488: # ------------------------------------------------------------ Directory lister
                   2489: 
                   2490: sub dirlist {
1.253     stredwic 2491:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   2492: 
1.18      www      2493:     $uri=~s/^\///;
                   2494:     $uri=~s/\/$//;
1.253     stredwic 2495:     my ($udom, $uname);
                   2496:     (undef,$udom,$uname)=split(/\//,$uri);
                   2497:     if(defined($userdomain)) {
                   2498:         $udom = $userdomain;
                   2499:     }
                   2500:     if(defined($username)) {
                   2501:         $uname = $username;
                   2502:     }
                   2503: 
                   2504:     my $dirRoot = $perlvar{'lonDocRoot'};
                   2505:     if(defined($alternateDirectoryRoot)) {
                   2506:         $dirRoot = $alternateDirectoryRoot;
                   2507:         $dirRoot =~ s/\/$//;
                   2508:     }
                   2509: 
                   2510:     if($udom) {
                   2511:         if($uname) {
                   2512:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   2513:                               homeserver($uname,$udom));
                   2514:             return split(/:/,$listing);
                   2515:         } elsif(!defined($alternateDirectoryRoot)) {
                   2516:             my $tryserver;
                   2517:             my %allusers=();
                   2518:             foreach $tryserver (keys %libserv) {
                   2519:                 if($hostdom{$tryserver} eq $udom) {
                   2520:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   2521:                                       $udom, $tryserver);
                   2522:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   2523:                         && ($listing ne 'con_lost')) {
                   2524:                         foreach (split(/:/,$listing)) {
                   2525:                             my ($entry,@stat)=split(/&/,$_);
                   2526:                             $allusers{$entry}=1;
                   2527:                         }
                   2528:                     }
1.191     harris41 2529:                 }
1.253     stredwic 2530:             }
                   2531:             my $alluserstr='';
                   2532:             foreach (sort keys %allusers) {
                   2533:                 $alluserstr.=$_.'&user:';
                   2534:             }
                   2535:             $alluserstr=~s/:$//;
                   2536:             return split(/:/,$alluserstr);
                   2537:         } else {
                   2538:             my @emptyResults = ();
                   2539:             push(@emptyResults, 'missing user name');
                   2540:             return split(':',@emptyResults);
                   2541:         }
                   2542:     } elsif(!defined($alternateDirectoryRoot)) {
                   2543:         my $tryserver;
                   2544:         my %alldom=();
                   2545:         foreach $tryserver (keys %libserv) {
                   2546:             $alldom{$hostdom{$tryserver}}=1;
                   2547:         }
                   2548:         my $alldomstr='';
                   2549:         foreach (sort keys %alldom) {
                   2550:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
                   2551:         }
                   2552:         $alldomstr=~s/:$//;
                   2553:         return split(/:/,$alldomstr);       
                   2554:     } else {
                   2555:         my @emptyResults = ();
                   2556:         push(@emptyResults, 'missing domain');
                   2557:         return split(':',@emptyResults);
1.275     stredwic 2558:     }
                   2559: }
                   2560: 
                   2561: # --------------------------------------------- GetFileTimestamp
                   2562: # This function utilizes dirlist and returns the date stamp for
                   2563: # when it was last modified.  It will also return an error of -1
                   2564: # if an error occurs
                   2565: 
                   2566: sub GetFileTimestamp {
                   2567:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   2568:     $studentDomain=~s/\W//g;
                   2569:     $studentName=~s/\W//g;
                   2570:     my $subdir=$studentName.'__';
                   2571:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   2572:     my $proname="$studentDomain/$subdir/$studentName";
                   2573:     $proname .= '/'.$filename;
                   2574:     my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
                   2575:                                        $root);
                   2576:     my $fileStat = $dir[0];
                   2577:     my @stats = split('&', $fileStat);
                   2578:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   2579:         return $stats[9];
                   2580:     } else {
                   2581:         return -1;
1.253     stredwic 2582:     }
1.26      www      2583: }
                   2584: 
                   2585: # -------------------------------------------------------- Value of a Condition
                   2586: 
1.40      www      2587: sub directcondval {
                   2588:     my $number=shift;
                   2589:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   2590:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   2591:     } else {
                   2592:        return 2;
                   2593:     }
                   2594: }
                   2595: 
1.26      www      2596: sub condval {
                   2597:     my $condidx=shift;
                   2598:     my $result=0;
1.54      www      2599:     my $allpathcond='';
1.191     harris41 2600:     foreach (split(/\|/,$condidx)) {
1.54      www      2601:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   2602: 	   $allpathcond.=
                   2603:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   2604:        }
1.191     harris41 2605:     }
1.54      www      2606:     $allpathcond=~s/\|$//;
1.33      www      2607:     if ($ENV{'request.course.id'}) {
1.54      www      2608:        if ($allpathcond) {
1.26      www      2609:           my $operand='|';
                   2610: 	  my @stack;
1.191     harris41 2611:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      2612:               if ($_ eq '(') {
                   2613:                  push @stack,($operand,$result)
                   2614:               } elsif ($_ eq ')') {
                   2615:                   my $before=pop @stack;
                   2616: 		  if (pop @stack eq '&') {
                   2617: 		      $result=$result>$before?$before:$result;
                   2618:                   } else {
                   2619:                       $result=$result>$before?$result:$before;
                   2620:                   }
                   2621:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   2622:                   $operand=$_;
                   2623:               } else {
1.40      www      2624:                   my $new=directcondval($_);
1.26      www      2625:                   if ($operand eq '&') {
                   2626:                      $result=$result>$new?$new:$result;
                   2627:                   } else {
                   2628:                      $result=$result>$new?$result:$new;
1.191     harris41 2629:                   }
1.26      www      2630:               }
1.191     harris41 2631:           }
1.26      www      2632:        }
                   2633:     }
                   2634:     return $result;
1.279     www      2635: }
                   2636: 
                   2637: # ---------------------------------------------------- Devalidate courseresdata
                   2638: 
                   2639: sub devalidatecourseresdata {
                   2640:     my ($coursenum,$coursedomain)=@_;
                   2641:     my $hashid=$coursenum.':'.$coursedomain;
                   2642:     delete $courseresdatacache{$hashid.'.time'};
1.28      www      2643: }
                   2644: 
1.200     www      2645: # --------------------------------------------------- Course Resourcedata Query
                   2646: 
                   2647: sub courseresdata {
                   2648:     my ($coursenum,$coursedomain,@which)=@_;
                   2649:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   2650:     my $hashid=$coursenum.':'.$coursedomain;
1.250     albertel 2651:     my $dodump=0;
                   2652:     if (!defined($courseresdatacache{$hashid.'.time'})) {
                   2653: 	$dodump=1;
                   2654:     } else {
                   2655: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
                   2656:     }
                   2657:     if ($dodump) {
1.251     albertel 2658: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
                   2659: 	my ($tmp) = keys(%dumpreply);
                   2660: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   2661: 	    $courseresdatacache{$hashid.'.time'}=time;
                   2662: 	    $courseresdatacache{$hashid}=\%dumpreply;
1.250     albertel 2663: 	}
                   2664:     }
1.251     albertel 2665:     foreach my $item (@which) {
1.287     albertel 2666: 	if (defined($courseresdatacache{$hashid}->{$item})) {
1.251     albertel 2667: 	    return $courseresdatacache{$hashid}->{$item};
                   2668: 	}
1.250     albertel 2669:     }
1.291     albertel 2670:     return undef;
1.200     www      2671: }
                   2672: 
1.28      www      2673: # --------------------------------------------------------- Value of a Variable
                   2674: 
1.58      www      2675: sub EXT {
1.282     albertel 2676:     my ($varname,$symbparm,$udom,$uname,)=@_;
1.218     albertel 2677: 
1.68      www      2678:     unless ($varname) { return ''; }
1.218     albertel 2679: 
                   2680:     #get real user name/domain, courseid and symb
                   2681:     my $courseid;
                   2682:     if (!($uname && $udom)) {
                   2683:       (my $cursymb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2684:       if (!$symbparm) {	$symbparm=$cursymb; }
                   2685:     } else {
                   2686: 	$courseid=$ENV{'request.course.id'};
                   2687:     }
                   2688: 
1.48      www      2689:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   2690:     my $rest;
                   2691:     if ($therest[0]) {
                   2692:        $rest=join('.',@therest);
                   2693:     } else {
                   2694:        $rest='';
                   2695:     }
1.57      www      2696:     my $qualifierrest=$qualifier;
                   2697:     if ($rest) { $qualifierrest.='.'.$rest; }
                   2698:     my $spacequalifierrest=$space;
                   2699:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      2700:     if ($realm eq 'user') {
1.48      www      2701: # --------------------------------------------------------------- user.resource
                   2702: 	if ($space eq 'resource') {
1.218     albertel 2703: 	    my %restored=&restore(undef,undef,$udom,$uname);
1.57      www      2704:             return $restored{$qualifierrest};
1.48      www      2705: # ----------------------------------------------------------------- user.access
                   2706:         } elsif ($space eq 'access') {
1.218     albertel 2707: 	    # FIXME - not supporting calls for a specific user
1.48      www      2708:             return &allowed($qualifier,$rest);
                   2709: # ------------------------------------------ user.preferences, user.environment
                   2710:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 2711: 	    if (($uname eq $ENV{'user.name'}) &&
                   2712: 		($udom eq $ENV{'user.domain'})) {
                   2713: 		return $ENV{join('.',('environment',$qualifierrest))};
                   2714: 	    } else {
                   2715: 		my %returnhash=&userenvironment($udom,$uname,$qualifierrest);
                   2716: 		return $returnhash{$qualifierrest};
                   2717: 	    }
1.48      www      2718: # ----------------------------------------------------------------- user.course
                   2719:         } elsif ($space eq 'course') {
1.218     albertel 2720: 	    # FIXME - not supporting calls for a specific user
1.48      www      2721:             return $ENV{join('.',('request.course',$qualifier))};
                   2722: # ------------------------------------------------------------------- user.role
                   2723:         } elsif ($space eq 'role') {
1.218     albertel 2724: 	    # FIXME - not supporting calls for a specific user
1.48      www      2725:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   2726:             if ($qualifier eq 'value') {
                   2727: 		return $role;
                   2728:             } elsif ($qualifier eq 'extent') {
                   2729:                 return $where;
                   2730:             }
                   2731: # ----------------------------------------------------------------- user.domain
                   2732:         } elsif ($space eq 'domain') {
1.218     albertel 2733:             return $udom;
1.48      www      2734: # ------------------------------------------------------------------- user.name
                   2735:         } elsif ($space eq 'name') {
1.218     albertel 2736:             return $uname;
1.48      www      2737: # ---------------------------------------------------- Any other user namespace
1.29      www      2738:         } else {
1.48      www      2739:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
1.131     albertel 2740:             my %reply=&get($space,[$item]);
1.48      www      2741:             return $reply{$item};
                   2742:         }
1.236     www      2743:     } elsif ($realm eq 'query') {
                   2744: # ---------------------------------------------- pull stuff out of query string
                   2745:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
                   2746: 	return $ENV{'form.'.$space}; 
                   2747:    } elsif ($realm eq 'request') {
1.48      www      2748: # ------------------------------------------------------------- request.browser
                   2749:         if ($space eq 'browser') {
                   2750: 	    return $ENV{'browser.'.$qualifier};
1.57      www      2751: # ------------------------------------------------------------ request.filename
                   2752:         } else {
                   2753:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      2754:         }
1.28      www      2755:     } elsif ($realm eq 'course') {
1.48      www      2756: # ---------------------------------------------------------- course.description
1.218     albertel 2757:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      2758:     } elsif ($realm eq 'resource') {
1.165     www      2759: 
1.218     albertel 2760: 	if ($courseid eq $ENV{'request.course.id'}) {
1.165     www      2761: 
1.218     albertel 2762: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      2763: 
1.60      www      2764: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 2765: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   2766: 	    my $symbp=$symbparm;
                   2767: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
                   2768: 
                   2769: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   2770: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   2771: 
                   2772: 	    my $section;
                   2773: 	    if (($ENV{'user.name'} eq $uname) &&
                   2774: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 2775: 		$section=$ENV{'request.course.sec'};
1.218     albertel 2776: 	    } else {
                   2777: 		$section=&usection($udom,$uname,$courseid);
                   2778: 	    }
                   2779: 
                   2780: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   2781: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   2782: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   2783: 
                   2784: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
                   2785: 	    my $courselevelr=$courseid.'.'.$symbparm;
                   2786: 	    my $courselevelm=$courseid.'.'.$mapparm;
1.69      www      2787: 
1.60      www      2788: # ----------------------------------------------------------- first, check user
1.218     albertel 2789: 	    my %resourcedata=&get('resourcedata',
                   2790: 				  [$courselevelr,$courselevelm,$courselevel],
                   2791: 				 $udom,$uname);
                   2792: 	    if (($resourcedata{$courselevelr}!~/^error\:/) &&
                   2793: 		($resourcedata{$courselevelr}!~/^con_lost/)) {
                   2794: 
                   2795: 		if ($resourcedata{$courselevelr}) {
                   2796: 		    return $resourcedata{$courselevelr}; }
                   2797: 		if ($resourcedata{$courselevelm}) {
                   2798: 		    return $resourcedata{$courselevelm}; }
                   2799: 		if ($resourcedata{$courselevel}) {
                   2800: 		    return $resourcedata{$courselevel}; }
                   2801: 	    } else {
                   2802: 		if ($resourcedata{$courselevelr}!~/No such file/) {
                   2803: 		    &logthis("<font color=blue>WARNING:".
                   2804: 			     " Trying to get resource data for ".
                   2805: 			     $uname." at ".$udom.": ".
                   2806: 			     $resourcedata{$courselevelr}."</font>");
                   2807: 		}
                   2808: 	    }
1.95      www      2809: 
1.60      www      2810: # -------------------------------------------------------- second, check course
1.96      www      2811: 
1.218     albertel 2812: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   2813: 					  $ENV{'course.'.$courseid.'.domain'},
                   2814: 					  ($seclevelr,$seclevelm,$seclevel,
                   2815: 					   $courselevelr,$courselevelm,
                   2816: 					   $courselevel));
1.287     albertel 2817: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      2818: 
1.60      www      2819: # ------------------------------------------------------ third, check map parms
1.218     albertel 2820: 	    my %parmhash=();
                   2821: 	    my $thisparm='';
                   2822: 	    if (tie(%parmhash,'GDBM_File',
                   2823: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 2824: 		    &GDBM_READER(),0640)) {
1.218     albertel 2825: 		$thisparm=$parmhash{$symbparm};
                   2826: 		untie(%parmhash);
                   2827: 	    }
                   2828: 	    if ($thisparm) { return $thisparm; }
                   2829: 	}
1.60      www      2830: # --------------------------------------------- last, look in resource metadata
1.71      www      2831: 
1.218     albertel 2832: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 2833: 	my $filename;
                   2834: 	if (!$symbparm) { $symbparm=&symbread(); }
                   2835: 	if ($symbparm) {
                   2836: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
                   2837: 	} else {
                   2838: 	    $filename=$ENV{'request.filename'};
                   2839: 	}
                   2840: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 2841: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 2842: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 2843: 	if (defined($metadata)) { return $metadata; }
1.142     www      2844: 
1.145     www      2845: # ------------------------------------------------------------------ Cascade up
1.218     albertel 2846: 	unless ($space eq '0') {
                   2847: 	    my ($part,$id)=split(/\_/,$space);
                   2848: 	    if ($id) {
                   2849: 		my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
                   2850: 				     $symbparm,$udom,$uname);
1.288     albertel 2851: 		if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 2852: 	    } else {
                   2853: 		my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
                   2854: 					 $symbparm,$udom,$uname);
1.288     albertel 2855: 		if (defined($resourcegeneral)) { return $resourcegeneral; }
1.218     albertel 2856: 	    }
                   2857: 	}
1.71      www      2858: 
1.48      www      2859: # ---------------------------------------------------- Any other user namespace
                   2860:     } elsif ($realm eq 'environment') {
                   2861: # ----------------------------------------------------------------- environment
1.219     albertel 2862: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   2863: 	    return $ENV{'environment.'.$spacequalifierrest};
                   2864: 	} else {
                   2865: 	    my %returnhash=&userenvironment($udom,$uname,
                   2866: 					    $spacequalifierrest);
                   2867: 	    return $returnhash{$spacequalifierrest};
                   2868: 	}
1.28      www      2869:     } elsif ($realm eq 'system') {
1.48      www      2870: # ----------------------------------------------------------------- system.time
                   2871: 	if ($space eq 'time') {
                   2872: 	    return time;
                   2873:         }
1.28      www      2874:     }
1.48      www      2875:     return '';
1.61      www      2876: }
                   2877: 
1.71      www      2878: # ---------------------------------------------------------------- Get metadata
                   2879: 
                   2880: sub metadata {
1.176     www      2881:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      2882: 
1.71      www      2883:     $uri=&declutter($uri);
1.288     albertel 2884:     # if it is a non metadata possible uri return quickly
1.293     matthew  2885:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
                   2886:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
1.288     albertel 2887: 	return '';
                   2888:     }
1.73      www      2889:     my $filename=$uri;
                   2890:     $uri=~s/\.meta$//;
1.172     www      2891: #
                   2892: # Is the metadata already cached?
1.177     www      2893: # Look at timestamp of caching
1.172     www      2894: # Everything is cached by the main uri, libraries are never directly cached
                   2895: #
1.277     albertel 2896:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
1.172     www      2897: #
                   2898: # Is this a recursive call for a library?
                   2899: #
1.171     www      2900:         if ($liburi) {
                   2901: 	    $liburi=&declutter($liburi);
                   2902:             $filename=$liburi;
                   2903:         }
1.140     www      2904:         my %metathesekeys=();
1.73      www      2905:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
                   2906: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
1.208     albertel 2907:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      2908:         my $token;
1.140     www      2909:         undef %metathesekeys;
1.71      www      2910:         while ($token=$parser->get_token) {
                   2911:            if ($token->[0] eq 'S') {
1.135     www      2912: 	     if (defined($token->[2]->{'package'})) {
1.172     www      2913: #
                   2914: # This is a package - get package info
                   2915: #
1.136     www      2916: 	      my $package=$token->[2]->{'package'};
                   2917: 	      my $keyroot='';
1.172     www      2918:               if ($prefix) {
1.276     albertel 2919: 		  $keyroot.=$prefix;
1.172     www      2920:               } else {
                   2921:                 if (defined($token->[2]->{'part'})) { 
                   2922:                    $keyroot.='_'.$token->[2]->{'part'}; 
                   2923: 	        }
1.136     www      2924: 	      }
                   2925:               if (defined($token->[2]->{'id'})) { 
1.165     www      2926:                  $keyroot.='_'.$token->[2]->{'id'}; 
1.136     www      2927: 	      }
                   2928:               if ($metacache{$uri.':packages'}) {
                   2929:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
                   2930:               } else {
                   2931:                  $metacache{$uri.':packages'}=$package.$keyroot;
                   2932: 	      }
1.191     harris41 2933:               foreach (keys %packagetab) {
1.137     www      2934: 		  if ($_=~/^$package\&/) {
                   2935: 		      my ($pack,$name,$subp)=split(/\&/,$_);
1.139     www      2936:                       my $value=$packagetab{$_};
1.144     www      2937: 		      my $part=$keyroot;
                   2938:                       $part=~s/^\_//;
1.139     www      2939:                       if ($subp eq 'display') {
                   2940: 			  $value.=' [Part: '.$part.']';
                   2941:                       }
                   2942:                       my $unikey='parameter'.$keyroot.'_'.$name;
1.140     www      2943:                       $metathesekeys{$unikey}=1;
1.144     www      2944:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
1.141     www      2945:                       unless 
                   2946:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   2947:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   2948: 		      }
1.137     www      2949:                   }
1.191     harris41 2950:               }
1.135     www      2951:              } else {
1.172     www      2952: #
                   2953: # This is not a package - some other kind of start tag
                   2954: # 
1.175     www      2955:               my $entry=$token->[1];
1.176     www      2956:               my $unikey;
                   2957:               if ($entry eq 'import') {
                   2958:                  $unikey='';
                   2959:               } else {
                   2960:                  $unikey=$entry;
                   2961: 	      }
1.172     www      2962:               if ($prefix) {
1.176     www      2963: 		  $unikey.=$prefix;
1.172     www      2964:               } else {
                   2965:                 if (defined($token->[2]->{'part'})) { 
                   2966:                    $unikey.='_'.$token->[2]->{'part'}; 
                   2967: 	        }
1.136     www      2968: 	      }
                   2969:               if (defined($token->[2]->{'id'})) { 
1.165     www      2970:                  $unikey.='_'.$token->[2]->{'id'}; 
1.71      www      2971: 	      }
1.175     www      2972: 
                   2973:              if ($entry eq 'import') {
                   2974: #
                   2975: # Importing a library here
1.176     www      2976: #                
                   2977:                  if ($depthcount<20) {
1.276     albertel 2978: 		     my $location=$parser->get_text('/import');
                   2979: 		     my $dir=$filename;
                   2980: 		     $dir=~s|[^/]*$||;
                   2981: 		     $location=&filelocation($dir,$location);
                   2982: 		     foreach (sort(split(/\,/,&metadata($uri,'keys',
                   2983: 							$location,$unikey,
                   2984: 							$depthcount+1)))) {
1.177     www      2985:                          $metathesekeys{$_}=1;
1.191     harris41 2986: 		     }
1.176     www      2987: 		 }
1.175     www      2988:              } else { 
                   2989: 
1.72      www      2990:               if (defined($token->[2]->{'name'})) { 
1.71      www      2991:                  $unikey.='_'.$token->[2]->{'name'}; 
                   2992: 	      }
1.140     www      2993:               $metathesekeys{$unikey}=1;
1.191     harris41 2994:               foreach (@{$token->[3]}) {
1.71      www      2995: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.191     harris41 2996:               }
1.78      www      2997:               unless (
1.208     albertel 2998:                  $metacache{$uri.':'.$unikey}=&HTML::Entities::decode($parser->get_text('/'.$entry))
1.78      www      2999: 		      ) { $metacache{$uri.':'.$unikey}=
                   3000: 			      $metacache{$uri.':'.$unikey.'.default'};
                   3001: 		      }
1.172     www      3002: # end of not-a-package not-a-library import
1.175     www      3003: 	   }
1.172     www      3004: # end of not-a-package start tag
                   3005: 	  }
                   3006: # the next is the end of "start tag"
1.140     www      3007: 	 }
1.71      www      3008:        }
1.274     albertel 3009:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.261     albertel 3010: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
1.274     albertel 3011:        $metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
1.174     www      3012:        $metacache{$uri.':cachedtimestamp'}=time;
1.177     www      3013: # this is the end of "was not already recently cached
1.71      www      3014:     }
                   3015:     return $metacache{$uri.':'.$what};
1.261     albertel 3016: }
                   3017: 
                   3018: sub metadata_generate_part0 {
                   3019:     my ($metadata,$metacache,$uri) = @_;
                   3020:     my %allnames;
                   3021:     foreach my $metakey (sort keys %$metadata) {
                   3022: 	if ($metakey=~/^parameter\_(.*)/) {
                   3023: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
                   3024: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
                   3025: 	  if (! exists($$metadata{'parameter_0_'.$name})) {
                   3026: 	    $allnames{$name}=$part;
                   3027: 	  }
                   3028: 	}
                   3029:     }
                   3030:     foreach my $name (keys(%allnames)) {
                   3031:       $$metadata{"parameter_0_$name"}=1;
                   3032:       my $key="$uri:parameter_0_$name";
                   3033:       $$metacache{"$key.part"}='0';
                   3034:       $$metacache{"$key.name"}=$name;
                   3035:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
                   3036: 					   $allnames{$name}.'_'.$name.
                   3037: 					   '.type'};
                   3038:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
                   3039: 			     '.display'};
                   3040:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
                   3041:       $olddis=~s/$expr/\[Part: 0\]/;
                   3042:       $$metacache{"$key.display"}=$olddis;
                   3043:     }
1.71      www      3044: }
                   3045: 
1.31      www      3046: # ------------------------------------------------- Update symbolic store links
                   3047: 
                   3048: sub symblist {
                   3049:     my ($mapname,%newhash)=@_;
                   3050:     $mapname=declutter($mapname);
                   3051:     my %hash;
                   3052:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   3053:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3054:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 3055: 	    foreach (keys %newhash) {
1.211     www      3056:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 3057:             }
1.31      www      3058:             if (untie(%hash)) {
                   3059: 		return 'ok';
                   3060:             }
                   3061:         }
                   3062:     }
                   3063:     return 'error';
1.212     www      3064: }
                   3065: 
                   3066: # --------------------------------------------------------------- Verify a symb
                   3067: 
                   3068: sub symbverify {
                   3069:     my ($symb,$thisfn)=@_;
1.213     www      3070:     $thisfn=&declutter($thisfn);
1.215     www      3071: # direct jump to resource in page or to a sequence - will construct own symbs
                   3072:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   3073: # check URL part
1.213     www      3074:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
                   3075:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
                   3076: 
1.216     www      3077:     $symb=&symbclean($symb);
1.213     www      3078: 
                   3079:     my %bighash;
                   3080:     my $okay=0;
                   3081:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3082:                             &GDBM_READER(),0640)) {
1.280     www      3083:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.216     www      3084:         unless ($ids) { 
                   3085:            $ids=$bighash{'ids_/'.$thisfn};
                   3086:         }
                   3087:         if ($ids) {
                   3088: # ------------------------------------------------------------------- Has ID(s)
                   3089: 	    foreach (split(/\,/,$ids)) {
                   3090:                my ($mapid,$resid)=split(/\./,$_);
                   3091:                if (
                   3092:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   3093:    eq $symb) { 
                   3094:                   $okay=1; 
                   3095:                }
                   3096: 	   }
                   3097:         }
1.213     www      3098: 	untie(%bighash);
                   3099:     }
                   3100:     return $okay;
1.31      www      3101: }
                   3102: 
1.210     www      3103: # --------------------------------------------------------------- Clean-up symb
                   3104: 
                   3105: sub symbclean {
                   3106:     my $symb=shift;
1.213     www      3107: 
1.210     www      3108: # remove version from map
                   3109:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      3110: 
1.210     www      3111: # remove version from URL
                   3112:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      3113: 
1.210     www      3114:     return $symb;
                   3115: }
                   3116: 
1.31      www      3117: # ------------------------------------------------------ Return symb list entry
                   3118: 
                   3119: sub symbread {
1.249     www      3120:     my ($thisfn,$donotrecurse)=@_;
1.242     www      3121: # no filename provided? try from environment
1.44      www      3122:     unless ($thisfn) {
1.210     www      3123:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44      www      3124: 	$thisfn=$ENV{'request.filename'};
                   3125:     }
1.242     www      3126: # is that filename actually a symb? Verify, clean, and return
                   3127:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
                   3128: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
                   3129:     }
1.44      www      3130:     $thisfn=declutter($thisfn);
1.31      www      3131:     my %hash;
1.37      www      3132:     my %bighash;
                   3133:     my $syval='';
1.45      www      3134:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      3135:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3136:                       &GDBM_READER(),0640)) {
1.31      www      3137: 	    $syval=$hash{$thisfn};
1.37      www      3138:             untie(%hash);
                   3139:         }
                   3140: # ---------------------------------------------------------- There was an entry
                   3141:         if ($syval) {
                   3142:            unless ($syval=~/\_\d+$/) {
                   3143: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      3144:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      3145:                   return '';
                   3146:                }    
                   3147:                $syval.=$1;
                   3148: 	   }
                   3149:         } else {
                   3150: # ------------------------------------------------------- Was not in symb table
                   3151:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3152:                             &GDBM_READER(),0640)) {
1.37      www      3153: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      3154:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      3155:               unless ($ids) { 
                   3156:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      3157:               }
                   3158:               unless ($ids) {
                   3159: # alias?
                   3160: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      3161:               }
1.37      www      3162:               if ($ids) {
                   3163: # ------------------------------------------------------------------- Has ID(s)
                   3164:                  my @possibilities=split(/\,/,$ids);
1.39      www      3165:                  if ($#possibilities==0) {
                   3166: # ----------------------------------------------- There is only one possibility
1.37      www      3167: 		     my ($mapid,$resid)=split(/\./,$ids);
                   3168:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      3169:                  } elsif (!$donotrecurse) {
1.39      www      3170: # ------------------------------------------ There is more than one possibility
                   3171:                      my $realpossible=0;
1.191     harris41 3172:                      foreach (@possibilities) {
1.39      www      3173: 			 my $file=$bighash{'src_'.$_};
                   3174:                          if (&allowed('bre',$file)) {
                   3175:          		    my ($mapid,$resid)=split(/\./,$_);
                   3176:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   3177: 				$realpossible++;
                   3178:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   3179:                                        '___'.$resid;
                   3180:                             }
                   3181: 			 }
1.191     harris41 3182:                      }
1.39      www      3183: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      3184:                  } else {
                   3185:                      $syval='';
1.37      www      3186:                  }
                   3187: 	      }
                   3188:               untie(%bighash)
                   3189:            } 
1.31      www      3190:         }
1.62      www      3191:         if ($syval) {
1.210     www      3192:            return &symbclean($syval.'___'.$thisfn); 
1.62      www      3193:         }
1.31      www      3194:     }
1.44      www      3195:     &appenv('request.ambiguous' => $thisfn);
1.31      www      3196:     return '';
                   3197: }
                   3198: 
                   3199: # ---------------------------------------------------------- Return random seed
                   3200: 
1.32      www      3201: sub numval {
                   3202:     my $txt=shift;
                   3203:     $txt=~tr/A-J/0-9/;
                   3204:     $txt=~tr/a-j/0-9/;
                   3205:     $txt=~tr/K-T/0-9/;
                   3206:     $txt=~tr/k-t/0-9/;
                   3207:     $txt=~tr/U-Z/0-5/;
                   3208:     $txt=~tr/u-z/0-5/;
                   3209:     $txt=~s/\D//g;
                   3210:     return int($txt);
                   3211: }    
                   3212: 
1.31      www      3213: sub rndseed {
1.155     albertel 3214:     my ($symb,$courseid,$domain,$username)=@_;
                   3215:     if (!$symb) {
                   3216:       unless ($symb=&symbread()) { return time; }
                   3217:     }
                   3218:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
                   3219:     if (!$domain) {$domain=$ENV{'user.domain'};}
                   3220:     if (!$username) {$username=$ENV{'user.name'};}
                   3221:     {
1.98      albertel 3222:       use integer;
                   3223:       my $symbchck=unpack("%32C*",$symb) << 27;
1.100     albertel 3224:       my $symbseed=numval($symb) << 22;
1.155     albertel 3225:       my $namechck=unpack("%32C*",$username) << 17;
                   3226:       my $nameseed=numval($username) << 12;
                   3227:       my $domainseed=unpack("%32C*",$domain) << 7;
                   3228:       my $courseseed=unpack("%32C*",$courseid);
1.98      albertel 3229:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.99      albertel 3230:       #uncommenting these lines can break things!
                   3231:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   3232:       #&Apache::lonxml::debug("rndseed :$num:$symb");
1.98      albertel 3233:       return $num;
                   3234:     }
1.36      albertel 3235: }
                   3236: 
1.76      www      3237: sub ireceipt {
                   3238:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   3239:     my $cuname=unpack("%32C*",$funame);
                   3240:     my $cudom=unpack("%32C*",$fudom);
                   3241:     my $cucourseid=unpack("%32C*",$fucourseid);
                   3242:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      3243:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      3244:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   3245:            ($cunique%$cuname+
                   3246:             $cunique%$cudom+
                   3247:             $cusymb%$cuname+
                   3248:             $cusymb%$cudom+
                   3249:             $cucourseid%$cuname+
                   3250:             $cucourseid%$cudom);
                   3251: }
                   3252: 
                   3253: sub receipt {
1.260     ng       3254:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   3255:   return &ireceipt($name,$domain,$courseid,$symb);
1.76      www      3256: }
1.260     ng       3257: 
1.36      albertel 3258: # ------------------------------------------------------------ Serves up a file
                   3259: # returns either the contents of the file or a -1
                   3260: sub getfile {
1.269     www      3261:  my $file=shift;
                   3262:  if ($file=~/^\/*uploaded\//) { # user file
                   3263:     my $ua=new LWP::UserAgent;
                   3264:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
                   3265:     my $response=$ua->request($request);
                   3266:     if ($response->is_success()) {
                   3267:        return $response->content;
                   3268:     } else { 
                   3269:        return -1; 
                   3270:     }
                   3271:  } else { # normal file from res space
1.37      www      3272:   &repcopy($file);
1.36      albertel 3273:   if (! -e $file ) { return -1; };
                   3274:   my $fh=Apache::File->new($file);
                   3275:   my $a='';
                   3276:   while (<$fh>) { $a .=$_; }
1.269     www      3277:   return $a;
                   3278:  }
1.36      albertel 3279: }
                   3280: 
                   3281: sub filelocation {
                   3282:   my ($dir,$file) = @_;
                   3283:   my $location;
                   3284:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 3285:   if ($file=~m:^/~:) { # is a contruction space reference
                   3286:     $location = $file;
                   3287:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270     www      3288:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
                   3289:     $location=$file;
1.36      albertel 3290:   } else {
1.59      albertel 3291:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   3292:     $file=~s:^/*res::;
                   3293:     if ( !( $file =~ m:^/:) ) {
                   3294:       $location = $dir. '/'.$file;
                   3295:     } else {
                   3296:       $location = '/home/httpd/html/res'.$file;
                   3297:     }
1.36      albertel 3298:   }
                   3299:   $location=~s://+:/:g; # remove duplicate /
1.46      www      3300:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   3301:   return $location;
                   3302: }
1.36      albertel 3303: 
1.46      www      3304: sub hreflocation {
                   3305:     my ($dir,$file)=@_;
1.191     harris41 3306:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      3307:        my $finalpath=filelocation($dir,$file);
                   3308:        $finalpath=~s/^\/home\/httpd\/html//;
1.225     albertel 3309:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46      www      3310:        return $finalpath;
                   3311:     } else {
                   3312:        return $file;
                   3313:     }
1.31      www      3314: }
                   3315: 
                   3316: # ------------------------------------------------------------- Declutters URLs
                   3317: 
                   3318: sub declutter {
                   3319:     my $thisfn=shift;
                   3320:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   3321:     $thisfn=~s/^\///;
                   3322:     $thisfn=~s/^res\///;
1.235     www      3323:     $thisfn=~s/\?.+$//;
1.268     www      3324:     return $thisfn;
                   3325: }
                   3326: 
                   3327: # ------------------------------------------------------------- Clutter up URLs
                   3328: 
                   3329: sub clutter {
                   3330:     my $thisfn='/'.&declutter(shift);
1.270     www      3331:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
                   3332:        $thisfn='/res'.$thisfn; 
                   3333:     }
1.31      www      3334:     return $thisfn;
1.12      www      3335: }
                   3336: 
                   3337: # -------------------------------------------------------- Escape Special Chars
                   3338: 
                   3339: sub escape {
                   3340:     my $str=shift;
                   3341:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   3342:     return $str;
                   3343: }
                   3344: 
                   3345: # ----------------------------------------------------- Un-Escape Special Chars
                   3346: 
                   3347: sub unescape {
                   3348:     my $str=shift;
                   3349:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   3350:     return $str;
                   3351: }
1.11      www      3352: 
1.1       albertel 3353: # ================================================================ Main Program
                   3354: 
1.184     www      3355: sub goodbye {
1.204     albertel 3356:    &logthis("Starting Shut down");
1.184     www      3357:    &flushcourselogs();
                   3358:    &logthis("Shutting down");
                   3359: }
                   3360: 
1.179     www      3361: BEGIN {
1.228     harris41 3362: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      3363:     unless ($readit) {
1.217     harris41 3364: {
                   3365:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
                   3366: 
                   3367:     while (my $configline=<$config>) {
                   3368:         if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 3369: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      3370:            chomp($varvalue);
1.1       albertel 3371:            $perlvar{$varname}=$varvalue;
                   3372:         }
                   3373:     }
                   3374: }
1.227     harris41 3375: {
                   3376:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
                   3377: 
                   3378:     while (my $configline=<$config>) {
                   3379:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   3380: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   3381:            chomp($varvalue);
                   3382:            $perlvar{$varname}=$varvalue;
                   3383:         }
                   3384:     }
                   3385: }
1.1       albertel 3386: 
                   3387: # ------------------------------------------------------------- Read hosts file
                   3388: {
                   3389:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   3390: 
                   3391:     while (my $configline=<$config>) {
1.154     www      3392:        chomp($configline);
1.245     www      3393:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252     albertel 3394:        if ($id && $domain && $role && $name && $ip) {
                   3395: 	 $hostname{$id}=$name;
                   3396: 	 $hostdom{$id}=$domain;
                   3397: 	 $hostip{$id}=$ip;
                   3398: 	 if ($domdescr) { $domaindescription{$domain}=$domdescr; }
                   3399: 	 if ($role eq 'library') { $libserv{$id}=$name; }
                   3400:        } else {
                   3401: 	 if ($configline) {
                   3402: 	   &logthis("Skipping hosts.tab line -$configline-");
                   3403: 	 }
1.245     www      3404:        }
1.1       albertel 3405:     }
                   3406: }
                   3407: 
                   3408: # ------------------------------------------------------ Read spare server file
                   3409: {
                   3410:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   3411: 
                   3412:     while (my $configline=<$config>) {
                   3413:        chomp($configline);
1.284     matthew  3414:        if ($configline) {
1.1       albertel 3415:           $spareid{$configline}=1;
                   3416:        }
                   3417:     }
                   3418: }
1.11      www      3419: # ------------------------------------------------------------ Read permissions
                   3420: {
                   3421:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   3422: 
                   3423:     while (my $configline=<$config>) {
                   3424:        chomp($configline);
1.160     www      3425:       if ($configline) {
1.11      www      3426:        my ($role,$perm)=split(/ /,$configline);
                   3427:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      3428:       }
1.11      www      3429:     }
                   3430: }
                   3431: 
                   3432: # -------------------------------------------- Read plain texts for permissions
                   3433: {
                   3434:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   3435: 
                   3436:     while (my $configline=<$config>) {
                   3437:        chomp($configline);
1.160     www      3438:       if ($configline) {
1.11      www      3439:        my ($short,$plain)=split(/:/,$configline);
                   3440:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      3441:       }
1.135     www      3442:     }
                   3443: }
                   3444: 
                   3445: # ---------------------------------------------------------- Read package table
                   3446: {
                   3447:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   3448: 
                   3449:     while (my $configline=<$config>) {
                   3450:        chomp($configline);
                   3451:        my ($short,$plain)=split(/:/,$configline);
1.143     www      3452:        my ($pack,$name)=split(/\&/,$short);
                   3453:        if ($plain ne '') {
                   3454:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   3455:           $packagetab{$short}=$plain; 
1.25      www      3456:        }
1.11      www      3457:     }
                   3458: }
                   3459: 
1.71      www      3460: %metacache=();
1.185     www      3461: 
1.281     www      3462: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      3463: $dumpcount=0;
1.22      www      3464: 
1.163     harris41 3465: &logtouch();
1.12      www      3466: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      3467: $readit=1;
                   3468: }
1.1       albertel 3469: }
1.179     www      3470: 
1.1       albertel 3471: 1;
1.191     harris41 3472: __END__
                   3473: 
1.243     albertel 3474: =pod
                   3475: 
1.191     harris41 3476: =head1 NAME
                   3477: 
1.243     albertel 3478: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 3479: 
                   3480: =head1 SYNOPSIS
                   3481: 
1.243     albertel 3482: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 3483: 
                   3484:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   3485: 
1.243     albertel 3486: Common parameters:
                   3487: 
                   3488: =over 4
                   3489: 
                   3490: =item *
                   3491: 
                   3492: $uname : an internal username (if $cname expecting a course Id specifically)
                   3493: 
                   3494: =item *
                   3495: 
                   3496: $udom : a domain (if $cdom expecting a course's domain specifically)
                   3497: 
                   3498: =item *
                   3499: 
                   3500: $symb : a resource instance identifier
                   3501: 
                   3502: =item *
                   3503: 
                   3504: $namespace : the name of a .db file that contains the data needed or
                   3505: being set.
                   3506: 
                   3507: =back
                   3508: 
1.191     harris41 3509: =head1 INTRODUCTION
                   3510: 
                   3511: This module provides subroutines which interact with the
1.243     albertel 3512: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
                   3513: - classes
                   3514: - users 
                   3515: - resources
                   3516: 
                   3517: For many of these objects you can also use this to store data about
                   3518: them or modify them in various ways.
1.191     harris41 3519: 
                   3520: This is part of the LearningOnline Network with CAPA project
                   3521: described at http://www.lon-capa.org.
                   3522: 
1.243     albertel 3523: =head1 RETURN MESSAGES
1.191     harris41 3524: 
                   3525: =over 4
                   3526: 
                   3527: =item *
                   3528: 
1.243     albertel 3529: con_lost : unable to contact remote host
1.191     harris41 3530: 
                   3531: =item *
                   3532: 
1.243     albertel 3533: con_delayed : unable to contact remote host, message will be delivered
                   3534: when the connection is brought back up
1.191     harris41 3535: 
                   3536: =item *
                   3537: 
1.243     albertel 3538: con_failed : unable to contact remote host and unable to save message
                   3539: for later delivery
1.191     harris41 3540: 
                   3541: =item *
                   3542: 
1.243     albertel 3543: error: : an error a occured, a description of the error follows the :
1.191     harris41 3544: 
                   3545: =item *
                   3546: 
1.243     albertel 3547: no_such_host : unable to fund a host associated with the user/domain
                   3548: that was requested
1.191     harris41 3549: 
1.243     albertel 3550: =back
1.191     harris41 3551: 
1.243     albertel 3552: =head1 PUBLIC SUBROUTINES
1.191     harris41 3553: 
1.243     albertel 3554: =head2 Session Environment Functions
1.191     harris41 3555: 
1.243     albertel 3556: =over 4
1.191     harris41 3557: 
                   3558: =item *
                   3559: 
1.243     albertel 3560: appenv(%hash) : the value of %hash is written to the user envirnoment
                   3561: file, and will be restored for each access this user makes during this
                   3562: session, also modifies the %ENV for the current process
1.191     harris41 3563: 
                   3564: =item *
                   3565: 
1.243     albertel 3566: delenv($regexp) : removes all items from the session environment file that matches the regular expression in $regexp. The values are also delted from the current processes %ENV.
1.191     harris41 3567: 
1.243     albertel 3568: =back
                   3569: 
                   3570: =head2 User Information
1.191     harris41 3571: 
1.243     albertel 3572: =over 4
1.191     harris41 3573: 
                   3574: =item *
                   3575: 
                   3576: queryauthenticate($uname,$udom) : try to determine user's current
                   3577: authentication scheme
                   3578: 
                   3579: =item *
                   3580: 
                   3581: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
1.243     albertel 3582: servers (first use the current one), $upass should be the users password
1.191     harris41 3583: 
                   3584: =item *
                   3585: 
1.243     albertel 3586: homeserver($uname,$udom) : find the server which has the user's
                   3587: directory and files (there must be only one), this caches the answer,
                   3588: and also caches if there is a borken connection.
1.191     harris41 3589: 
                   3590: =item *
                   3591: 
1.243     albertel 3592: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
                   3593: unique resource in a domain, there must be only 1 ID per username, and
                   3594: only 1 username per ID in a specific domain) (returns hash:
1.191     harris41 3595: id=>name,id=>name)
                   3596: 
                   3597: =item *
                   3598: 
                   3599: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
                   3600: name=>id,name=>id)
                   3601: 
                   3602: =item *
                   3603: 
                   3604: idput($udom,%ids) : store away a list of names and associated IDs
                   3605: 
                   3606: =item *
                   3607: 
1.243     albertel 3608: rolesinit($udom,$username,$authhost) : get user privileges
                   3609: 
                   3610: =item *
                   3611: 
                   3612: usection($udom,$uname,$cname) : finds the section of student in the
                   3613: course $cname, return section name/number or '' for "not in course"
                   3614: and '-1' for "no section"
                   3615: 
                   3616: =item *
                   3617: 
                   3618: userenvironment($udom,$uname,@what) : gets the values of the keys
                   3619: passed in @what from the requested user's environment, returns a hash
                   3620: 
                   3621: =back
                   3622: 
                   3623: =head2 User Roles
                   3624: 
                   3625: =over 4
                   3626: 
                   3627: =item *
                   3628: 
                   3629: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   3630: actions
                   3631:  F: full access
                   3632:  U,I,K: authentication modes (cxx only)
                   3633:  '': forbidden
                   3634:  1: user needs to choose course
                   3635:  2: browse allowed
                   3636: 
                   3637: =item *
                   3638: 
                   3639: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   3640: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   3641: and course level
                   3642: 
                   3643: =item *
                   3644: 
                   3645: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   3646: explanation of a user role term
                   3647: 
                   3648: =back
                   3649: 
                   3650: =head2 User Modification
                   3651: 
                   3652: =over 4
                   3653: 
                   3654: =item *
                   3655: 
                   3656: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   3657: user for the level given by URL.  Optional start and end dates (leave empty
                   3658: string or zero for "no date")
1.191     harris41 3659: 
                   3660: =item *
                   3661: 
1.243     albertel 3662: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   3663: change a users, password, possible return values are: ok,
                   3664: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   3665: refused
1.191     harris41 3666: 
                   3667: =item *
                   3668: 
1.243     albertel 3669: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 3670: 
                   3671: =item *
                   3672: 
1.243     albertel 3673: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   3674: modify user
1.191     harris41 3675: 
                   3676: =item *
                   3677: 
1.286     matthew  3678: modifystudent
                   3679: 
                   3680: modify a students enrollment and identification information.
                   3681: The course id is resolved based on the current users environment.  
                   3682: This means the envoking user must be a course coordinator or otherwise
                   3683: associated with a course.
                   3684: 
1.297   ! matthew  3685: This call is essentially a wrapper for lonnet::modifyuser and
        !          3686: lonnet::modify_student_enrollment
1.286     matthew  3687: 
                   3688: Inputs: 
                   3689: 
                   3690: =over 4
                   3691: 
                   3692: =item B<$udom> Students loncapa domain
                   3693: 
                   3694: =item B<$uname> Students loncapa login name
                   3695: 
                   3696: =item B<$uid> Students id/student number
                   3697: 
                   3698: =item B<$umode> Students authentication mode
                   3699: 
                   3700: =item B<$upass> Students password
                   3701: 
                   3702: =item B<$first> Students first name
                   3703: 
                   3704: =item B<$middle> Students middle name
                   3705: 
                   3706: =item B<$last> Students last name
                   3707: 
                   3708: =item B<$gene> Students generation
                   3709: 
                   3710: =item B<$usec> Students section in course
                   3711: 
                   3712: =item B<$end> Unix time of the roles expiration
                   3713: 
                   3714: =item B<$start> Unix time of the roles start date
                   3715: 
                   3716: =item B<$forceid> If defined, allow $uid to be changed
                   3717: 
                   3718: =item B<$desiredhome> server to use as home server for student
                   3719: 
                   3720: =back
1.297   ! matthew  3721: 
        !          3722: =item *
        !          3723: 
        !          3724: modify_student_enrollment
        !          3725: 
        !          3726: Change a students enrollment status in a class.  The environment variable
        !          3727: 'role.request.course' must be defined for this function to proceed.
        !          3728: 
        !          3729: Inputs:
        !          3730: 
        !          3731: =over 4
        !          3732: 
        !          3733: =item $udom, students domain
        !          3734: 
        !          3735: =item $uname, students name
        !          3736: 
        !          3737: =item $uid, students user id
        !          3738: 
        !          3739: =item $first, students first name
        !          3740: 
        !          3741: =item $middle
        !          3742: 
        !          3743: =item $last
        !          3744: 
        !          3745: =item $gene
        !          3746: 
        !          3747: =item $usec
        !          3748: 
        !          3749: =item $end
        !          3750: 
        !          3751: =item $start
        !          3752: 
        !          3753: =back
        !          3754: 
1.191     harris41 3755: 
                   3756: =item *
                   3757: 
1.243     albertel 3758: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   3759: custom role; give a custom role to a user for the level given by URL.  Specify
                   3760: name and domain of role author, and role name
1.191     harris41 3761: 
                   3762: =item *
                   3763: 
1.243     albertel 3764: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 3765: 
                   3766: =item *
                   3767: 
1.243     albertel 3768: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   3769: 
                   3770: =back
                   3771: 
                   3772: =head2 Course Infomation
                   3773: 
                   3774: =over 4
1.191     harris41 3775: 
                   3776: =item *
                   3777: 
1.243     albertel 3778: coursedescription($courseid) : course description
1.191     harris41 3779: 
                   3780: =item *
                   3781: 
1.243     albertel 3782: courseresdata($coursenum,$coursedomain,@which) : request for current
                   3783: parameter setting for a specific course, @what should be a list of
                   3784: parameters to ask about. This routine caches answers for 5 minutes.
                   3785: 
                   3786: =back
                   3787: 
                   3788: =head2 Course Modification
                   3789: 
                   3790: =over 4
1.191     harris41 3791: 
                   3792: =item *
                   3793: 
1.243     albertel 3794: writecoursepref($courseid,%prefs) : write preferences (environment
                   3795: database) for a course
1.191     harris41 3796: 
                   3797: =item *
                   3798: 
1.243     albertel 3799: createcourse($udom,$description,$url) : make/modify course
                   3800: 
                   3801: =back
                   3802: 
                   3803: =head2 Resource Subroutines
                   3804: 
                   3805: =over 4
1.191     harris41 3806: 
                   3807: =item *
                   3808: 
1.243     albertel 3809: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 3810: 
                   3811: =item *
                   3812: 
1.243     albertel 3813: repcopy($filename) : subscribes to the requested file, and attempts to
                   3814: replicate from the owning library server, Might return
                   3815: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
                   3816: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
                   3817: resource. Expects the local filesystem pathname
                   3818: (/home/httpd/html/res/....)
                   3819: 
                   3820: =back
                   3821: 
                   3822: =head2 Resource Information
                   3823: 
                   3824: =over 4
1.191     harris41 3825: 
                   3826: =item *
                   3827: 
1.243     albertel 3828: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   3829: a vairety of different possible values, $varname should be a request
                   3830: string, and the other parameters can be used to specify who and what
                   3831: one is asking about.
                   3832: 
                   3833: Possible values for $varname are environment.lastname (or other item
                   3834: from the envirnment hash), user.name (or someother aspect about the
                   3835: user), resource.0.maxtries (or some other part and parameter of a
                   3836: resource)
1.204     albertel 3837: 
                   3838: =item *
                   3839: 
1.243     albertel 3840: directcondval($number) : get current value of a condition; reads from a state
                   3841: string
1.204     albertel 3842: 
                   3843: =item *
                   3844: 
1.243     albertel 3845: condval($condidx) : value of condition index based on state
1.204     albertel 3846: 
                   3847: =item *
                   3848: 
1.243     albertel 3849: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   3850: resource's metadata, $what should be either a specific key, or either
                   3851: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   3852: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   3853: 
                   3854: this function automatically caches all requests
1.191     harris41 3855: 
                   3856: =item *
                   3857: 
1.243     albertel 3858: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   3859: network of library servers; returns file handle of where SQL and regex results
                   3860: will be stored for query
1.191     harris41 3861: 
                   3862: =item *
                   3863: 
1.243     albertel 3864: symbread($filename) : return symbolic list entry (filename argument optional);
                   3865: returns the data handle
1.191     harris41 3866: 
                   3867: =item *
                   3868: 
1.243     albertel 3869: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
                   3870: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
                   3871: failure, user must be in a course, as it assumes the existance of the
                   3872: course initi hash, and uses $ENV('request.course.id'}
                   3873: 
1.191     harris41 3874: 
                   3875: =item *
                   3876: 
1.243     albertel 3877: symbclean($symb) : removes versions numbers from a symb, returns the
                   3878: cleaned symb
1.191     harris41 3879: 
                   3880: =item *
                   3881: 
1.243     albertel 3882: is_on_map($uri) : checks if the $uri is somewhere on the current
                   3883: course map, user must be in a course for it to work.
1.191     harris41 3884: 
                   3885: =item *
                   3886: 
1.243     albertel 3887: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 3888: 
                   3889: =item *
                   3890: 
1.243     albertel 3891: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   3892: a random seed, all arguments are optional, if they aren't sent it uses the
                   3893: environment to derive them. Note: if symb isn't sent and it can't get one
                   3894: from &symbread it will use the current time as its return value
1.191     harris41 3895: 
                   3896: =item *
                   3897: 
1.243     albertel 3898: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   3899: unfakeable, receipt
1.191     harris41 3900: 
                   3901: =item *
                   3902: 
1.243     albertel 3903: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 3904: 
                   3905: =item *
                   3906: 
1.243     albertel 3907: countacc($url) : count the number of accesses to a given URL
1.191     harris41 3908: 
                   3909: =item *
                   3910: 
1.243     albertel 3911: 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 3912: 
                   3913: =item *
                   3914: 
1.243     albertel 3915: 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 3916: 
                   3917: =item *
                   3918: 
1.243     albertel 3919: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 3920: 
                   3921: =item *
                   3922: 
1.243     albertel 3923: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   3924: forcing spreadsheet to reevaluate the resource scores next time.
                   3925: 
                   3926: =back
                   3927: 
                   3928: =head2 Storing/Retreiving Data
                   3929: 
                   3930: =over 4
1.191     harris41 3931: 
                   3932: =item *
                   3933: 
1.243     albertel 3934: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   3935: for this url; hashref needs to be given and should be a \%hashname; the
                   3936: remaining args aren't required and if they aren't passed or are '' they will
                   3937: be derived from the ENV
1.191     harris41 3938: 
                   3939: =item *
                   3940: 
1.243     albertel 3941: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   3942: uses critical subroutine
1.191     harris41 3943: 
                   3944: =item *
                   3945: 
1.243     albertel 3946: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   3947: all args are optional
1.191     harris41 3948: 
                   3949: =item *
                   3950: 
1.243     albertel 3951: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   3952: works very similar to store/cstore, but all data is stored in a
                   3953: temporary location and can be reset using tmpreset, $storehash should
                   3954: be a hash reference, returns nothing on success
1.191     harris41 3955: 
                   3956: =item *
                   3957: 
1.243     albertel 3958: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   3959: similar to restore, but all data is stored in a temporary location and
                   3960: can be reset using tmpreset. Returns a hash of values on success,
                   3961: error string otherwise.
1.191     harris41 3962: 
                   3963: =item *
                   3964: 
1.243     albertel 3965: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   3966: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 3967: 
                   3968: =item *
                   3969: 
1.243     albertel 3970: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   3971: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 3972: 
                   3973: =item *
                   3974: 
1.243     albertel 3975: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   3976: namesp ($udom and $uname are optional)
1.191     harris41 3977: 
                   3978: =item *
                   3979: 
1.243     albertel 3980: dump($namespace,$udom,$uname,$regexp) : 
                   3981: dumps the complete (or key matching regexp) namespace into a hash
                   3982: ($udom, $uname and $regexp are optional)
1.191     harris41 3983: 
                   3984: =item *
                   3985: 
1.243     albertel 3986: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   3987: ($udom and $uname are optional)
1.191     harris41 3988: 
                   3989: =item *
                   3990: 
1.243     albertel 3991: cput($namespace,$storehash,$udom,$uname) : critical put
                   3992: ($udom and $uname are optional)
1.191     harris41 3993: 
                   3994: =item *
                   3995: 
1.243     albertel 3996: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   3997: reference filled in from namesp (encrypts the return communication)
                   3998: ($udom and $uname are optional)
1.191     harris41 3999: 
                   4000: =item *
                   4001: 
1.243     albertel 4002: log($udom,$name,$home,$message) : write to permanent log for user; use
                   4003: critical subroutine
                   4004: 
                   4005: =back
                   4006: 
                   4007: =head2 Network Status Functions
                   4008: 
                   4009: =over 4
1.191     harris41 4010: 
                   4011: =item *
                   4012: 
                   4013: dirlist($uri) : return directory list based on URI
                   4014: 
                   4015: =item *
                   4016: 
1.243     albertel 4017: spareserver() : find server with least workload from spare.tab
                   4018: 
                   4019: =back
                   4020: 
                   4021: =head2 Apache Request
                   4022: 
                   4023: =over 4
1.191     harris41 4024: 
                   4025: =item *
                   4026: 
1.243     albertel 4027: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   4028: localhost, posts hash
                   4029: 
                   4030: =back
                   4031: 
                   4032: =head2 Data to String to Data
                   4033: 
                   4034: =over 4
1.191     harris41 4035: 
                   4036: =item *
                   4037: 
1.243     albertel 4038: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   4039: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 4040: 
                   4041: =item *
                   4042: 
1.243     albertel 4043: hashref2str($hashref) : convert a hashref into a string complete with
                   4044: escaping and '=' and '&' separators, supports elements that are
                   4045: arrayrefs and hashrefs
1.191     harris41 4046: 
                   4047: =item *
                   4048: 
1.243     albertel 4049: arrayref2str($arrayref) : convert an arrayref into a string complete
                   4050: with escaping and '&' separators, supports elements that are arrayrefs
                   4051: and hashrefs
1.191     harris41 4052: 
                   4053: =item *
                   4054: 
1.243     albertel 4055: str2hash($string) : convert string to hash using unescaping and
                   4056: splitting on '=' and '&', supports elements that are arrayrefs and
                   4057: hashrefs
1.191     harris41 4058: 
                   4059: =item *
                   4060: 
1.243     albertel 4061: str2array($string) : convert string to hash using unescaping and
                   4062: splitting on '&', supports elements that are arrayrefs and hashrefs
                   4063: 
                   4064: =back
                   4065: 
                   4066: =head2 Logging Routines
                   4067: 
                   4068: =over 4
                   4069: 
                   4070: These routines allow one to make log messages in the lonnet.log and
                   4071: lonnet.perm logfiles.
1.191     harris41 4072: 
                   4073: =item *
                   4074: 
1.243     albertel 4075: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 4076: 
                   4077: =item *
                   4078: 
1.243     albertel 4079: logthis() : append message to the normal lonnet.log file, it gets
                   4080: preiodically rolled over and deleted.
1.191     harris41 4081: 
                   4082: =item *
                   4083: 
1.243     albertel 4084: logperm() : append a permanent message to lonnet.perm.log, this log
                   4085: file never gets deleted by any automated portion of the system, only
                   4086: messages of critical importance should go in here.
                   4087: 
                   4088: =back
                   4089: 
                   4090: =head2 General File Helper Routines
                   4091: 
                   4092: =over 4
1.191     harris41 4093: 
                   4094: =item *
                   4095: 
1.243     albertel 4096: getfile($file) : returns the entire contents of a file or -1; it
                   4097: properly subscribes to and replicates the file if neccessary.
1.191     harris41 4098: 
                   4099: =item *
                   4100: 
1.243     albertel 4101: filelocation($dir,$file) : returns file system location of a file
                   4102: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   4103: directory that relative $file lookups are to looked in ($dir of /a/dir
                   4104: and a file of ../bob will become /a/bob)
1.191     harris41 4105: 
                   4106: =item *
                   4107: 
                   4108: hreflocation($dir,$file) : returns file system location or a URL; same as
                   4109: filelocation except for hrefs
                   4110: 
                   4111: =item *
                   4112: 
                   4113: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   4114: 
1.243     albertel 4115: =back
                   4116: 
                   4117: =head2 HTTP Helper Routines
                   4118: 
                   4119: =over 4
                   4120: 
1.191     harris41 4121: =item *
                   4122: 
                   4123: escape() : unpack non-word characters into CGI-compatible hex codes
                   4124: 
                   4125: =item *
                   4126: 
                   4127: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   4128: 
1.243     albertel 4129: =back
                   4130: 
                   4131: =head1 PRIVATE SUBROUTINES
                   4132: 
                   4133: =head2 Underlying communication routines (Shouldn't call)
                   4134: 
                   4135: =over 4
                   4136: 
                   4137: =item *
                   4138: 
                   4139: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   4140: 
                   4141: =item *
                   4142: 
                   4143: reply() : uses subreply to send a message to remote machine, logs all failures
                   4144: 
                   4145: =item *
                   4146: 
                   4147: critical() : passes a critical message to another server; if cannot
                   4148: get through then place message in connection buffer directory and
                   4149: returns con_delayed, if incapable of saving message, returns
                   4150: con_failed
                   4151: 
                   4152: =item *
                   4153: 
                   4154: reconlonc() : tries to reconnect lonc client processes.
                   4155: 
                   4156: =back
                   4157: 
                   4158: =head2 Resource Access Logging
                   4159: 
                   4160: =over 4
                   4161: 
                   4162: =item *
                   4163: 
                   4164: flushcourselogs() : flush (save) buffer logs and access logs
                   4165: 
                   4166: =item *
                   4167: 
                   4168: courselog($what) : save message for course in hash
                   4169: 
                   4170: =item *
                   4171: 
                   4172: courseacclog($what) : save message for course using &courselog().  Perform
                   4173: special processing for specific resource types (problems, exams, quizzes, etc).
                   4174: 
1.191     harris41 4175: =item *
                   4176: 
                   4177: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   4178: as a PerlChildExitHandler
1.243     albertel 4179: 
                   4180: =back
                   4181: 
                   4182: =head2 Other
                   4183: 
                   4184: =over 4
                   4185: 
                   4186: =item *
                   4187: 
                   4188: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 4189: 
                   4190: =back
                   4191: 
                   4192: =cut

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