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

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

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