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

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

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