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

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

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