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

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

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