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

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

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