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

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

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