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

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

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