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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.204   ! albertel    4: # $Id: lonnet.pm,v 1.203 2002/02/25 14:33:58 www Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
                     29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
                     30: # 11/8,11/16,11/18,11/22,11/23,12/22,
                     31: # 01/06,01/13,02/24,02/28,02/29,
                     32: # 03/01,03/02,03/06,03/07,03/13,
                     33: # 04/05,05/29,05/31,06/01,
                     34: # 06/05,06/26 Gerd Kortemeyer
                     35: # 06/26 Ben Tyszka
                     36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
                     37: # 08/14 Ben Tyszka
                     38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
                     39: # 10/04 Gerd Kortemeyer
                     40: # 10/04 Guy Albertelli
                     41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
                     42: # 10/30,10/31,
                     43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
                     44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
                     45: # 05/01/01 Guy Albertelli
                     46: # 05/01,06/01,09/01 Gerd Kortemeyer
                     47: # 09/01 Guy Albertelli
                     48: # 09/01,10/01,11/01 Gerd Kortemeyer
                     49: # YEAR=2001
                     50: # 02/27/01 Scott Harrison
                     51: # 3/2 Gerd Kortemeyer
                     52: # 3/15,3/19 Scott Harrison
                     53: # 3/19,3/20 Gerd Kortemeyer
                     54: # 3/22,3/27,4/2,4/16,4/17 Scott Harrison
                     55: # 5/26,5/28 Gerd Kortemeyer
                     56: # 5/30 H. K. Ng
                     57: # 6/1 Gerd Kortemeyer
                     58: # July Guy Albertelli
                     59: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
                     60: # 10/2 Gerd Kortemeyer
                     61: # 10/5,10/10,11/13,11/15 Scott Harrison
1.179     www        62: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
1.182     matthew    63: # 12/5 Matthew Hall
1.184     www        64: # 12/5 Guy Albertelli
1.190     www        65: # 12/6,12/7,12/12 Gerd Kortemeyer
1.191     harris41   66: # 12/18 Scott Harrison
1.195     www        67: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
1.196     www        68: # YEAR=2002
1.200     www        69: # 1/4,2/4,2/7 Gerd Kortemeyer
1.171     www        70: #
1.169     harris41   71: ###
                     72: 
1.1       albertel   73: package Apache::lonnet;
                     74: 
                     75: use strict;
                     76: use Apache::File;
1.8       www        77: use LWP::UserAgent();
1.15      www        78: use HTTP::Headers;
1.11      www        79: use vars 
1.188     www        80: qw(%perlvar %hostname %homecache %hostip %spareid %hostdom 
1.192     www        81:    %libserv %pr %prp %metacache %packagetab 
1.188     www        82:    %courselogs %accesshash $processmarker $dumpcount 
1.200     www        83:    %coursedombuf %coursehombuf %courseresdatacache);
1.1       albertel   84: use IO::Socket;
1.31      www        85: use GDBM_File;
1.8       www        86: use Apache::Constants qw(:common :http);
1.71      www        87: use HTML::TokeParser;
1.88      www        88: use Fcntl qw(:flock);
1.195     www        89: my $readit;
1.1       albertel   90: 
                     91: # --------------------------------------------------------------------- Logging
                     92: 
1.163     harris41   93: sub logtouch {
                     94:     my $execdir=$perlvar{'lonDaemons'};
                     95:     unless (-e "$execdir/logs/lonnet.log") {
                     96: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                     97: 	close $fh;
                     98:     }
                     99:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    100:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    101: }
                    102: 
1.1       albertel  103: sub logthis {
                    104:     my $message=shift;
                    105:     my $execdir=$perlvar{'lonDaemons'};
                    106:     my $now=time;
                    107:     my $local=localtime($now);
1.162     harris41  108:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
                    109:     print $fh "$local ($$): $message\n";
1.1       albertel  110:     return 1;
                    111: }
                    112: 
                    113: sub logperm {
                    114:     my $message=shift;
                    115:     my $execdir=$perlvar{'lonDaemons'};
                    116:     my $now=time;
                    117:     my $local=localtime($now);
1.162     harris41  118:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
                    119:     print $fh "$now:$message:$local\n";
1.1       albertel  120:     return 1;
                    121: }
                    122: 
                    123: # -------------------------------------------------- Non-critical communication
                    124: sub subreply {
                    125:     my ($cmd,$server)=@_;
                    126:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    127:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    128:                                      Type    => SOCK_STREAM,
                    129:                                      Timeout => 10)
                    130:        or return "con_lost";
                    131:     print $client "$cmd\n";
                    132:     my $answer=<$client>;
1.9       www       133:     if (!$answer) { $answer="con_lost"; }
1.1       albertel  134:     chomp($answer);
                    135:     return $answer;
                    136: }
                    137: 
                    138: sub reply {
                    139:     my ($cmd,$server)=@_;
                    140:     my $answer=subreply($cmd,$server);
1.203     www       141:     if ($answer eq 'con_lost') {
                    142:        sleep 5; 
                    143:        $answer=subreply($cmd,$server);
                    144:        if ($answer eq 'con_lost') {
                    145: 	   &logthis("Second attempt con_lost on $server");
                    146:            my $peerfile="$perlvar{'lonSockDir'}/$server";
                    147:            my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    148:                                             Type    => SOCK_STREAM,
                    149:                                             Timeout => 10)
                    150:                       or return "con_lost";
                    151:            &logthis("Killing socket");
                    152:            print $client "close_connection_exit\n";
                    153:            sleep 5;
                    154:            $answer=subreply($cmd,$server);       
                    155:        }   
                    156:     }
1.65      www       157:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       158:        &logthis("<font color=blue>WARNING:".
                    159:                 " $cmd to $server returned $answer</font>");
                    160:     }
1.1       albertel  161:     return $answer;
                    162: }
                    163: 
                    164: # ----------------------------------------------------------- Send USR1 to lonc
                    165: 
                    166: sub reconlonc {
                    167:     my $peerfile=shift;
                    168:     &logthis("Trying to reconnect for $peerfile");
                    169:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                    170:     if (my $fh=Apache::File->new("$loncfile")) {
                    171: 	my $loncpid=<$fh>;
                    172:         chomp($loncpid);
                    173:         if (kill 0 => $loncpid) {
                    174: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    175:             kill USR1 => $loncpid;
                    176:             sleep 1;
                    177:             if (-e "$peerfile") { return; }
                    178:             &logthis("$peerfile still not there, give it another try");
                    179:             sleep 5;
                    180:             if (-e "$peerfile") { return; }
1.12      www       181:             &logthis(
                    182:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  183:         } else {
1.12      www       184: 	    &logthis(
                    185:                "<font color=blue>WARNING:".
                    186:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  187:         }
                    188:     } else {
1.12      www       189:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  190:     }
                    191: }
                    192: 
                    193: # ------------------------------------------------------ Critical communication
1.12      www       194: 
1.1       albertel  195: sub critical {
                    196:     my ($cmd,$server)=@_;
1.89      www       197:     unless ($hostname{$server}) {
                    198:         &logthis("<font color=blue>WARNING:".
                    199:                " Critical message to unknown server ($server)</font>");
                    200:         return 'no_such_host';
                    201:     }
1.1       albertel  202:     my $answer=reply($cmd,$server);
                    203:     if ($answer eq 'con_lost') {
                    204:         my $pingreply=reply('ping',$server);
                    205: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
                    206:         my $pongreply=reply('pong',$server);
                    207:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
                    208:         $answer=reply($cmd,$server);
                    209:         if ($answer eq 'con_lost') {
                    210:             my $now=time;
                    211:             my $middlename=$cmd;
1.5       www       212:             $middlename=substr($middlename,0,16);
1.1       albertel  213:             $middlename=~s/\W//g;
                    214:             my $dfilename=
                    215:              "$perlvar{'lonSockDir'}/delayed/$now.$middlename.$server";
                    216:             {
                    217:              my $dfh;
                    218:              if ($dfh=Apache::File->new(">$dfilename")) {
1.7       www       219:                 print $dfh "$cmd\n";
1.1       albertel  220: 	     }
                    221:             }
                    222:             sleep 2;
                    223:             my $wcmd='';
                    224:             {
                    225: 	     my $dfh;
                    226:              if ($dfh=Apache::File->new("$dfilename")) {
                    227:                 $wcmd=<$dfh>;
                    228: 	     }
                    229:             }
                    230:             chomp($wcmd);
1.7       www       231:             if ($wcmd eq $cmd) {
1.12      www       232: 		&logthis("<font color=blue>WARNING: ".
                    233:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  234:                 &logperm("D:$server:$cmd");
                    235: 	        return 'con_delayed';
                    236:             } else {
1.12      www       237:                 &logthis("<font color=red>CRITICAL:"
                    238:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  239:                 &logperm("F:$server:$cmd");
                    240:                 return 'con_failed';
                    241:             }
                    242:         }
                    243:     }
                    244:     return $answer;
                    245: }
                    246: 
1.5       www       247: # ---------------------------------------------------------- Append Environment
                    248: 
                    249: sub appenv {
1.6       www       250:     my %newenv=@_;
1.191     harris41  251:     foreach (keys %newenv) {
1.35      www       252: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    253:             &logthis("<font color=blue>WARNING: ".
1.151     www       254:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    255:                 .'</font>');
1.35      www       256: 	    delete($newenv{$_});
                    257:         } else {
                    258:             $ENV{$_}=$newenv{$_};
                    259:         }
1.191     harris41  260:     }
1.95      www       261: 
                    262:     my $lockfh;
                    263:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       264:        return 'error: '.$!;
1.95      www       265:     }
                    266:     unless (flock($lockfh,LOCK_EX)) {
                    267:          &logthis("<font color=blue>WARNING: ".
                    268:                   'Could not obtain exclusive lock in appenv: '.$!);
                    269:          $lockfh->close();
                    270:          return 'error: '.$!;
                    271:     }
                    272: 
1.6       www       273:     my @oldenv;
                    274:     {
                    275:      my $fh;
                    276:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       277: 	return 'error: '.$!;
1.6       www       278:      }
                    279:      @oldenv=<$fh>;
1.89      www       280:      $fh->close();
1.6       www       281:     }
                    282:     for (my $i=0; $i<=$#oldenv; $i++) {
                    283:         chomp($oldenv[$i]);
1.9       www       284:         if ($oldenv[$i] ne '') {
                    285:            my ($name,$value)=split(/=/,$oldenv[$i]);
1.24      www       286:            unless (defined($newenv{$name})) {
                    287: 	      $newenv{$name}=$value;
                    288: 	   }
1.9       www       289:         }
1.6       www       290:     }
                    291:     {
                    292:      my $fh;
                    293:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    294: 	return 'error';
                    295:      }
                    296:      my $newname;
1.93      www       297:      foreach $newname (keys %newenv) {
1.6       www       298: 	 print $fh "$newname=$newenv{$newname}\n";
                    299:      }
1.86      albertel  300:      $fh->close();
1.56      www       301:     }
1.95      www       302: 
                    303:     $lockfh->close();
1.56      www       304:     return 'ok';
                    305: }
                    306: # ----------------------------------------------------- Delete from Environment
                    307: 
                    308: sub delenv {
                    309:     my $delthis=shift;
                    310:     my %newenv=();
                    311:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    312:         &logthis("<font color=blue>WARNING: ".
                    313:                 "Attempt to delete from environment ".$delthis);
                    314:         return 'error';
                    315:     }
                    316:     my @oldenv;
                    317:     {
                    318:      my $fh;
                    319:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
                    320: 	return 'error';
                    321:      }
1.89      www       322:      unless (flock($fh,LOCK_SH)) {
                    323:          &logthis("<font color=blue>WARNING: ".
                    324:                   'Could not obtain shared lock in delenv: '.$!);
                    325:          $fh->close();
                    326:          return 'error: '.$!;
                    327:      }
1.56      www       328:      @oldenv=<$fh>;
1.89      www       329:      $fh->close();
1.56      www       330:     }
                    331:     {
                    332:      my $fh;
                    333:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    334: 	return 'error';
                    335:      }
1.89      www       336:      unless (flock($fh,LOCK_EX)) {
                    337:          &logthis("<font color=blue>WARNING: ".
                    338:                   'Could not obtain exclusive lock in delenv: '.$!);
                    339:          $fh->close();
                    340:          return 'error: '.$!;
                    341:      }
1.191     harris41  342:      foreach (@oldenv) {
1.56      www       343: 	 unless ($_=~/^$delthis/) { print $fh $_; }
1.191     harris41  344:      }
1.87      www       345:      $fh->close();
1.5       www       346:     }
                    347:     return 'ok';
                    348: }
1.1       albertel  349: 
                    350: # ------------------------------ Find server with least workload from spare.tab
1.11      www       351: 
1.1       albertel  352: sub spareserver {
                    353:     my $tryserver;
                    354:     my $spareserver='';
                    355:     my $lowestserver=100;
                    356:     foreach $tryserver (keys %spareid) {
                    357:        my $answer=reply('load',$tryserver);
                    358:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    359: 	   $spareserver="http://$hostname{$tryserver}";
                    360:            $lowestserver=$answer;
                    361:        }
                    362:     }    
                    363:     return $spareserver;
1.202     matthew   364: }
                    365: 
                    366: # --------------------------------------------- Try to change a user's password
                    367: 
                    368: sub changepass {
                    369:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    370:     $currentpass = &escape($currentpass);
                    371:     $newpass     = &escape($newpass);
                    372:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    373: 		       $server);
                    374:     if (! $answer) {
                    375: 	&logthis("No reply on password change request to $server ".
                    376: 		 "by $uname in domain $udom.");
                    377:     } elsif ($answer =~ "^ok") {
                    378:         &logthis("$uname in $udom successfully changed their password ".
                    379: 		 "on $server.");
                    380:     } elsif ($answer =~ "^pwchange_failure") {
                    381: 	&logthis("$uname in $udom was unable to change their password ".
                    382: 		 "on $server.  The action was blocked by either lcpasswd ".
                    383: 		 "or pwchange");
                    384:     } elsif ($answer =~ "^non_authorized") {
                    385:         &logthis("$uname in $udom did not get their password correct when ".
                    386: 		 "attempting to change it on $server.");
                    387:     } elsif ($answer =~ "^auth_mode_error") {
                    388:         &logthis("$uname in $udom attempted to change their password despite ".
                    389: 		 "not being locally or internally authenticated on $server.");
                    390:     } elsif ($answer =~ "^unknown_user") {
                    391:         &logthis("$uname in $udom attempted to change their password ".
                    392: 		 "on $server but were unable to because $server is not ".
                    393: 		 "their home server.");
                    394:     } elsif ($answer =~ "^refused") {
                    395: 	&logthis("$server refused to change $uname in $udom password because ".
                    396: 		 "it was sent an unencrypted request to change the password.");
                    397:     }
                    398:     return $answer;
1.1       albertel  399: }
                    400: 
1.169     harris41  401: # ----------------------- Try to determine user's current authentication scheme
                    402: 
                    403: sub queryauthenticate {
                    404:     my ($uname,$udom)=@_;
                    405:     if (($perlvar{'lonRole'} eq 'library') && 
                    406:         ($udom eq $perlvar{'lonDefDomain'})) {
                    407: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    408: 			 $perlvar{'lonHostID'});
                    409: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    410: 	    if (length($answer)) {
                    411: 		return $answer;
                    412: 	    }
                    413: 	    else {
                    414: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    415: 		return 'no_host';
                    416: 	    }
                    417: 	}
                    418:     }
                    419: 
                    420:     my $tryserver;
                    421:     foreach $tryserver (keys %libserv) {
                    422: 	if ($hostdom{$tryserver} eq $udom) {
                    423:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    424: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    425: 	       if (length($answer)) {
                    426: 		   return $answer;
                    427: 	       }
                    428: 	       else {
                    429: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    430: 		   return 'no_host';
                    431: 	       }
                    432: 	   }
                    433:        }
                    434:     }
                    435:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    436:     return 'no_host';
                    437: }
                    438: 
1.1       albertel  439: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       440: 
1.1       albertel  441: sub authenticate {
                    442:     my ($uname,$upass,$udom)=@_;
1.12      www       443:     $upass=escape($upass);
1.199     www       444:     $uname=~s/\W//g;
1.1       albertel  445:     if (($perlvar{'lonRole'} eq 'library') && 
                    446:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       447:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       448:         if ($answer =~ /authorized/) {
1.9       www       449:               if ($answer eq 'authorized') {
                    450:                  &logthis("User $uname at $udom authorized by local server"); 
                    451:                  return $perlvar{'lonHostID'}; 
                    452:               }
                    453:               if ($answer eq 'non_authorized') {
                    454:                  &logthis("User $uname at $udom rejected by local server"); 
                    455:                  return 'no_host'; 
                    456:               }
1.2       www       457: 	}
1.1       albertel  458:     }
                    459: 
                    460:     my $tryserver;
                    461:     foreach $tryserver (keys %libserv) {
                    462: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       463:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  464:            if ($answer =~ /authorized/) {
1.9       www       465:               if ($answer eq 'authorized') {
                    466:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    467:                  return $tryserver; 
                    468:               }
                    469:               if ($answer eq 'non_authorized') {
                    470:                  &logthis("User $uname at $udom rejected by $tryserver");
                    471:                  return 'no_host';
                    472:               } 
1.1       albertel  473: 	   }
                    474:        }
1.9       www       475:     }
                    476:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  477:     return 'no_host';
                    478: }
                    479: 
                    480: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       481: 
1.1       albertel  482: sub homeserver {
                    483:     my ($uname,$udom)=@_;
                    484: 
                    485:     my $index="$uname:$udom";
                    486:     if ($homecache{$index}) { return "$homecache{$index}"; }
                    487: 
                    488:     my $tryserver;
                    489:     foreach $tryserver (keys %libserv) {
                    490: 	if ($hostdom{$tryserver} eq $udom) {
                    491:            my $answer=reply("home:$udom:$uname",$tryserver);
                    492:            if ($answer eq 'found') { 
                    493: 	      $homecache{$index}=$tryserver;
                    494:               return $tryserver; 
                    495: 	   }
                    496:        }
                    497:     }    
                    498:     return 'no_host';
1.70      www       499: }
                    500: 
                    501: # ------------------------------------- Find the usernames behind a list of IDs
                    502: 
                    503: sub idget {
                    504:     my ($udom,@ids)=@_;
                    505:     my %returnhash=();
                    506:     
                    507:     my $tryserver;
                    508:     foreach $tryserver (keys %libserv) {
                    509:        if ($hostdom{$tryserver} eq $udom) {
                    510: 	  my $idlist=join('&',@ids);
                    511:           $idlist=~tr/A-Z/a-z/; 
                    512: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    513:           my @answer=();
1.76      www       514:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       515: 	      @answer=split(/\&/,$reply);
                    516:           }                    ;
                    517:           my $i;
                    518:           for ($i=0;$i<=$#ids;$i++) {
                    519:               if ($answer[$i]) {
                    520: 		  $returnhash{$ids[$i]}=$answer[$i];
                    521:               } 
                    522:           }
                    523:        }
                    524:     }    
                    525:     return %returnhash;
                    526: }
                    527: 
                    528: # ------------------------------------- Find the IDs behind a list of usernames
                    529: 
                    530: sub idrget {
                    531:     my ($udom,@unames)=@_;
                    532:     my %returnhash=();
1.191     harris41  533:     foreach (@unames) {
1.70      www       534:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  535:     }
1.70      www       536:     return %returnhash;
                    537: }
                    538: 
                    539: # ------------------------------- Store away a list of names and associated IDs
                    540: 
                    541: sub idput {
                    542:     my ($udom,%ids)=@_;
                    543:     my %servers=();
1.191     harris41  544:     foreach (keys %ids) {
1.70      www       545:         my $uhom=&homeserver($_,$udom);
                    546:         if ($uhom ne 'no_host') {
                    547:             my $id=&escape($ids{$_});
                    548:             $id=~tr/A-Z/a-z/;
                    549:             my $unam=&escape($_);
                    550: 	    if ($servers{$uhom}) {
                    551: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    552:             } else {
                    553:                 $servers{$uhom}=$id.'='.$unam;
                    554:             }
                    555:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    556:         }
1.191     harris41  557:     }
                    558:     foreach (keys %servers) {
1.70      www       559:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  560:     }
1.70      www       561: }
                    562: 
                    563: # ------------------------------------- Find the section of student in a course
                    564: 
                    565: sub usection {
                    566:     my ($udom,$unam,$courseid)=@_;
                    567:     $courseid=~s/\_/\//g;
                    568:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  569:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    570:                         &homeserver($unam,$udom)))) {
1.70      www       571:         my ($key,$value)=split(/\=/,$_);
                    572:         $key=&unescape($key);
                    573:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                    574:             my $section=$1;
                    575:             if ($key eq $courseid.'_st') { $section=''; }
                    576: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    577:             my $now=time;
                    578:             my $notactive=0;
                    579:             if ($start) {
                    580: 		if ($now<$start) { $notactive=1; }
                    581:             }
                    582:             if ($end) {
                    583:                 if ($now>$end) { $notactive=1; }
                    584:             } 
                    585:             unless ($notactive) { return $section; }
                    586:         }
1.191     harris41  587:     }
1.70      www       588:     return '-1';
                    589: }
                    590: 
                    591: # ------------------------------------- Read an entry from a user's environment
                    592: 
                    593: sub userenvironment {
                    594:     my ($udom,$unam,@what)=@_;
                    595:     my %returnhash=();
                    596:     my @answer=split(/\&/,
                    597:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    598:                       &homeserver($unam,$udom)));
                    599:     my $i;
                    600:     for ($i=0;$i<=$#what;$i++) {
                    601: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    602:     }
                    603:     return %returnhash;
1.1       albertel  604: }
                    605: 
                    606: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       607: 
1.1       albertel  608: sub subscribe {
                    609:     my $fname=shift;
                    610:     my $author=$fname;
                    611:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    612:     my ($udom,$uname)=split(/\//,$author);
                    613:     my $home=homeserver($uname,$udom);
                    614:     if (($home eq 'no_host') || ($home eq $perlvar{'lonHostID'})) { 
                    615:         return 'not_found'; 
                    616:     }
                    617:     my $answer=reply("sub:$fname",$home);
1.64      www       618:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    619: 	$answer.=' by '.$home;
                    620:     }
1.1       albertel  621:     return $answer;
                    622: }
                    623:     
1.8       www       624: # -------------------------------------------------------------- Replicate file
                    625: 
                    626: sub repcopy {
                    627:     my $filename=shift;
1.23      www       628:     $filename=~s/\/+/\//g;
1.8       www       629:     my $transname="$filename.in.transfer";
1.17      www       630:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www       631:     my $remoteurl=subscribe($filename);
1.64      www       632:     if ($remoteurl =~ /^con_lost by/) {
                    633: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       634:            return HTTP_SERVICE_UNAVAILABLE;
                    635:     } elsif ($remoteurl eq 'not_found') {
                    636: 	   &logthis("Subscribe returned not_found: $filename");
                    637: 	   return HTTP_NOT_FOUND;
1.64      www       638:     } elsif ($remoteurl =~ /^rejected by/) {
                    639: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       640:            return FORBIDDEN;
1.20      www       641:     } elsif ($remoteurl eq 'directory') {
                    642:            return OK;
1.8       www       643:     } else {
                    644:            my @parts=split(/\//,$filename);
                    645:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                    646:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                    647:                &logthis("Malconfiguration for replication: $filename");
                    648: 	       return HTTP_BAD_REQUEST;
                    649:            }
                    650:            my $count;
                    651:            for ($count=5;$count<$#parts;$count++) {
                    652:                $path.="/$parts[$count]";
                    653:                if ((-e $path)!=1) {
                    654: 		   mkdir($path,0777);
                    655:                }
                    656:            }
                    657:            my $ua=new LWP::UserAgent;
                    658:            my $request=new HTTP::Request('GET',"$remoteurl");
                    659:            my $response=$ua->request($request,$transname);
                    660:            if ($response->is_error()) {
                    661: 	       unlink($transname);
                    662:                my $message=$response->status_line;
1.12      www       663:                &logthis("<font color=blue>WARNING:"
                    664:                        ." LWP get: $message: $filename</font>");
1.8       www       665:                return HTTP_SERVICE_UNAVAILABLE;
                    666:            } else {
1.16      www       667: 	       if ($remoteurl!~/\.meta$/) {
                    668:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                    669:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                    670:                   if ($mresponse->is_error()) {
                    671: 		      unlink($filename.'.meta');
                    672:                       &logthis(
                    673:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                    674:                   }
                    675: 	       }
1.8       www       676:                rename($transname,$filename);
                    677:                return OK;
                    678:            }
                    679:     }
                    680: }
                    681: 
1.15      www       682: # --------------------------------------------------------- Server Side Include
                    683: 
                    684: sub ssi {
                    685: 
1.23      www       686:     my ($fn,%form)=@_;
1.15      www       687: 
                    688:     my $ua=new LWP::UserAgent;
1.23      www       689:     
                    690:     my $request;
                    691:     
                    692:     if (%form) {
                    693:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel  694:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www       695:     } else {
                    696:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                    697:     }
                    698: 
1.15      www       699:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                    700:     my $response=$ua->request($request);
                    701: 
                    702:     return $response->content;
                    703: }
                    704: 
1.14      www       705: # ------------------------------------------------------------------------- Log
                    706: 
                    707: sub log {
                    708:     my ($dom,$nam,$hom,$what)=@_;
1.47      www       709:     return critical("log:$dom:$nam:$what",$hom);
1.157     www       710: }
                    711: 
                    712: # ------------------------------------------------------------------ Course Log
                    713: 
                    714: sub flushcourselogs {
                    715:     &logthis('Flushing course log buffers');
1.191     harris41  716:     foreach (keys %courselogs) {
1.157     www       717:         my $crsid=$_;
1.204   ! albertel  718: 	&logthis(":$crsid:$coursehombuf{$crsid}");
1.188     www       719:         if (&reply('log:'.$coursedombuf{$crsid}.':'.
                    720: 		          &escape($courselogs{$crsid}),
                    721: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www       722: 	    delete $courselogs{$crsid};
                    723:         } else {
                    724:             &logthis('Failed to flush log buffer for '.$crsid);
                    725:             if (length($courselogs{$crsid})>40000) {
                    726:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                    727:                         " exceeded maximum size, deleting.</font>");
                    728:                delete $courselogs{$crsid};
                    729:             }
                    730:         }        
1.191     harris41  731:     }
1.185     www       732:     &logthis('Flushing access logs');
1.191     harris41  733:     foreach (keys %accesshash) {
1.185     www       734:         my $entry=$_;
                    735:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
                    736:         my %temphash=($entry => $accesshash{$entry});
                    737:         if (&Apache::lonnet::put('resevaldata',\%temphash,$1,$2) eq 'ok') {
                    738: 	    delete $accesshash{$entry};
                    739:         }
1.191     harris41  740:     }
1.186     www       741:     $dumpcount++;
1.157     www       742: }
                    743: 
                    744: sub courselog {
                    745:     my $what=shift;
1.158     www       746:     $what=time.':'.$what;
1.157     www       747:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www       748:     $coursedombuf{$ENV{'request.course.id'}}=
                    749:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.
                    750:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    751:     $coursehombuf{$ENV{'request.course.id'}}=
                    752:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.157     www       753:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                    754: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                    755:     } else {
                    756: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                    757:     }
                    758:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                    759: 	&flushcourselogs();
                    760:     }
1.158     www       761: }
                    762: 
                    763: sub courseacclog {
                    764:     my $fnsymb=shift;
                    765:     unless ($ENV{'request.course.id'}) { return ''; }
                    766:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.192     www       767:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
1.187     www       768:         $what.=':POST';
1.191     harris41  769: 	foreach (keys %ENV) {
1.158     www       770:             if ($_=~/^form\.(.*)/) {
                    771: 		$what.=':'.$1.'='.$ENV{$_};
                    772:             }
1.191     harris41  773:         }
1.158     www       774:     }
                    775:     &courselog($what);
1.149     www       776: }
                    777: 
1.185     www       778: sub countacc {
                    779:     my $url=&declutter(shift);
                    780:     unless ($ENV{'request.course.id'}) { return ''; }
                    781:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.186     www       782:     my $key=$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.185     www       783:     if (defined($accesshash{$key})) {
                    784: 	$accesshash{$key}++;
                    785:     } else {
                    786:         $accesshash{$key}=1;
                    787:     }
                    788: }
                    789:     
1.149     www       790: # ----------------------------------------------------------- Check out an item
                    791: 
                    792: sub checkout {
                    793:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                    794:     my $now=time;
                    795:     my $lonhost=$perlvar{'lonHostID'};
                    796:     my $infostr=&escape(
                    797:                  $tuname.'&'.
                    798:                  $tudom.'&'.
                    799:                  $tcrsid.'&'.
                    800:                  $symb.'&'.
                    801: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                    802:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www       803:     if ($token=~/^error\:/) { 
                    804:         &logthis("<font color=blue>WARNING: ".
                    805:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                    806:                  "</font>");
                    807:         return ''; 
                    808:     }
                    809: 
1.149     www       810:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                    811:     $token=~tr/a-z/A-Z/;
                    812: 
1.153     www       813:     my %infohash=('resource.0.outtoken' => $token,
                    814:                   'resource.0.checkouttime' => $now,
                    815:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www       816: 
                    817:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                    818:        return '';
1.151     www       819:     } else {
                    820:         &logthis("<font color=blue>WARNING: ".
                    821:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                    822:                  "</font>");
1.149     www       823:     }    
                    824: 
                    825:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                    826:                          &escape('Checkout '.$infostr.' - '.
                    827:                                                  $token)) ne 'ok') {
                    828: 	return '';
1.151     www       829:     } else {
                    830:         &logthis("<font color=blue>WARNING: ".
                    831:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                    832:                  "</font>");
1.149     www       833:     }
1.151     www       834:     return $token;
1.149     www       835: }
                    836: 
                    837: # ------------------------------------------------------------ Check in an item
                    838: 
                    839: sub checkin {
                    840:     my $token=shift;
1.150     www       841:     my $now=time;
                    842:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                    843:     $lonhost=~tr/A-Z/a-z/;
                    844:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                    845:     $dtoken=~s/\W/\_/g;
                    846:     my ($tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                    847:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                    848: 
1.154     www       849:     unless (($tuname) && ($tudom)) {
                    850:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                    851:         return '';
                    852:     }
                    853:     
                    854:     unless (&allowed('mgr',$tcrsid)) {
                    855:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                    856:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                    857:         return '';
                    858:     }
                    859: 
1.153     www       860:     my %infohash=('resource.0.intoken' => $token,
                    861:                   'resource.0.checkintime' => $now,
                    862:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www       863: 
                    864:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                    865:        return '';
                    866:     }    
                    867: 
                    868:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                    869:                          &escape('Checkin - '.$token)) ne 'ok') {
                    870: 	return '';
                    871:     }
                    872: 
                    873:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www       874: }
                    875: 
                    876: # --------------------------------------------- Set Expire Date for Spreadsheet
                    877: 
                    878: sub expirespread {
                    879:     my ($uname,$udom,$stype,$usymb)=@_;
                    880:     my $cid=$ENV{'request.course.id'}; 
                    881:     if ($cid) {
                    882:        my $now=time;
                    883:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                    884:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                    885:                             $ENV{'course.'.$cid.'.num'}.
                    886: 	        	    ':nohist_expirationdates:'.
                    887:                             &escape($key).'='.$now,
                    888:                             $ENV{'course.'.$cid.'.home'})
                    889:     }
                    890:     return 'ok';
1.14      www       891: }
                    892: 
1.109     www       893: # ----------------------------------------------------- Devalidate Spreadsheets
                    894: 
                    895: sub devalidate {
                    896:     my $symb=shift;
                    897:     my $cid=$ENV{'request.course.id'}; 
                    898:     if ($cid) {
                    899: 	my $key=$ENV{'user.name'}.':'.$ENV{'user.domain'}.':';
                    900:         my $status=
1.133     albertel  901: 	    &del('nohist_calculatedsheet',
                    902: 		 [$key.'studentcalc'],
                    903: 		 $ENV{'course.'.$cid.'.domain'},
                    904: 		 $ENV{'course.'.$cid.'.num'})
                    905: 		.' '.
                    906: 	    &del('nohist_calculatedsheets_'.$cid,
                    907: 		 [$key.'assesscalc:'.$symb]);
1.109     www       908:         unless ($status eq 'ok ok') {
                    909:            &logthis('Could not devalidate spreadsheet '.
                    910:                     $ENV{'user.name'}.' at '.$ENV{'user.domain'}.' for '.
                    911: 		    $symb.': '.$status);
1.133     albertel  912:         }
1.109     www       913:     }
                    914: }
                    915: 
1.204   ! albertel  916: sub arrayref2str {
        !           917:   my ($arrayref) = @_;
        !           918:   my $result='_ARRAY_REF__';
        !           919:   foreach my $elem (@$arrayref) {
        !           920:     if (ref($elem) eq 'ARRAY') {
        !           921:       $result.=&escape(&arrayref2str($elem)).'&';
        !           922:     } elsif (ref($elem) eq 'HASH') {
        !           923:       $result.=&escape(&hashref2str($elem)).'&';
        !           924:     } elsif (ref($elem)) {
        !           925:       &logthis("Got a ref of ".(ref($elem))." skipping.");
        !           926:     } else {
        !           927:       $result.=&escape($elem).'&';
        !           928:     }
        !           929:   }
        !           930:   $result=~s/\&$//;
        !           931:   return $result;
        !           932: }
        !           933: 
1.168     albertel  934: sub hash2str {
1.204   ! albertel  935:   my (%hash) = @_;
        !           936:   my $result=&hashref2str(\%hash);
        !           937:   $result=~s/^_HASH_REF__//;
        !           938:   return $result;
        !           939: }
        !           940: 
        !           941: sub hashref2str {
        !           942:   my ($hashref)=@_;
        !           943:   my $result='_HASH_REF__';
        !           944:   foreach (keys(%$hashref)) {
        !           945:     if (ref($_) eq 'ARRAY') {
        !           946:       $result.=&escape(&arrayref2str($_)).'=';
        !           947:     } elsif (ref($_) eq 'HASH') {
        !           948:       $result.=&escape(&hashref2str($_)).'=';
        !           949:     } elsif (ref($_)) {
        !           950:       &logthis("Got a ref of ".(ref($_))." skipping.");
        !           951:     } else {
        !           952:       $result.=&escape($_).'=';
        !           953:     }
        !           954: 
        !           955:     if (ref($$hashref{$_}) eq 'ARRAY') {
        !           956:       $result.=&escape(&arrayref2str($$hashref{$_})).'&';
        !           957:     } elsif (ref($$hashref{$_}) eq 'HASH') {
        !           958:       $result.=&escape(&hashref2str($$hashref{$_})).'&';
        !           959:     } elsif (ref($$hashref{$_})) {
        !           960:       &logthis("Got a ref of ".(ref($$hashref{$_}))." skipping.");
        !           961:     } else {
        !           962:       $result.=&escape($$hashref{$_}).'&';
        !           963:     }
        !           964:   }
1.168     albertel  965:   $result=~s/\&$//;
                    966:   return $result;
                    967: }
                    968: 
                    969: sub str2hash {
                    970:   my ($string) = @_;
                    971:   my %returnhash;
1.191     harris41  972:   foreach (split(/\&/,$string)) {
1.168     albertel  973:     my ($name,$value)=split(/\=/,$_);
1.204   ! albertel  974:     $name=&unescape($name);
        !           975:     $value=&unescape($value);
        !           976:     if ($value =~ /^_HASH_REF__/) {
        !           977:       $value =~ s/^_HASH_REF__//;
        !           978:       my %hash=&str2hash($value);
        !           979:       $value=\%hash;
        !           980:     } elsif ($value =~ /^_ARRAY_REF__/) {
        !           981:       $value =~ s/^_ARRAY_REF__//;
        !           982:       my @array=&str2array($value);
        !           983:       $value=\@array;
        !           984:     }
        !           985:     $returnhash{$name}=$value;
        !           986:   }
        !           987:   return (%returnhash);
        !           988: }
        !           989: 
        !           990: sub str2array {
        !           991:   my ($string) = @_;
        !           992:   my @returnarray;
        !           993:   foreach my $value (split(/\&/,$string)) {
        !           994:     $value=&unescape($value);
        !           995:     if ($value =~ /^_HASH_REF__/) {
        !           996:       $value =~ s/^_HASH_REF__//;
        !           997:       my %hash=&str2hash($value);
        !           998:       $value=\%hash;
        !           999:     } elsif ($value =~ /^_ARRAY_REF__/) {
        !          1000:       $value =~ s/^_ARRAY_REF__//;
        !          1001:       my @array=&str2array($value);
        !          1002:       $value=\@array;
        !          1003:     }
        !          1004:     push(@returnarray,$value);
1.191     harris41 1005:   }
1.204   ! albertel 1006:   return (@returnarray);
1.168     albertel 1007: }
                   1008: 
1.167     albertel 1009: # -------------------------------------------------------------------Temp Store
                   1010: 
1.168     albertel 1011: sub tmpreset {
                   1012:   my ($symb,$namespace,$domain,$stuname) = @_;
                   1013:   if (!$symb) {
                   1014:     $symb=&symbread();
                   1015:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
                   1016:   }
                   1017:   $symb=escape($symb);
                   1018: 
                   1019:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1020:   $namespace=~s/\//\_/g;
                   1021:   $namespace=~s/\W//g;
                   1022: 
                   1023:   #FIXME needs to do something for /pub resources
                   1024:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1025:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1026:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1027:   my %hash;
                   1028:   if (tie(%hash,'GDBM_File',
                   1029: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
                   1030: 	  &GDBM_WRCREAT,0640)) {
                   1031:     foreach my $key (keys %hash) {
1.180     albertel 1032:       if ($key=~ /:$symb/) {
1.168     albertel 1033: 	delete($hash{$key});
                   1034:       }
                   1035:     }
                   1036:   }
                   1037: }
                   1038: 
1.167     albertel 1039: sub tmpstore {
1.168     albertel 1040:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1041: 
                   1042:   if (!$symb) {
                   1043:     $symb=&symbread();
                   1044:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1045:   }
                   1046:   $symb=escape($symb);
                   1047: 
                   1048:   if (!$namespace) {
                   1049:     # I don't think we would ever want to store this for a course.
                   1050:     # it seems this will only be used if we don't have a course.
                   1051:     #$namespace=$ENV{'request.course.id'};
                   1052:     #if (!$namespace) {
                   1053:       $namespace=$ENV{'request.state'};
                   1054:     #}
                   1055:   }
                   1056:   $namespace=~s/\//\_/g;
                   1057:   $namespace=~s/\W//g;
                   1058: #FIXME needs to do something for /pub resources
                   1059:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1060:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1061:   my $now=time;
                   1062:   my %hash;
                   1063:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1064:   if (tie(%hash,'GDBM_File',
                   1065: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
                   1066: 	  &GDBM_WRCREAT,0640)) {
                   1067:     $hash{"version:$symb"}++;
                   1068:     my $version=$hash{"version:$symb"};
                   1069:     my $allkeys=''; 
                   1070:     foreach my $key (keys(%$storehash)) {
                   1071:       $allkeys.=$key.':';
                   1072:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                   1073:     }
                   1074:     $hash{"$version:$symb:timestamp"}=$now;
                   1075:     $allkeys.='timestamp';
                   1076:     $hash{"$version:keys:$symb"}=$allkeys;
                   1077:     if (untie(%hash)) {
                   1078:       return 'ok';
                   1079:     } else {
                   1080:       return "error:$!";
                   1081:     }
                   1082:   } else {
                   1083:     return "error:$!";
                   1084:   }
                   1085: }
1.167     albertel 1086: 
1.168     albertel 1087: # -----------------------------------------------------------------Temp Restore
1.167     albertel 1088: 
1.168     albertel 1089: sub tmprestore {
                   1090:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 1091: 
1.168     albertel 1092:   if (!$symb) {
                   1093:     $symb=&symbread();
                   1094:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1095:   }
                   1096:   $symb=escape($symb);
                   1097: 
                   1098:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1099:   #FIXME needs to do something for /pub resources
                   1100:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1101:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1102: 
                   1103:   my %returnhash;
                   1104:   $namespace=~s/\//\_/g;
                   1105:   $namespace=~s/\W//g;
                   1106:   my %hash;
                   1107:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1108:   if (tie(%hash,'GDBM_File',
                   1109: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
                   1110: 	  &GDBM_READER,0640)) {
                   1111:     my $version=$hash{"version:$symb"};
                   1112:     $returnhash{'version'}=$version;
                   1113:     my $scope;
                   1114:     for ($scope=1;$scope<=$version;$scope++) {
                   1115:       my $vkeys=$hash{"$scope:keys:$symb"};
                   1116:       my @keys=split(/:/,$vkeys);
                   1117:       my $key;
                   1118:       $returnhash{"$scope:keys"}=$vkeys;
                   1119:       foreach $key (@keys) {
                   1120: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                   1121: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel 1122:       }
                   1123:     }
1.168     albertel 1124:     if (!(untie(%hash))) {
                   1125:       return "error:$!";
                   1126:     }
                   1127:   } else {
                   1128:     return "error:$!";
                   1129:   }
                   1130:   return %returnhash;
1.167     albertel 1131: }
                   1132: 
1.9       www      1133: # ----------------------------------------------------------------------- Store
                   1134: 
                   1135: sub store {
1.124     www      1136:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1137:     my $home='';
                   1138: 
1.168     albertel 1139:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1140: 
1.122     albertel 1141:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1142: 
                   1143:     &devalidate($symb);
                   1144: 
                   1145:     $symb=escape($symb);
1.187     www      1146:     if (!$namespace) { 
                   1147:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1148:           return ''; 
                   1149:        } 
                   1150:     }
1.122     albertel 1151:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1152:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1153:     if (!$home) { $home=$ENV{'user.home'}; }
1.12      www      1154:     my $namevalue='';
1.191     harris41 1155:     foreach (keys %$storehash) {
1.122     albertel 1156:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1157:     }
1.12      www      1158:     $namevalue=~s/\&$//;
1.187     www      1159:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      1160:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      1161: }
                   1162: 
1.47      www      1163: # -------------------------------------------------------------- Critical Store
                   1164: 
                   1165: sub cstore {
1.124     www      1166:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1167:     my $home='';
                   1168: 
1.168     albertel 1169:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1170: 
1.122     albertel 1171:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1172: 
                   1173:     &devalidate($symb);
                   1174: 
                   1175:     $symb=escape($symb);
1.187     www      1176:     if (!$namespace) { 
                   1177:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1178:           return ''; 
                   1179:        } 
                   1180:     }
1.122     albertel 1181:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1182:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1183:     if (!$home) { $home=$ENV{'user.home'}; }
                   1184: 
1.47      www      1185:     my $namevalue='';
1.191     harris41 1186:     foreach (keys %$storehash) {
1.122     albertel 1187:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1188:     }
1.47      www      1189:     $namevalue=~s/\&$//;
1.187     www      1190:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      1191:     return critical
                   1192:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      1193: }
                   1194: 
1.9       www      1195: # --------------------------------------------------------------------- Restore
                   1196: 
                   1197: sub restore {
1.124     www      1198:     my ($symb,$namespace,$domain,$stuname) = @_;
                   1199:     my $home='';
                   1200: 
1.168     albertel 1201:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1202: 
1.122     albertel 1203:     if (!$symb) {
                   1204:       unless ($symb=escape(&symbread())) { return ''; }
                   1205:     } else {
                   1206:       $symb=&escape($symb);
                   1207:     }
1.188     www      1208:     if (!$namespace) { 
                   1209:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1210:           return ''; 
                   1211:        } 
                   1212:     }
1.122     albertel 1213:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1214:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1215:     if (!$home) { $home=$ENV{'user.home'}; }
                   1216:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   1217: 
1.12      www      1218:     my %returnhash=();
1.191     harris41 1219:     foreach (split(/\&/,$answer)) {
1.12      www      1220: 	my ($name,$value)=split(/\=/,$_);
                   1221:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 1222:     }
1.75      www      1223:     my $version;
                   1224:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 1225:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      1226:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 1227:        }
1.75      www      1228:     }
1.13      www      1229:     return %returnhash;
1.34      www      1230: }
                   1231: 
                   1232: # ---------------------------------------------------------- Course Description
                   1233: 
                   1234: sub coursedescription {
                   1235:     my $courseid=shift;
                   1236:     $courseid=~s/^\///;
1.49      www      1237:     $courseid=~s/\_/\//g;
1.34      www      1238:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 1239:     my $chome=&homeserver($cnum,$cdomain);
1.34      www      1240:     if ($chome ne 'no_host') {
1.129     albertel 1241:        my %returnhash=&dump('environment',$cdomain,$cnum);
                   1242:        if (!exists($returnhash{'con_lost'})) {
1.96      www      1243:            my $normalid=$cdomain.'_'.$cnum;
1.53      www      1244:            my %envhash=();
1.129     albertel 1245:            $returnhash{'home'}= $chome;
                   1246: 	   $returnhash{'domain'} = $cdomain;
                   1247: 	   $returnhash{'num'} = $cnum;
1.130     albertel 1248:            while (my ($name,$value) = each %returnhash) {
1.53      www      1249:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 1250:            }
1.34      www      1251:            $returnhash{'url'}='/res/'.declutter($returnhash{'url'});
                   1252:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      1253: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.54      www      1254:            $envhash{'course.'.$normalid.'.last_cache'}=time;
1.60      www      1255:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   1256:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   1257:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.53      www      1258:            &appenv(%envhash);
1.34      www      1259:            return %returnhash;
                   1260:        }
                   1261:     }
                   1262:     return ();
1.9       www      1263: }
1.1       albertel 1264: 
1.103     harris41 1265: # -------------------------------------------------------- Get user privileges
1.11      www      1266: 
                   1267: sub rolesinit {
                   1268:     my ($domain,$username,$authhost)=@_;
                   1269:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      1270:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      1271:     my %allroles=();
                   1272:     my %thesepriv=();
                   1273:     my $now=time;
1.21      www      1274:     my $userroles="user.login.time=$now\n";
1.11      www      1275:     my $thesestr;
                   1276: 
                   1277:     if ($rolesdump ne '') {
1.191     harris41 1278:         foreach (split(/&/,$rolesdump)) {
1.21      www      1279: 	  if ($_!~/^rolesdef\&/) {
1.11      www      1280:             my ($area,$role)=split(/=/,$_);
1.21      www      1281:             $area=~s/\_\w\w$//;
1.11      www      1282:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      1283:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   1284:                         $tstart.'.'.$tend."\n";
1.11      www      1285:             if ($tend!=0) {
                   1286: 	        if ($tend<$now) {
                   1287: 	            $trole='';
                   1288:                 } 
                   1289:             }
                   1290:             if ($tstart!=0) {
                   1291:                 if ($tstart>$now) {
                   1292:                    $trole='';        
                   1293:                 }
                   1294:             }
                   1295:             if (($area ne '') && ($trole ne '')) {
1.50      www      1296: 	       my $spec=$trole.'.'.$area;
1.12      www      1297:                my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   1298:                if ($trole =~ /^cr\//) {
                   1299: 		   my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   1300:                    my $homsvr=homeserver($rauthor,$rdomain);
                   1301:                    if ($hostname{$homsvr} ne '') {
                   1302:                       my $roledef=
1.21      www      1303: 			  reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
1.12      www      1304:                                 $homsvr);
                   1305:                       if (($roledef ne 'con_lost') && ($roledef ne '')) {
                   1306:                          my ($syspriv,$dompriv,$coursepriv)=
1.21      www      1307: 			     split(/\_/,unescape($roledef));
1.50      www      1308:  	                 $allroles{'cm./'}.=':'.$syspriv;
                   1309:                          $allroles{$spec.'./'}.=':'.$syspriv;
1.12      www      1310:                          if ($tdomain ne '') {
1.50      www      1311:                              $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   1312:                              $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
1.12      www      1313:                              if ($trest ne '') {
1.50      www      1314: 		                $allroles{'cm.'.$area}.=':'.$coursepriv;
                   1315: 		                $allroles{$spec.'.'.$area}.=':'.$coursepriv;
1.12      www      1316:                              }
                   1317: 	                 }
                   1318:                       }
1.11      www      1319:                    }
1.12      www      1320:                } else {
1.50      www      1321: 	           $allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   1322: 	           $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
1.12      www      1323:                    if ($tdomain ne '') {
1.50      www      1324:                      $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   1325:                      $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
1.12      www      1326:                       if ($trest ne '') {
1.50      www      1327: 		          $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   1328: 		          $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
1.12      www      1329:                       }
                   1330: 	           }
1.11      www      1331: 	       }
1.12      www      1332:             }
                   1333:           } 
1.191     harris41 1334:         }
1.125     www      1335:         my $adv=0;
1.128     www      1336:         my $author=0;
1.191     harris41 1337:         foreach (keys %allroles) {
1.11      www      1338:             %thesepriv=();
1.146     www      1339:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      1340:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 1341:             foreach (split(/:/,$allroles{$_})) {
1.11      www      1342:                 if ($_ ne '') {
1.103     harris41 1343: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      1344:                     if ($restrictions eq '') {
1.103     harris41 1345: 			$thesepriv{$privilege}='F';
1.11      www      1346:                     } else {
1.103     harris41 1347:                         if ($thesepriv{$privilege} ne 'F') {
                   1348: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      1349:                         }
                   1350:                     }
                   1351:                 }
1.191     harris41 1352:             }
1.11      www      1353:             $thesestr='';
1.191     harris41 1354:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      1355:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 1356:         }
1.128     www      1357:         $userroles.='user.adv='.$adv."\n".
                   1358: 	            'user.author='.$author."\n";
1.126     www      1359:         $ENV{'user.adv'}=$adv;
1.11      www      1360:     }
                   1361:     return $userroles;  
                   1362: }
                   1363: 
1.12      www      1364: # --------------------------------------------------------------- get interface
                   1365: 
                   1366: sub get {
1.131     albertel 1367:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1368:    my $items='';
1.191     harris41 1369:    foreach (@$storearr) {
1.12      www      1370:        $items.=escape($_).'&';
1.191     harris41 1371:    }
1.12      www      1372:    $items=~s/\&$//;
1.131     albertel 1373:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1374:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1375:    my $uhome=&homeserver($uname,$udomain);
                   1376: 
1.133     albertel 1377:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1378:    my @pairs=split(/\&/,$rep);
                   1379:    my %returnhash=();
1.42      www      1380:    my $i=0;
1.191     harris41 1381:    foreach (@$storearr) {
1.42      www      1382:       $returnhash{$_}=unescape($pairs[$i]);
                   1383:       $i++;
1.191     harris41 1384:    }
1.15      www      1385:    return %returnhash;
1.27      www      1386: }
                   1387: 
                   1388: # --------------------------------------------------------------- del interface
                   1389: 
                   1390: sub del {
1.133     albertel 1391:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      1392:    my $items='';
1.191     harris41 1393:    foreach (@$storearr) {
1.27      www      1394:        $items.=escape($_).'&';
1.191     harris41 1395:    }
1.27      www      1396:    $items=~s/\&$//;
1.133     albertel 1397:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1398:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1399:    my $uhome=&homeserver($uname,$udomain);
                   1400: 
                   1401:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      1402: }
                   1403: 
                   1404: # -------------------------------------------------------------- dump interface
                   1405: 
                   1406: sub dump {
1.193     www      1407:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 1408:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1409:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1410:    my $uhome=&homeserver($uname,$udomain);
1.193     www      1411:    if ($regexp) {
                   1412:        $regexp=&escape($regexp);
                   1413:    } else {
                   1414:        $regexp='.';
                   1415:    }
                   1416:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      1417:    my @pairs=split(/\&/,$rep);
                   1418:    my %returnhash=();
1.191     harris41 1419:    foreach (@pairs) {
1.12      www      1420:       my ($key,$value)=split(/=/,$_);
1.29      www      1421:       $returnhash{unescape($key)}=unescape($value);
1.191     harris41 1422:    }
1.12      www      1423:    return %returnhash;
                   1424: }
                   1425: 
                   1426: # --------------------------------------------------------------- put interface
                   1427: 
                   1428: sub put {
1.134     albertel 1429:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   1430:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1431:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1432:    my $uhome=&homeserver($uname,$udomain);
1.12      www      1433:    my $items='';
1.191     harris41 1434:    foreach (keys %$storehash) {
1.134     albertel 1435:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 1436:    }
1.12      www      1437:    $items=~s/\&$//;
1.134     albertel 1438:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      1439: }
                   1440: 
                   1441: # ------------------------------------------------------ critical put interface
                   1442: 
                   1443: sub cput {
1.134     albertel 1444:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   1445:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1446:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1447:    my $uhome=&homeserver($uname,$udomain);
1.47      www      1448:    my $items='';
1.191     harris41 1449:    foreach (keys %$storehash) {
1.134     albertel 1450:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1451:    }
1.47      www      1452:    $items=~s/\&$//;
1.134     albertel 1453:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      1454: }
                   1455: 
                   1456: # -------------------------------------------------------------- eget interface
                   1457: 
                   1458: sub eget {
1.133     albertel 1459:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      1460:    my $items='';
1.191     harris41 1461:    foreach (@$storearr) {
1.12      www      1462:        $items.=escape($_).'&';
1.191     harris41 1463:    }
1.12      www      1464:    $items=~s/\&$//;
1.133     albertel 1465:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   1466:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   1467:    my $uhome=&homeserver($uname,$udomain);
                   1468:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      1469:    my @pairs=split(/\&/,$rep);
                   1470:    my %returnhash=();
1.42      www      1471:    my $i=0;
1.191     harris41 1472:    foreach (@$storearr) {
1.42      www      1473:       $returnhash{$_}=unescape($pairs[$i]);
                   1474:       $i++;
1.191     harris41 1475:    }
1.12      www      1476:    return %returnhash;
                   1477: }
                   1478: 
1.103     harris41 1479: # ------------------------------------------------- Check for a user privilege
1.12      www      1480: 
                   1481: sub allowed {
                   1482:     my ($priv,$uri)=@_;
1.152     www      1483: 
                   1484:     my $orguri=$uri;
1.52      www      1485:     $uri=&declutter($uri);
1.29      www      1486: 
1.54      www      1487: # Free bre access to adm and meta resources
1.29      www      1488: 
1.54      www      1489:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      1490: 	return 'F';
1.159     www      1491:     }
                   1492: 
                   1493: # Free bre to public access
                   1494: 
                   1495:     if ($priv eq 'bre') {
                   1496: 	if (&metadata($uri,'copyright') eq 'public') { return 'F'; }
1.14      www      1497:     }
1.29      www      1498: 
1.52      www      1499:     my $thisallowed='';
                   1500:     my $statecond=0;
                   1501:     my $courseprivid='';
                   1502: 
                   1503: # Course
                   1504: 
                   1505:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   1506:        $thisallowed.=$1;
                   1507:     }
1.29      www      1508: 
1.52      www      1509: # Domain
                   1510: 
                   1511:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   1512:        =~/$priv\&([^\:]*)/) {
1.12      www      1513:        $thisallowed.=$1;
                   1514:     }
1.52      www      1515: 
                   1516: # Course: uri itself is a course
1.66      www      1517:     my $courseuri=$uri;
                   1518:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      1519:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      1520: 
1.83      www      1521:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      1522:        =~/$priv\&([^\:]*)/) {
1.12      www      1523:        $thisallowed.=$1;
                   1524:     }
1.29      www      1525: 
1.52      www      1526: # Full access at system, domain or course-wide level? Exit.
1.29      www      1527: 
                   1528:     if ($thisallowed=~/F/) {
                   1529: 	return 'F';
                   1530:     }
                   1531: 
1.52      www      1532: # If this is generating or modifying users, exit with special codes
1.29      www      1533: 
1.166     www      1534:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      1535: 	return $thisallowed;
                   1536:     }
                   1537: #
1.103     harris41 1538: # Gathered so far: system, domain and course wide privileges
1.52      www      1539: #
                   1540: # Course: See if uri or referer is an individual resource that is part of 
                   1541: # the course
                   1542: 
                   1543:     if ($ENV{'request.course.id'}) {
                   1544:        $courseprivid=$ENV{'request.course.id'};
                   1545:        if ($ENV{'request.course.sec'}) {
                   1546:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   1547:        }
                   1548:        $courseprivid=~s/\_/\//;
                   1549:        my $checkreferer=1;
                   1550:        my @uriparts=split(/\//,$uri);
                   1551:        my $filename=$uriparts[$#uriparts];
                   1552:        my $pathname=$uri;
                   1553:        $pathname=~s/\/$filename$//;
                   1554:        if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.54      www      1555:            /\&$filename\:([\d\|]+)\&/) {
1.52      www      1556:            $statecond=$1;
                   1557:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1558:                =~/$priv\&([^\:]*)/) {
                   1559:                $thisallowed.=$1;
                   1560:                $checkreferer=0;
                   1561:            }
1.29      www      1562:        }
1.83      www      1563:        
1.148     www      1564:        if ($checkreferer) {
1.152     www      1565: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      1566: 
                   1567:             unless ($refuri) {
1.191     harris41 1568:                 foreach (keys %ENV) {
1.148     www      1569: 		    if ($_=~/^httpref\..*\*/) {
                   1570: 			my $pattern=$_;
1.156     www      1571:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      1572:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   1573:                         $pattern=~s/\//\\\//g;
1.152     www      1574:                         if ($orguri=~/$pattern/) {
1.148     www      1575: 			    $refuri=$ENV{$_};
                   1576:                         }
                   1577:                     }
1.191     harris41 1578:                 }
1.148     www      1579:             }
                   1580:          if ($refuri) { 
1.152     www      1581: 	  $refuri=&declutter($refuri);
1.53      www      1582:           my @uriparts=split(/\//,$refuri);
1.52      www      1583:           my $filename=$uriparts[$#uriparts];
1.53      www      1584:           my $pathname=$refuri;
1.52      www      1585:           $pathname=~s/\/$filename$//;
1.53      www      1586:             if ($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.54      www      1587:               /\&$filename\:([\d\|]+)\&/) {
1.53      www      1588:               my $refstatecond=$1;
1.52      www      1589:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   1590:                   =~/$priv\&([^\:]*)/) {
                   1591:                   $thisallowed.=$1;
1.53      www      1592:                   $uri=$refuri;
                   1593:                   $statecond=$refstatecond;
1.52      www      1594:               }
                   1595:           }
1.148     www      1596:         }
1.29      www      1597:        }
1.52      www      1598:    }
1.29      www      1599: 
1.52      www      1600: #
1.103     harris41 1601: # Gathered now: all privileges that could apply, and condition number
1.52      www      1602: # 
                   1603: #
                   1604: # Full or no access?
                   1605: #
1.29      www      1606: 
1.52      www      1607:     if ($thisallowed=~/F/) {
                   1608: 	return 'F';
                   1609:     }
1.29      www      1610: 
1.52      www      1611:     unless ($thisallowed) {
                   1612:         return '';
                   1613:     }
1.29      www      1614: 
1.52      www      1615: # Restrictions exist, deal with them
                   1616: #
                   1617: #   C:according to course preferences
                   1618: #   R:according to resource settings
                   1619: #   L:unless locked
                   1620: #   X:according to user session state
                   1621: #
                   1622: 
                   1623: # Possibly locked functionality, check all courses
1.54      www      1624: # Locks might take effect only after 10 minutes cache expiration for other
                   1625: # courses, and 2 minutes for current course
1.52      www      1626: 
                   1627:     my $envkey;
                   1628:     if ($thisallowed=~/L/) {
                   1629:         foreach $envkey (keys %ENV) {
1.54      www      1630:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   1631:                my $courseid=$2;
                   1632:                my $roleid=$1.'.'.$2;
1.92      www      1633:                $courseid=~s/^\///;
1.54      www      1634:                my $expiretime=600;
                   1635:                if ($ENV{'request.role'} eq $roleid) {
                   1636: 		  $expiretime=120;
                   1637:                }
                   1638: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   1639:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   1640:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   1641: 		   &coursedescription($courseid);
                   1642:                }
                   1643:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   1644:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   1645: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      1646:                        &log($ENV{'user.domain'},$ENV{'user.name'},
                   1647:                             $ENV{'user.host'},
                   1648:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      1649:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1650:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1651: 		       return '';
                   1652:                    }
                   1653:                }
1.54      www      1654:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   1655:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   1656: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      1657:                        &log($ENV{'user.domain'},$ENV{'user.name'},
                   1658:                             $ENV{'user.host'},
                   1659:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      1660:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      1661:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      1662: 		       return '';
                   1663:                    }
                   1664:                }
                   1665: 	   }
1.29      www      1666:        }
1.52      www      1667:     }
                   1668:    
                   1669: #
                   1670: # Rest of the restrictions depend on selected course
                   1671: #
                   1672: 
                   1673:     unless ($ENV{'request.course.id'}) {
                   1674:        return '1';
                   1675:     }
1.29      www      1676: 
1.52      www      1677: #
                   1678: # Now user is definitely in a course
                   1679: #
1.53      www      1680: 
                   1681: 
                   1682: # Course preferences
                   1683: 
                   1684:    if ($thisallowed=~/C/) {
1.54      www      1685:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
                   1686:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      1687: 	   =~/$rolecode/) {
1.57      www      1688:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1689:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.54      www      1690:                 $ENV{'request.course.id'});
                   1691:            return '';
                   1692:        }
1.53      www      1693:    }
                   1694: 
                   1695: # Resource preferences
                   1696: 
                   1697:    if ($thisallowed=~/R/) {
1.54      www      1698:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
                   1699:        my $filename=$perlvar{'lonDocRoot'}.'/res/'.$uri.'.meta';
                   1700:        if (-e $filename) {
                   1701:            my @content;
                   1702:            {
                   1703: 	     my $fh=Apache::File->new($filename);
                   1704:              @content=<$fh>;
                   1705: 	   }
                   1706:            if (join('',@content)=~
                   1707:                     /\<roledeny[^\>]*\>[^\<]*$rolecode[^\<]*\<\/roledeny\>/) {
1.57      www      1708: 	       &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   1709:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.54      www      1710:            return '';
                   1711: 
                   1712:            }
                   1713:        }
1.53      www      1714:    }
1.30      www      1715: 
1.52      www      1716: # Restricted by state?
1.30      www      1717: 
1.52      www      1718:    if ($thisallowed=~/X/) {
                   1719:       if (&condval($statecond)) {
                   1720: 	 return '2';
                   1721:       } else {
                   1722:          return '';
                   1723:       }
                   1724:    }
1.30      www      1725: 
1.52      www      1726:    return 'F';
1.12      www      1727: }
                   1728: 
                   1729: # ----------------------------------------------------------------- Define Role
                   1730: 
                   1731: sub definerole {
                   1732:   if (allowed('mcr','/')) {
                   1733:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.191     harris41 1734:     foreach (split('/',$sysrole)) {
1.21      www      1735: 	my ($crole,$cqual)=split(/\&/,$_);
                   1736:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   1737:         if ($pr{'cr:s'}=~/$crole\&/) {
                   1738: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   1739:                return "refused:s:$crole&$cqual"; 
                   1740:             }
                   1741:         }
1.191     harris41 1742:     }
                   1743:     foreach (split('/',$domrole)) {
1.21      www      1744: 	my ($crole,$cqual)=split(/\&/,$_);
                   1745:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   1746:         if ($pr{'cr:d'}=~/$crole\&/) {
                   1747: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   1748:                return "refused:d:$crole&$cqual"; 
                   1749:             }
                   1750:         }
1.191     harris41 1751:     }
                   1752:     foreach (split('/',$courole)) {
1.21      www      1753: 	my ($crole,$cqual)=split(/\&/,$_);
                   1754:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   1755:         if ($pr{'cr:c'}=~/$crole\&/) {
                   1756: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   1757:                return "refused:c:$crole&$cqual"; 
                   1758:             }
                   1759:         }
1.191     harris41 1760:     }
1.12      www      1761:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   1762:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      1763: 	        "rolesdef_$rolename=".
                   1764:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      1765:     return reply($command,$ENV{'user.home'});
                   1766:   } else {
                   1767:     return 'refused';
                   1768:   }
1.105     harris41 1769: }
                   1770: 
                   1771: # ---------------- Make a metadata query against the network of library servers
                   1772: 
                   1773: sub metadata_query {
1.116     harris41 1774:     my ($query,$custom,$customshow)=@_;
1.120     harris41 1775:     my %rhash;
1.123     harris41 1776:     for my $server (keys %libserv) {
1.118     harris41 1777: 	unless ($custom or $customshow) {
                   1778: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   1779: 	    $rhash{$server}=$reply;
                   1780: 	}
                   1781: 	else {
                   1782: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   1783: 			     &escape($custom).':'.&escape($customshow),
                   1784: 			     $server);
                   1785: 	    $rhash{$server}=$reply;
                   1786: 	}
1.112     harris41 1787:     }
1.118     harris41 1788:     return \%rhash;
1.12      www      1789: }
                   1790: 
                   1791: # ------------------------------------------------------------------ Plain Text
                   1792: 
                   1793: sub plaintext {
1.22      www      1794:     my $short=shift;
                   1795:     return $prp{$short};
1.12      www      1796: }
                   1797: 
                   1798: # ----------------------------------------------------------------- Assign Role
                   1799: 
                   1800: sub assignrole {
1.21      www      1801:     my ($udom,$uname,$url,$role,$end,$start)=@_;
                   1802:     my $mrole;
                   1803:     if ($role =~ /^cr\//) {
1.104     www      1804: 	unless (&allowed('ccr',$url)) {
                   1805:            &logthis('Refused custom assignrole: '.
                   1806:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   1807: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   1808:            return 'refused'; 
                   1809:         }
1.21      www      1810:         $mrole='cr';
                   1811:     } else {
1.82      www      1812:         my $cwosec=$url;
1.83      www      1813:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.104     www      1814:         unless (&allowed('c'.$role,$cwosec)) { 
                   1815:            &logthis('Refused assignrole: '.
                   1816:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   1817: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   1818:            return 'refused'; 
                   1819:         }
1.21      www      1820:         $mrole=$role;
                   1821:     }
                   1822:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   1823:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      1824:     if ($end) { $command.='_'.$end; }
1.21      www      1825:     if ($start) {
                   1826: 	if ($end) { 
1.81      www      1827:            $command.='_'.$start; 
1.21      www      1828:         } else {
1.81      www      1829:            $command.='_0_'.$start;
1.21      www      1830:         }
                   1831:     }
                   1832:     return &reply($command,&homeserver($uname,$udom));
1.169     harris41 1833: }
                   1834: 
                   1835: # -------------------------------------------------- Modify user authentication
1.197     www      1836: # Overrides without validation
                   1837: 
1.169     harris41 1838: sub modifyuserauth {
                   1839:     my ($udom,$uname,$umode,$upass)=@_;
                   1840:     my $uhome=&homeserver($uname,$udom);
1.197     www      1841:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   1842:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.169     harris41 1843:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'});  
                   1844:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   1845: 		     &escape($upass),$uhome);
1.197     www      1846:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   1847:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   1848:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   1849:     &log($udom,,$uname,$uhome,
                   1850:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   1851:                                      $ENV{'user.name'}.', '.$umode.
                   1852:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 1853:     unless ($reply eq 'ok') {
1.197     www      1854:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 1855: 	return 'error: '.$reply;
                   1856:     }   
1.170     harris41 1857:     return 'ok';
1.80      www      1858: }
                   1859: 
1.81      www      1860: # --------------------------------------------------------------- Modify a user
1.80      www      1861: 
                   1862: 
1.81      www      1863: sub modifyuser {
1.196     www      1864:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   1865:         $forceid)=@_;
1.198     www      1866:     $udom=~s/\W//g;
                   1867:     $uname=~s/\W//g;
1.81      www      1868:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      1869:              $umode.', '.$first.', '.$middle.', '.
1.196     www      1870: 	     $last.', '.$gene.'(forceid: '.$forceid.') by '.
1.80      www      1871:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});  
                   1872:     my $uhome=&homeserver($uname,$udom);
                   1873: # ----------------------------------------------------------------- Create User
1.81      www      1874:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
1.80      www      1875:         my $unhome='';
                   1876: 	if ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
                   1877: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1878:         } else {
                   1879:             my $tryserver;
1.81      www      1880:             my $loadm=10000000;
1.80      www      1881:             foreach $tryserver (keys %libserv) {
                   1882: 	       if ($hostdom{$tryserver} eq $udom) {
                   1883:                   my $answer=reply('load',$tryserver);
                   1884:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   1885: 		      $loadm=$answer;
                   1886:                       $unhome=$tryserver;
                   1887:                   }
                   1888: 	       }
                   1889: 	    }
                   1890:         }
                   1891:         if (($unhome eq '') || ($unhome eq 'no_host')) {
                   1892: 	    return 'error: find home';
                   1893:         }
                   1894:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   1895:                          &escape($upass),$unhome);
                   1896: 	unless ($reply eq 'ok') {
                   1897:             return 'error: '.$reply;
                   1898:         }   
                   1899:         $uhome=&homeserver($uname,$udom);
                   1900:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
                   1901: 	    return 'error: verify home';
                   1902:         }
                   1903:     }
                   1904: # ---------------------------------------------------------------------- Add ID
                   1905:     if ($uid) {
                   1906:        $uid=~tr/A-Z/a-z/;
                   1907:        my %uidhash=&idrget($udom,$uname);
1.196     www      1908:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   1909:          && (!$forceid)) {
1.80      www      1910: 	  unless ($uid eq $uidhash{$uname}) {
                   1911: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
                   1912:           }
                   1913:        } else {
                   1914: 	  &idput($udom,($uname => $uid));
                   1915:        }
                   1916:     }
                   1917: # -------------------------------------------------------------- Add names, etc
1.134     albertel 1918:     my %names=&get('environment',
                   1919: 		   ['firstname','middlename','lastname','generation'],
                   1920: 		   $udom,$uname);
                   1921:     if ($first)  { $names{'firstname'}  = $first; }
                   1922:     if ($middle) { $names{'middlename'} = $middle; }
                   1923:     if ($last)   { $names{'lastname'}   = $last; }
                   1924:     if ($gene)   { $names{'generation'} = $gene; }
                   1925:     my $reply = &put('environment', \%names, $udom,$uname);
                   1926:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      1927:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      1928:              $umode.', '.$first.', '.$middle.', '.
                   1929: 	     $last.', '.$gene.' by '.
                   1930:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 1931:     return 'ok';
1.80      www      1932: }
                   1933: 
1.81      www      1934: # -------------------------------------------------------------- Modify student
1.80      www      1935: 
1.81      www      1936: sub modifystudent {
                   1937:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.197     www      1938:         $end,$start,$forceid)=@_;
1.81      www      1939:     my $cid='';
                   1940:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      1941: 	return 'not_in_class';
                   1942:     }
                   1943: # --------------------------------------------------------------- Make the user
1.81      www      1944:     my $reply=&modifyuser
1.197     www      1945: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid);
1.80      www      1946:     unless ($reply eq 'ok') { return $reply; }
1.81      www      1947:     my $uhome=&homeserver($uname,$udom);
                   1948:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   1949: 	return 'error: no such user';
                   1950:     }
1.80      www      1951: # -------------------------------------------------- Add student to course list
1.160     www      1952:     $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      1953: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   1954:                       &escape($uname.':'.$udom).'='.
                   1955:                       &escape($end.':'.$start),
                   1956: 	              $ENV{'course.'.$cid.'.home'});
                   1957:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   1958: 	return 'error: '.$reply;
                   1959:     }
1.80      www      1960: # ---------------------------------------------------- Add student role to user
1.83      www      1961:     my $uurl='/'.$cid;
1.81      www      1962:     $uurl=~s/\_/\//g;
                   1963:     if ($usec) {
                   1964: 	$uurl.='/'.$usec;
                   1965:     }
                   1966:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      1967: }
                   1968: 
1.84      www      1969: # ------------------------------------------------- Write to course preferences
                   1970: 
                   1971: sub writecoursepref {
                   1972:     my ($courseid,%prefs)=@_;
                   1973:     $courseid=~s/^\///;
                   1974:     $courseid=~s/\_/\//g;
                   1975:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   1976:     my $chome=homeserver($cnum,$cdomain);
                   1977:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   1978: 	return 'error: no such course';
                   1979:     }
                   1980:     my $cstring='';
1.191     harris41 1981:     foreach (keys %prefs) {
1.84      www      1982: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 1983:     }
1.84      www      1984:     $cstring=~s/\&$//;
                   1985:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   1986: }
                   1987: 
                   1988: # ---------------------------------------------------------- Make/modify course
                   1989: 
                   1990: sub createcourse {
                   1991:     my ($udom,$description,$url)=@_;
                   1992:     $url=&declutter($url);
                   1993:     my $cid='';
                   1994:     unless (&allowed('ccc',$ENV{'user.domain'})) {
                   1995:         return 'refused';
                   1996:     }
                   1997:     unless ($udom eq $ENV{'user.domain'}) {
                   1998:         return 'refused';
                   1999:     }
                   2000: # ------------------------------------------------------------------- Create ID
                   2001:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2002:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   2003: # ----------------------------------------------- Make sure that does not exist
                   2004:    my $uhome=&homeserver($uname,$udom);
                   2005:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2006:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   2007:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   2008:        $uhome=&homeserver($uname,$udom);       
                   2009:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   2010:            return 'error: unable to generate unique course-ID';
                   2011:        } 
                   2012:    }
                   2013: # ------------------------------------------------------------- Make the course
                   2014:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
                   2015:                       $ENV{'user.home'});
                   2016:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.160     www      2017:     $uhome=&homeserver($uname,$udom);
1.84      www      2018:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2019: 	return 'error: no such course';
                   2020:     }
                   2021:     &writecoursepref($udom.'_'.$uname,
                   2022:                      ('description' => $description,
                   2023:                       'url'         => $url));
                   2024:     return '/'.$udom.'/'.$uname;
                   2025: }
                   2026: 
1.21      www      2027: # ---------------------------------------------------------- Assign Custom Role
                   2028: 
                   2029: sub assigncustomrole {
                   2030:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start)=@_;
                   2031:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
                   2032:                        $end,$start);
                   2033: }
                   2034: 
                   2035: # ----------------------------------------------------------------- Revoke Role
                   2036: 
                   2037: sub revokerole {
                   2038:     my ($udom,$uname,$url,$role)=@_;
                   2039:     my $now=time;
                   2040:     return &assignrole($udom,$uname,$url,$role,$now);
                   2041: }
                   2042: 
                   2043: # ---------------------------------------------------------- Revoke Custom Role
                   2044: 
                   2045: sub revokecustomrole {
                   2046:     my ($udom,$uname,$url,$rdom,$rnam,$rolename)=@_;
                   2047:     my $now=time;
                   2048:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now);
1.17      www      2049: }
                   2050: 
                   2051: # ------------------------------------------------------------ Directory lister
                   2052: 
                   2053: sub dirlist {
                   2054:     my $uri=shift;
1.18      www      2055:     $uri=~s/^\///;
                   2056:     $uri=~s/\/$//;
1.19      www      2057:     my ($res,$udom,$uname,@rest)=split(/\//,$uri);
                   2058:     if ($udom) {
                   2059:      if ($uname) {
                   2060:        my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/'.$uri,
                   2061:                       homeserver($uname,$udom));
                   2062:        return split(/:/,$listing);
                   2063:      } else {
                   2064:        my $tryserver;
                   2065:        my %allusers=();
                   2066:        foreach $tryserver (keys %libserv) {
                   2067: 	  if ($hostdom{$tryserver} eq $udom) {
                   2068:              my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.$udom,
                   2069: 			       $tryserver);
                   2070:              if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   2071:               && ($listing ne 'con_lost')) {
1.191     harris41 2072:                 foreach (split(/:/,$listing)) {
1.19      www      2073:                   my ($entry,@stat)=split(/&/,$_);
                   2074:                   $allusers{$entry}=1;
1.191     harris41 2075:                 }
1.19      www      2076:              }
                   2077: 	  }
                   2078:        }
                   2079:        my $alluserstr='';
1.191     harris41 2080:        foreach (sort keys %allusers) {
1.19      www      2081:            $alluserstr.=$_.'&user:';
1.191     harris41 2082:        }
1.19      www      2083:        $alluserstr=~s/:$//;
                   2084:        return split(/:/,$alluserstr);
                   2085:      } 
                   2086:    } else {
                   2087:        my $tryserver;
                   2088:        my %alldom=();
                   2089:        foreach $tryserver (keys %libserv) {
                   2090: 	   $alldom{$hostdom{$tryserver}}=1;
                   2091:        }
                   2092:        my $alldomstr='';
1.191     harris41 2093:        foreach (sort keys %alldom) {
1.19      www      2094:           $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
1.191     harris41 2095:        }
1.19      www      2096:        $alldomstr=~s/:$//;
                   2097:        return split(/:/,$alldomstr);       
                   2098:    }
1.26      www      2099: }
                   2100: 
                   2101: # -------------------------------------------------------- Value of a Condition
                   2102: 
1.40      www      2103: sub directcondval {
                   2104:     my $number=shift;
                   2105:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   2106:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   2107:     } else {
                   2108:        return 2;
                   2109:     }
                   2110: }
                   2111: 
1.26      www      2112: sub condval {
                   2113:     my $condidx=shift;
                   2114:     my $result=0;
1.54      www      2115:     my $allpathcond='';
1.191     harris41 2116:     foreach (split(/\|/,$condidx)) {
1.54      www      2117:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   2118: 	   $allpathcond.=
                   2119:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   2120:        }
1.191     harris41 2121:     }
1.54      www      2122:     $allpathcond=~s/\|$//;
1.33      www      2123:     if ($ENV{'request.course.id'}) {
1.54      www      2124:        if ($allpathcond) {
1.26      www      2125:           my $operand='|';
                   2126: 	  my @stack;
1.191     harris41 2127:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      2128:               if ($_ eq '(') {
                   2129:                  push @stack,($operand,$result)
                   2130:               } elsif ($_ eq ')') {
                   2131:                   my $before=pop @stack;
                   2132: 		  if (pop @stack eq '&') {
                   2133: 		      $result=$result>$before?$before:$result;
                   2134:                   } else {
                   2135:                       $result=$result>$before?$result:$before;
                   2136:                   }
                   2137:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   2138:                   $operand=$_;
                   2139:               } else {
1.40      www      2140:                   my $new=directcondval($_);
1.26      www      2141:                   if ($operand eq '&') {
                   2142:                      $result=$result>$new?$new:$result;
                   2143:                   } else {
                   2144:                      $result=$result>$new?$result:$new;
1.191     harris41 2145:                   }
1.26      www      2146:               }
1.191     harris41 2147:           }
1.26      www      2148:        }
                   2149:     }
                   2150:     return $result;
1.28      www      2151: }
                   2152: 
1.200     www      2153: # --------------------------------------------------- Course Resourcedata Query
                   2154: 
                   2155: sub courseresdata {
                   2156:     my ($coursenum,$coursedomain,@which)=@_;
                   2157:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   2158:     my $hashid=$coursenum.':'.$coursedomain;
                   2159:     unless (defined($courseresdatacache{$hashid.'.time'})) {
                   2160: 	unless (time-$courseresdatacache{$hashid.'.time'}<300) {
                   2161:            my $coursehom=&homeserver($coursenum,$coursedomain);
                   2162:            if ($coursehom) {
                   2163:               my $dumpreply=&reply('dump:'.$coursedomain.':'.$coursenum.
                   2164: 			     ':resourcedata:.',$coursehom);
                   2165: 	      unless ($dumpreply=~/^error\:/) {
                   2166: 	         $courseresdatacache{$hashid.'.time'}=time;
                   2167:                  $courseresdatacache{$hashid}=$dumpreply;
                   2168: 	     }
                   2169: 	  }
                   2170:        }
                   2171:     }
                   2172:    my @pairs=split(/\&/,$courseresdatacache{$hashid});
                   2173:    my %returnhash=();
                   2174:    foreach (@pairs) {
                   2175:       my ($key,$value)=split(/=/,$_);
                   2176:       $returnhash{unescape($key)}=unescape($value);
                   2177:    }
                   2178:     my $item;
                   2179:    foreach $item (@which) {
                   2180:        if ($returnhash{$item}) { return $returnhash{$item}; }
                   2181:    }
                   2182:    return '';
                   2183: }
                   2184: 
1.28      www      2185: # --------------------------------------------------------- Value of a Variable
                   2186: 
1.58      www      2187: sub EXT {
1.147     www      2188:     my ($varname,$symbparm)=@_;
1.68      www      2189:     unless ($varname) { return ''; }
1.48      www      2190:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   2191:     my $rest;
                   2192:     if ($therest[0]) {
                   2193:        $rest=join('.',@therest);
                   2194:     } else {
                   2195:        $rest='';
                   2196:     }
1.57      www      2197:     my $qualifierrest=$qualifier;
                   2198:     if ($rest) { $qualifierrest.='.'.$rest; }
                   2199:     my $spacequalifierrest=$space;
                   2200:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      2201:     if ($realm eq 'user') {
1.48      www      2202: # --------------------------------------------------------------- user.resource
                   2203: 	if ($space eq 'resource') {
1.122     albertel 2204: 	    my %restored=&restore();
1.57      www      2205:             return $restored{$qualifierrest};
1.48      www      2206: # ----------------------------------------------------------------- user.access
                   2207:         } elsif ($space eq 'access') {
                   2208:             return &allowed($qualifier,$rest);
                   2209: # ------------------------------------------ user.preferences, user.environment
                   2210:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.57      www      2211:             return $ENV{join('.',('environment',$qualifierrest))};
1.48      www      2212: # ----------------------------------------------------------------- user.course
                   2213:         } elsif ($space eq 'course') {
                   2214:             return $ENV{join('.',('request.course',$qualifier))};
                   2215: # ------------------------------------------------------------------- user.role
                   2216:         } elsif ($space eq 'role') {
                   2217:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   2218:             if ($qualifier eq 'value') {
                   2219: 		return $role;
                   2220:             } elsif ($qualifier eq 'extent') {
                   2221:                 return $where;
                   2222:             }
                   2223: # ----------------------------------------------------------------- user.domain
                   2224:         } elsif ($space eq 'domain') {
                   2225:             return $ENV{'user.domain'};
                   2226: # ------------------------------------------------------------------- user.name
                   2227:         } elsif ($space eq 'name') {
                   2228:             return $ENV{'user.name'};
                   2229: # ---------------------------------------------------- Any other user namespace
1.29      www      2230:         } else {
1.48      www      2231:             my $item=($rest)?$qualifier.'.'.$rest:$qualifier;
1.131     albertel 2232:             my %reply=&get($space,[$item]);
1.48      www      2233:             return $reply{$item};
                   2234:         }
                   2235:     } elsif ($realm eq 'request') {
                   2236: # ------------------------------------------------------------- request.browser
                   2237:         if ($space eq 'browser') {
                   2238: 	    return $ENV{'browser.'.$qualifier};
1.57      www      2239: # ------------------------------------------------------------ request.filename
                   2240:         } else {
                   2241:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      2242:         }
1.28      www      2243:     } elsif ($realm eq 'course') {
1.48      www      2244: # ---------------------------------------------------------- course.description
1.127     ng       2245:         return $ENV{'course.'.$ENV{'request.course.id'}.'.'.
1.57      www      2246:                               $spacequalifierrest};
                   2247:     } elsif ($realm eq 'resource') {
1.127     ng       2248:        if ($ENV{'request.course.id'}) {
1.165     www      2249: 
                   2250: #	   print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
                   2251: 
                   2252: 
1.60      www      2253: # ----------------------------------------------------- Cascading lookup scheme
1.147     www      2254:          my $symbp;
                   2255:          if ($symbparm) {
                   2256:             $symbp=$symbparm;
                   2257: 	 } else {
                   2258:             $symbp=&symbread();
                   2259:          }            
1.127     ng       2260:          my $mapp=(split(/\_\_\_/,$symbp))[0];
1.69      www      2261: 
1.127     ng       2262:          my $symbparm=$symbp.'.'.$spacequalifierrest;
                   2263:          my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.69      www      2264: 
1.127     ng       2265:          my $seclevel=
1.69      www      2266:             $ENV{'request.course.id'}.'.['.
                   2267: 		$ENV{'request.course.sec'}.'].'.$spacequalifierrest;
1.127     ng       2268:          my $seclevelr=
1.69      www      2269:             $ENV{'request.course.id'}.'.['.
                   2270: 		$ENV{'request.course.sec'}.'].'.$symbparm;
1.127     ng       2271:          my $seclevelm=
1.69      www      2272:             $ENV{'request.course.id'}.'.['.
                   2273: 		$ENV{'request.course.sec'}.'].'.$mapparm;
                   2274: 
1.127     ng       2275:          my $courselevel=
1.60      www      2276:             $ENV{'request.course.id'}.'.'.$spacequalifierrest;
1.127     ng       2277:          my $courselevelr=
1.69      www      2278:             $ENV{'request.course.id'}.'.'.$symbparm;
1.127     ng       2279:          my $courselevelm=
1.69      www      2280:             $ENV{'request.course.id'}.'.'.$mapparm;
                   2281: 
1.60      www      2282: # ----------------------------------------------------------- first, check user
1.127     ng       2283:          my %resourcedata=get('resourcedata',
1.131     albertel 2284:                            [$courselevelr,$courselevelm,$courselevel]);
1.127     ng       2285:          if (($resourcedata{$courselevelr}!~/^error\:/) &&
                   2286:              ($resourcedata{$courselevelr}!~/^con_lost/)) {
1.69      www      2287: 
1.127     ng       2288:          if ($resourcedata{$courselevelr}) { 
                   2289:             return $resourcedata{$courselevelr}; }
                   2290:          if ($resourcedata{$courselevelm}) { 
                   2291:             return $resourcedata{$courselevelm}; }
                   2292:          if ($resourcedata{$courselevel}) { return $resourcedata{$courselevel}; }
1.69      www      2293: 
1.94      www      2294:       } else {
                   2295: 	  if ($resourcedata{$courselevelr}!~/No such file/) {
                   2296: 	    &logthis("<font color=blue>WARNING:".
                   2297: 		   " Trying to get resource data for ".$ENV{'user.name'}." at "
                   2298:                    .$ENV{'user.domain'}.": ".$resourcedata{$courselevelr}.
                   2299:                  "</font>");
                   2300: 	  }
1.63      www      2301:       }
1.95      www      2302: 
1.60      www      2303: # -------------------------------------------------------- second, check course
1.96      www      2304: 
1.200     www      2305:         my $coursereply=&courseresdata(
                   2306:                         $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
                   2307:                         $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
                   2308:                         ($seclevelr,$seclevelm,$seclevel,
                   2309:                          $courselevelr,$courselevelm,$courselevel));
                   2310:         if ($coursereply) { return $coursereply; }
                   2311: 
1.60      www      2312: # ------------------------------------------------------ third, check map parms
1.65      www      2313:        my %parmhash=();
                   2314:        my $thisparm='';       
                   2315:        if (tie(%parmhash,'GDBM_File',
                   2316:           $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {
                   2317:            $thisparm=$parmhash{$symbparm};
                   2318: 	   untie(%parmhash);
1.60      www      2319:        }
1.65      www      2320:        if ($thisparm) { return $thisparm; }
1.60      www      2321:      }
                   2322:      
                   2323: # --------------------------------------------- last, look in resource metadata
1.71      www      2324: 
1.78      www      2325:       $spacequalifierrest=~s/\./\_/;
1.71      www      2326:       my $metadata=&metadata($ENV{'request.filename'},$spacequalifierrest);
                   2327:       if ($metadata) { return $metadata; }
1.78      www      2328:       $metadata=&metadata($ENV{'request.filename'},
                   2329:                                          'parameter_'.$spacequalifierrest);
                   2330:       if ($metadata) { return $metadata; }
1.142     www      2331: 
1.145     www      2332: # ------------------------------------------------------------------ Cascade up
                   2333: 
                   2334:       unless ($space eq '0') {
1.165     www      2335:           my ($part,$id)=split(/\_/,$space);
1.145     www      2336:           if ($id) {
1.147     www      2337: 	      my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
                   2338:                                    $symbparm);
1.145     www      2339:               if ($partgeneral) { return $partgeneral; }
                   2340:           } else {
1.147     www      2341:               my $resourcegeneral=&EXT('resource.0.'.$qualifierrest,
                   2342:                                        $symbparm);
1.145     www      2343:               if ($resourcegeneral) { return $resourcegeneral; }
                   2344:           }
                   2345:       }
1.71      www      2346: 
1.48      www      2347: # ---------------------------------------------------- Any other user namespace
                   2348:     } elsif ($realm eq 'environment') {
                   2349: # ----------------------------------------------------------------- environment
1.127     ng       2350:         return $ENV{'environment.'.$spacequalifierrest};
1.28      www      2351:     } elsif ($realm eq 'system') {
1.48      www      2352: # ----------------------------------------------------------------- system.time
                   2353: 	if ($space eq 'time') {
                   2354: 	    return time;
                   2355:         }
1.28      www      2356:     }
1.48      www      2357:     return '';
1.61      www      2358: }
                   2359: 
1.71      www      2360: # ---------------------------------------------------------------- Get metadata
                   2361: 
                   2362: sub metadata {
1.176     www      2363:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      2364: 
1.71      www      2365:     $uri=&declutter($uri);
1.73      www      2366:     my $filename=$uri;
                   2367:     $uri=~s/\.meta$//;
1.172     www      2368: #
                   2369: # Is the metadata already cached?
1.177     www      2370: # Look at timestamp of caching
1.172     www      2371: # Everything is cached by the main uri, libraries are never directly cached
                   2372: #
1.174     www      2373:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600) {
1.172     www      2374: #
                   2375: # Is this a recursive call for a library?
                   2376: #
1.171     www      2377:         if ($liburi) {
                   2378: 	    $liburi=&declutter($liburi);
                   2379:             $filename=$liburi;
                   2380:         }
1.140     www      2381:         my %metathesekeys=();
1.73      www      2382:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
                   2383: 	my $metastring=&getfile($perlvar{'lonDocRoot'}.'/res/'.$filename);
1.71      www      2384:         my $parser=HTML::TokeParser->new(\$metastring);
                   2385:         my $token;
1.140     www      2386:         undef %metathesekeys;
1.71      www      2387:         while ($token=$parser->get_token) {
                   2388:            if ($token->[0] eq 'S') {
1.135     www      2389: 	     if (defined($token->[2]->{'package'})) {
1.172     www      2390: #
                   2391: # This is a package - get package info
                   2392: #
1.136     www      2393: 	      my $package=$token->[2]->{'package'};
                   2394: 	      my $keyroot='';
1.172     www      2395:               if ($prefix) {
                   2396: 		  $keyroot.='_'.$prefix;
                   2397:               } else {
                   2398:                 if (defined($token->[2]->{'part'})) { 
                   2399:                    $keyroot.='_'.$token->[2]->{'part'}; 
                   2400: 	        }
1.136     www      2401: 	      }
                   2402:               if (defined($token->[2]->{'id'})) { 
1.165     www      2403:                  $keyroot.='_'.$token->[2]->{'id'}; 
1.136     www      2404: 	      }
                   2405:               if ($metacache{$uri.':packages'}) {
                   2406:                  $metacache{$uri.':packages'}.=','.$package.$keyroot;
                   2407:               } else {
                   2408:                  $metacache{$uri.':packages'}=$package.$keyroot;
                   2409: 	      }
1.191     harris41 2410:               foreach (keys %packagetab) {
1.137     www      2411: 		  if ($_=~/^$package\&/) {
                   2412: 		      my ($pack,$name,$subp)=split(/\&/,$_);
1.139     www      2413:                       my $value=$packagetab{$_};
1.144     www      2414: 		      my $part=$keyroot;
                   2415:                       $part=~s/^\_//;
1.139     www      2416:                       if ($subp eq 'display') {
                   2417: 			  $value.=' [Part: '.$part.']';
                   2418:                       }
                   2419:                       my $unikey='parameter'.$keyroot.'_'.$name;
1.140     www      2420:                       $metathesekeys{$unikey}=1;
1.144     www      2421:                       $metacache{$uri.':'.$unikey.'.part'}=$part;
1.141     www      2422:                       unless 
                   2423:                        (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   2424:                          $metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   2425: 		      }
1.137     www      2426:                   }
1.191     harris41 2427:               }
1.135     www      2428:              } else {
1.172     www      2429: #
                   2430: # This is not a package - some other kind of start tag
                   2431: # 
1.175     www      2432:               my $entry=$token->[1];
1.176     www      2433:               my $unikey;
                   2434:               if ($entry eq 'import') {
                   2435:                  $unikey='';
                   2436:               } else {
                   2437:                  $unikey=$entry;
                   2438: 	      }
1.172     www      2439:               if ($prefix) {
1.176     www      2440: 		  $unikey.=$prefix;
1.172     www      2441:               } else {
                   2442:                 if (defined($token->[2]->{'part'})) { 
                   2443:                    $unikey.='_'.$token->[2]->{'part'}; 
                   2444: 	        }
1.136     www      2445: 	      }
                   2446:               if (defined($token->[2]->{'id'})) { 
1.165     www      2447:                  $unikey.='_'.$token->[2]->{'id'}; 
1.71      www      2448: 	      }
1.175     www      2449: 
                   2450:              if ($entry eq 'import') {
                   2451: #
                   2452: # Importing a library here
1.176     www      2453: #                
                   2454: 		 if (defined($depthcount)) { $depthcount++; } else 
                   2455:                                            { $depthcount=0; }
                   2456:                  if ($depthcount<20) {
1.191     harris41 2457: 		     foreach (split(/\,/,&metadata($uri,'keys',
                   2458:                                   $parser->get_text('/import'),$unikey,
                   2459:                                   $depthcount))) {
1.177     www      2460:                          $metathesekeys{$_}=1;
1.191     harris41 2461: 		     }
1.176     www      2462: 		 }
1.175     www      2463:              } else { 
                   2464: 
1.72      www      2465:               if (defined($token->[2]->{'name'})) { 
1.71      www      2466:                  $unikey.='_'.$token->[2]->{'name'}; 
                   2467: 	      }
1.140     www      2468:               $metathesekeys{$unikey}=1;
1.191     harris41 2469:               foreach (@{$token->[3]}) {
1.71      www      2470: 		  $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.191     harris41 2471:               }
1.78      www      2472:               unless (
                   2473:                  $metacache{$uri.':'.$unikey}=$parser->get_text('/'.$entry)
                   2474: 		      ) { $metacache{$uri.':'.$unikey}=
                   2475: 			      $metacache{$uri.':'.$unikey.'.default'};
                   2476: 		      }
1.172     www      2477: # end of not-a-package not-a-library import
1.175     www      2478: 	   }
1.172     www      2479: # end of not-a-package start tag
                   2480: 	  }
                   2481: # the next is the end of "start tag"
1.140     www      2482: 	 }
1.71      www      2483:        }
1.140     www      2484:        $metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.174     www      2485:        $metacache{$uri.':cachedtimestamp'}=time;
1.177     www      2486: # this is the end of "was not already recently cached
1.71      www      2487:     }
                   2488:     return $metacache{$uri.':'.$what};
                   2489: }
                   2490: 
1.31      www      2491: # ------------------------------------------------- Update symbolic store links
                   2492: 
                   2493: sub symblist {
                   2494:     my ($mapname,%newhash)=@_;
                   2495:     $mapname=declutter($mapname);
                   2496:     my %hash;
                   2497:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   2498:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
                   2499:                       &GDBM_WRCREAT,0640)) {
1.191     harris41 2500: 	    foreach (keys %newhash) {
1.31      www      2501:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 2502:             }
1.31      www      2503:             if (untie(%hash)) {
                   2504: 		return 'ok';
                   2505:             }
                   2506:         }
                   2507:     }
                   2508:     return 'error';
                   2509: }
                   2510: 
                   2511: # ------------------------------------------------------ Return symb list entry
                   2512: 
                   2513: sub symbread {
1.44      www      2514:     my $thisfn=shift;
                   2515:     unless ($thisfn) {
1.179     www      2516:         if ($ENV{'request.symb'}) { return $ENV{'request.symb'}; }
1.44      www      2517: 	$thisfn=$ENV{'request.filename'};
                   2518:     }
                   2519:     $thisfn=declutter($thisfn);
1.31      www      2520:     my %hash;
1.37      www      2521:     my %bighash;
                   2522:     my $syval='';
1.45      www      2523:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      2524:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
                   2525:                       &GDBM_READER,0640)) {
                   2526: 	    $syval=$hash{$thisfn};
1.37      www      2527:             untie(%hash);
                   2528:         }
                   2529: # ---------------------------------------------------------- There was an entry
                   2530:         if ($syval) {
                   2531:            unless ($syval=~/\_\d+$/) {
                   2532: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      2533:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      2534:                   return '';
                   2535:                }    
                   2536:                $syval.=$1;
                   2537: 	   }
                   2538:         } else {
                   2539: # ------------------------------------------------------- Was not in symb table
                   2540:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   2541:                             &GDBM_READER,0640)) {
                   2542: # ---------------------------------------------- Get ID(s) for current resource
                   2543:               my $ids=$bighash{'ids_/res/'.$thisfn};
1.65      www      2544:               unless ($ids) { 
                   2545:                  $ids=$bighash{'ids_/'.$thisfn};
                   2546:               }
1.37      www      2547:               if ($ids) {
                   2548: # ------------------------------------------------------------------- Has ID(s)
                   2549:                  my @possibilities=split(/\,/,$ids);
1.39      www      2550:                  if ($#possibilities==0) {
                   2551: # ----------------------------------------------- There is only one possibility
1.37      www      2552: 		     my ($mapid,$resid)=split(/\./,$ids);
                   2553:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
                   2554:                  } else {
1.39      www      2555: # ------------------------------------------ There is more than one possibility
                   2556:                      my $realpossible=0;
1.191     harris41 2557:                      foreach (@possibilities) {
1.39      www      2558: 			 my $file=$bighash{'src_'.$_};
                   2559:                          if (&allowed('bre',$file)) {
                   2560:          		    my ($mapid,$resid)=split(/\./,$_);
                   2561:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   2562: 				$realpossible++;
                   2563:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   2564:                                        '___'.$resid;
                   2565:                             }
                   2566: 			 }
1.191     harris41 2567:                      }
1.39      www      2568: 		     if ($realpossible!=1) { $syval=''; }
1.37      www      2569:                  }
                   2570: 	      }
                   2571:               untie(%bighash)
                   2572:            } 
1.31      www      2573:         }
1.62      www      2574:         if ($syval) {
                   2575:            return $syval.'___'.$thisfn; 
                   2576:         }
1.31      www      2577:     }
1.44      www      2578:     &appenv('request.ambiguous' => $thisfn);
1.31      www      2579:     return '';
                   2580: }
                   2581: 
                   2582: # ---------------------------------------------------------- Return random seed
                   2583: 
1.32      www      2584: sub numval {
                   2585:     my $txt=shift;
                   2586:     $txt=~tr/A-J/0-9/;
                   2587:     $txt=~tr/a-j/0-9/;
                   2588:     $txt=~tr/K-T/0-9/;
                   2589:     $txt=~tr/k-t/0-9/;
                   2590:     $txt=~tr/U-Z/0-5/;
                   2591:     $txt=~tr/u-z/0-5/;
                   2592:     $txt=~s/\D//g;
                   2593:     return int($txt);
                   2594: }    
                   2595: 
1.31      www      2596: sub rndseed {
1.155     albertel 2597:     my ($symb,$courseid,$domain,$username)=@_;
                   2598:     if (!$symb) {
                   2599:       unless ($symb=&symbread()) { return time; }
                   2600:     }
                   2601:     if (!$courseid) { $courseid=$ENV{'request.course.id'};}
                   2602:     if (!$domain) {$domain=$ENV{'user.domain'};}
                   2603:     if (!$username) {$username=$ENV{'user.name'};}
                   2604:     {
1.98      albertel 2605:       use integer;
                   2606:       my $symbchck=unpack("%32C*",$symb) << 27;
1.100     albertel 2607:       my $symbseed=numval($symb) << 22;
1.155     albertel 2608:       my $namechck=unpack("%32C*",$username) << 17;
                   2609:       my $nameseed=numval($username) << 12;
                   2610:       my $domainseed=unpack("%32C*",$domain) << 7;
                   2611:       my $courseseed=unpack("%32C*",$courseid);
1.98      albertel 2612:       my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.99      albertel 2613:       #uncommenting these lines can break things!
                   2614:       #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   2615:       #&Apache::lonxml::debug("rndseed :$num:$symb");
1.98      albertel 2616:       return $num;
                   2617:     }
1.36      albertel 2618: }
                   2619: 
1.76      www      2620: sub ireceipt {
                   2621:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   2622:     my $cuname=unpack("%32C*",$funame);
                   2623:     my $cudom=unpack("%32C*",$fudom);
                   2624:     my $cucourseid=unpack("%32C*",$fucourseid);
                   2625:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      2626:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      2627:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   2628:            ($cunique%$cuname+
                   2629:             $cunique%$cudom+
                   2630:             $cusymb%$cuname+
                   2631:             $cusymb%$cudom+
                   2632:             $cucourseid%$cuname+
                   2633:             $cucourseid%$cudom);
                   2634: }
                   2635: 
                   2636: sub receipt {
                   2637:     return &ireceipt($ENV{'user.name'},$ENV{'user.domain'},
                   2638:                      $ENV{'request.course.id'},&symbread());
                   2639: }
                   2640:   
1.36      albertel 2641: # ------------------------------------------------------------ Serves up a file
                   2642: # returns either the contents of the file or a -1
                   2643: sub getfile {
                   2644:   my $file=shift;
1.37      www      2645:   &repcopy($file);
1.36      albertel 2646:   if (! -e $file ) { return -1; };
                   2647:   my $fh=Apache::File->new($file);
                   2648:   my $a='';
                   2649:   while (<$fh>) { $a .=$_; }
                   2650:   return $a
                   2651: }
                   2652: 
                   2653: sub filelocation {
                   2654:   my ($dir,$file) = @_;
                   2655:   my $location;
                   2656:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 2657:   if ($file=~m:^/~:) { # is a contruction space reference
                   2658:     $location = $file;
                   2659:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.36      albertel 2660:   } else {
1.59      albertel 2661:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   2662:     $file=~s:^/*res::;
                   2663:     if ( !( $file =~ m:^/:) ) {
                   2664:       $location = $dir. '/'.$file;
                   2665:     } else {
                   2666:       $location = '/home/httpd/html/res'.$file;
                   2667:     }
1.36      albertel 2668:   }
                   2669:   $location=~s://+:/:g; # remove duplicate /
1.46      www      2670:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   2671:   return $location;
                   2672: }
1.36      albertel 2673: 
1.46      www      2674: sub hreflocation {
                   2675:     my ($dir,$file)=@_;
1.191     harris41 2676:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      2677:        my $finalpath=filelocation($dir,$file);
                   2678:        $finalpath=~s/^\/home\/httpd\/html//;
                   2679:        return $finalpath;
                   2680:     } else {
                   2681:        return $file;
                   2682:     }
1.31      www      2683: }
                   2684: 
                   2685: # ------------------------------------------------------------- Declutters URLs
                   2686: 
                   2687: sub declutter {
                   2688:     my $thisfn=shift;
                   2689:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   2690:     $thisfn=~s/^\///;
                   2691:     $thisfn=~s/^res\///;
                   2692:     return $thisfn;
1.12      www      2693: }
                   2694: 
                   2695: # -------------------------------------------------------- Escape Special Chars
                   2696: 
                   2697: sub escape {
                   2698:     my $str=shift;
                   2699:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   2700:     return $str;
                   2701: }
                   2702: 
                   2703: # ----------------------------------------------------- Un-Escape Special Chars
                   2704: 
                   2705: sub unescape {
                   2706:     my $str=shift;
                   2707:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2708:     return $str;
                   2709: }
1.11      www      2710: 
1.1       albertel 2711: # ================================================================ Main Program
                   2712: 
1.184     www      2713: sub goodbye {
1.204   ! albertel 2714:    &logthis("Starting Shut down");
1.184     www      2715:    &flushcourselogs();
                   2716:    &logthis("Shutting down");
                   2717: }
                   2718: 
1.179     www      2719: BEGIN {
1.1       albertel 2720: # ------------------------------------------------------------ Read access.conf
1.195     www      2721:     unless ($readit) {
1.1       albertel 2722: {
                   2723:     my $config=Apache::File->new("/etc/httpd/conf/access.conf");
                   2724: 
                   2725:     while (my $configline=<$config>) {
                   2726:         if ($configline =~ /PerlSetVar/) {
                   2727: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      2728:            chomp($varvalue);
1.1       albertel 2729:            $perlvar{$varname}=$varvalue;
                   2730:         }
                   2731:     }
                   2732: }
                   2733: 
                   2734: # ------------------------------------------------------------- Read hosts file
                   2735: {
                   2736:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   2737: 
                   2738:     while (my $configline=<$config>) {
1.154     www      2739:        chomp($configline);
1.1       albertel 2740:        my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   2741:        $hostname{$id}=$name;
                   2742:        $hostdom{$id}=$domain;
1.150     www      2743:        $hostip{$id}=$ip;
1.1       albertel 2744:        if ($role eq 'library') { $libserv{$id}=$name; }
                   2745:     }
                   2746: }
                   2747: 
                   2748: # ------------------------------------------------------ Read spare server file
                   2749: {
                   2750:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   2751: 
                   2752:     while (my $configline=<$config>) {
                   2753:        chomp($configline);
                   2754:        if (($configline) && ($configline ne $perlvar{'lonHostID'})) {
                   2755:           $spareid{$configline}=1;
                   2756:        }
                   2757:     }
                   2758: }
1.11      www      2759: # ------------------------------------------------------------ Read permissions
                   2760: {
                   2761:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   2762: 
                   2763:     while (my $configline=<$config>) {
                   2764:        chomp($configline);
1.160     www      2765:       if ($configline) {
1.11      www      2766:        my ($role,$perm)=split(/ /,$configline);
                   2767:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      2768:       }
1.11      www      2769:     }
                   2770: }
                   2771: 
                   2772: # -------------------------------------------- Read plain texts for permissions
                   2773: {
                   2774:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   2775: 
                   2776:     while (my $configline=<$config>) {
                   2777:        chomp($configline);
1.160     www      2778:       if ($configline) {
1.11      www      2779:        my ($short,$plain)=split(/:/,$configline);
                   2780:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      2781:       }
1.135     www      2782:     }
                   2783: }
                   2784: 
                   2785: # ---------------------------------------------------------- Read package table
                   2786: {
                   2787:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   2788: 
                   2789:     while (my $configline=<$config>) {
                   2790:        chomp($configline);
                   2791:        my ($short,$plain)=split(/:/,$configline);
1.143     www      2792:        my ($pack,$name)=split(/\&/,$short);
                   2793:        if ($plain ne '') {
                   2794:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   2795:           $packagetab{$short}=$plain; 
1.25      www      2796:        }
1.11      www      2797:     }
                   2798: }
                   2799: 
1.71      www      2800: %metacache=();
1.185     www      2801: 
                   2802: $processmarker=$$.'_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      2803: $dumpcount=0;
1.22      www      2804: 
1.163     harris41 2805: &logtouch();
1.12      www      2806: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      2807: $readit=1;
                   2808: }
1.1       albertel 2809: }
1.179     www      2810: 
1.1       albertel 2811: 1;
1.191     harris41 2812: __END__
                   2813: 
                   2814: =head1 NAME
                   2815: 
                   2816: Apache::lonnet - TCP networking package
                   2817: 
                   2818: =head1 SYNOPSIS
                   2819: 
                   2820: Invoked by other LON-CAPA modules.
                   2821: 
                   2822:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   2823: 
                   2824: =head1 INTRODUCTION
                   2825: 
                   2826: This module provides subroutines which interact with the
                   2827: lonc/lond (TCP) network layer of LON-CAPA.
                   2828: 
                   2829: This is part of the LearningOnline Network with CAPA project
                   2830: described at http://www.lon-capa.org.
                   2831: 
                   2832: =head1 HANDLER SUBROUTINE
                   2833: 
                   2834: There is no handler routine for this module.
                   2835: 
                   2836: =head1 OTHER SUBROUTINES
                   2837: 
                   2838: =over 4
                   2839: 
                   2840: =item *
                   2841: 
                   2842: logtouch() : make sure the logfile, lonnet.log, exists
                   2843: 
                   2844: =item *
                   2845: 
                   2846: logthis() : append message to lonnet.log
                   2847: 
                   2848: =item *
                   2849: 
                   2850: logperm() : append a permanent message to lonnet.perm.log
                   2851: 
                   2852: =item *
                   2853: 
                   2854: subreply() : non-critical communication, called by &reply
                   2855: 
                   2856: =item *
                   2857: 
                   2858: reply() : makes two attempts to pass message; logs refusals and rejections
                   2859: 
                   2860: =item *
                   2861: 
                   2862: reconlonc() : tries to reconnect lonc client processes.
                   2863: 
                   2864: =item *
                   2865: 
                   2866: critical() : passes a critical message to another server; if cannot get
                   2867: through then place message in connection buffer
                   2868: 
                   2869: =item *
                   2870: 
                   2871: appenv(%hash) : read in current user environment, append new environment
                   2872: values to make new user environment
                   2873: 
                   2874: =item *
                   2875: 
                   2876: delenv($varname) : read in current user environment, remove all values
                   2877: beginning with $varname, write new user environment (note: flock is used
                   2878: to prevent conflicting shared read/writes with file)
                   2879: 
                   2880: =item *
                   2881: 
                   2882: spareserver() : find server with least workload from spare.tab
                   2883: 
                   2884: =item *
                   2885: 
                   2886: queryauthenticate($uname,$udom) : try to determine user's current
                   2887: authentication scheme
                   2888: 
                   2889: =item *
                   2890: 
                   2891: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
                   2892: servers (first use the current one)
                   2893: 
                   2894: =item *
                   2895: 
                   2896: homeserver($uname,$udom) : find the homebase for a user from domain's lib
                   2897: servers
                   2898: 
                   2899: =item *
                   2900: 
                   2901: idget($udom,@ids) : find the usernames behind a list of IDs (returns hash:
                   2902: id=>name,id=>name)
                   2903: 
                   2904: =item *
                   2905: 
                   2906: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
                   2907: name=>id,name=>id)
                   2908: 
                   2909: =item *
                   2910: 
                   2911: idput($udom,%ids) : store away a list of names and associated IDs
                   2912: 
                   2913: =item *
                   2914: 
                   2915: usection($domain,$user,$courseid) : output of section name/number or '' for
                   2916: "not in course" and '-1' for "no section"
                   2917: 
                   2918: =item *
                   2919: 
                   2920: userenvironment($domain,$user,$what) : puts out any environment parameter 
                   2921: for a user
                   2922: 
                   2923: =item *
                   2924: 
                   2925: subscribe($fname) : subscribe to a resource, return URL if possible
                   2926: 
                   2927: =item *
                   2928: 
                   2929: repcopy($filename) : replicate file
                   2930: 
                   2931: =item *
                   2932: 
                   2933: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   2934: localhost, posts hash
                   2935: 
                   2936: =item *
                   2937: 
                   2938: log($domain,$name,$home,$message) : write to permanent log for user; use
                   2939: critical subroutine
                   2940: 
                   2941: =item *
                   2942: 
                   2943: flushcourselogs() : flush (save) buffer logs and access logs
                   2944: 
                   2945: =item *
                   2946: 
                   2947: courselog($what) : save message for course in hash
                   2948: 
                   2949: =item *
                   2950: 
                   2951: courseacclog($what) : save message for course using &courselog().  Perform
                   2952: special processing for specific resource types (problems, exams, quizzes, etc).
                   2953: 
                   2954: =item *
                   2955: 
                   2956: countacc($url) : count the number of accesses to a given URL
                   2957: 
                   2958: =item *
                   2959: 
                   2960: sub checkout($symb,$tuname,$tudom,$tcrsid) : check out an item
                   2961: 
                   2962: =item *
                   2963: 
                   2964: sub checkin($token) : check in an item
                   2965: 
                   2966: =item *
                   2967: 
                   2968: sub expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
                   2969: 
                   2970: =item *
                   2971: 
                   2972: devalidate($symb) : devalidate spreadsheets
                   2973: 
                   2974: =item *
                   2975: 
                   2976: hash2str(%hash) : convert a hash into a string complete with escaping and '='
1.204   ! albertel 2977: and '&' separators, supports elements that are arrayrefs and hashrefs
        !          2978: 
        !          2979: =item *
        !          2980: 
        !          2981: hashref2str($hashref) : convert a hashref into a string complete with
        !          2982: escaping and '=' and '&' separators, supports elements that are
        !          2983: arrayrefs and hashrefs
        !          2984: 
        !          2985: =item *
        !          2986: 
        !          2987: arrayref2str($arrayref) : convert an arrayref into a string complete
        !          2988: with escaping and '&' separators, supports elements that are arrayrefs
        !          2989: and hashrefs
        !          2990: 
        !          2991: =item *
        !          2992: 
        !          2993: str2hash($string) : convert string to hash using unescaping and
        !          2994: splitting on '=' and '&', supports elements that are arrayrefs and
        !          2995: hashrefs
1.191     harris41 2996: 
                   2997: =item *
                   2998: 
1.204   ! albertel 2999: str2array($string) : convert string to hash using unescaping and
        !          3000: splitting on '&', supports elements that are arrayrefs and hashrefs
1.191     harris41 3001: 
                   3002: =item *
                   3003: 
                   3004: tmpreset($symb,$namespace,$domain,$stuname) : temporary storage
                   3005: 
                   3006: =item *
                   3007: 
                   3008: tmprestore($symb,$namespace,$domain,$stuname) : temporary restore
                   3009: 
                   3010: =item *
                   3011: 
                   3012: store($storehash,$symb,$namespace,$domain,$stuname) : stores hash permanently
                   3013: for this url; hashref needs to be given and should be a \%hashname; the
                   3014: remaining args aren't required and if they aren't passed or are '' they will
                   3015: be derived from the ENV
                   3016: 
                   3017: =item *
                   3018: 
                   3019: cstore($storehash,$symb,$namespace,$domain,$stuname) : same as store but
                   3020: uses critical subroutine
                   3021: 
                   3022: =item *
                   3023: 
                   3024: restore($symb,$namespace,$domain,$stuname) : returns hash for this symb;
                   3025: all args are optional
                   3026: 
                   3027: =item *
                   3028: 
                   3029: coursedescription($courseid) : course description
                   3030: 
                   3031: =item *
                   3032: 
                   3033: rolesinit($domain,$username,$authhost) : get user privileges
                   3034: 
                   3035: =item *
                   3036: 
                   3037: get($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
                   3038: reference filled in from namesp ($udomain and $uname are optional)
                   3039: 
                   3040: =item *
                   3041: 
                   3042: del($namespace,$storearr,$udomain,$uname) : deletes keys out of array from
                   3043: namesp ($udomain and $uname are optional)
                   3044: 
                   3045: =item *
                   3046: 
1.193     www      3047: dump($namespace,$udomain,$uname,$regexp) : 
                   3048: dumps the complete (or key matching regexp) namespace into a hash
                   3049: ($udomain, $uname and $regexp are optional)
1.191     harris41 3050: 
                   3051: =item *
                   3052: 
                   3053: put($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   3054: ($udomain and $uname are optional)
                   3055: 
                   3056: =item *
                   3057: 
                   3058: cput($namespace,$storehash,$udomain,$uname) : critical put
                   3059: ($udomain and $uname are optional)
                   3060: 
                   3061: =item *
                   3062: 
                   3063: eget($namespace,$storearr,$udomain,$uname) : returns hash with keys from array
                   3064: reference filled in from namesp (encrypts the return communication)
                   3065: ($udomain and $uname are optional)
                   3066: 
                   3067: =item *
                   3068: 
                   3069: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   3070: actions
                   3071:  F: full access
                   3072:  U,I,K: authentication modes (cxx only)
                   3073:  '': forbidden
                   3074:  1: user needs to choose course
                   3075:  2: browse allowed
                   3076: 
                   3077: =item *
                   3078: 
                   3079: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   3080: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   3081: and course level
                   3082: 
                   3083: =item *
                   3084: 
                   3085: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   3086: network of library servers; returns file handle of where SQL and regex results
                   3087: will be stored for query
                   3088: 
                   3089: =item *
                   3090: 
                   3091: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   3092: explanation of a user role term
                   3093: 
                   3094: =item *
                   3095: 
                   3096: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   3097: user for the level given by URL.  Optional start and end dates (leave empty
                   3098: string or zero for "no date")
                   3099: 
                   3100: =item *
                   3101: 
                   3102: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
                   3103: 
                   3104: =item *
                   3105: 
                   3106: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   3107: modify user
                   3108: 
                   3109: =item *
                   3110: 
                   3111: modifystudent($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
                   3112: $end,$start) : modify student
                   3113: 
                   3114: =item *
                   3115: 
                   3116: writecoursepref($courseid,%prefs) : write preferences for a course
                   3117: 
                   3118: =item *
                   3119: 
                   3120: createcourse($udom,$description,$url) : make/modify course
                   3121: 
                   3122: =item *
                   3123: 
                   3124: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   3125: custom role; give a custom role to a user for the level given by URL.  Specify
                   3126: name and domain of role author, and role name
                   3127: 
                   3128: =item *
                   3129: 
                   3130: revokerole($udom,$uname,$url,$role) : revoke a role for url
                   3131: 
                   3132: =item *
                   3133: 
                   3134: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   3135: 
                   3136: =item *
                   3137: 
                   3138: dirlist($uri) : return directory list based on URI
                   3139: 
                   3140: =item *
                   3141: 
                   3142: directcondval($number) : get current value of a condition; reads from a state
                   3143: string
                   3144: 
                   3145: =item *
                   3146: 
                   3147: condval($condidx) : value of condition index based on state
                   3148: 
                   3149: =item *
                   3150: 
                   3151: EXT($varname,$symbparm) : value of a variable
                   3152: 
                   3153: =item *
                   3154: 
                   3155: metadata($uri,$what,$liburi,$prefix,$depthcount) : get metadata; returns the
                   3156: metadata entry for a file; entry='keys', returns a comma separated list of keys
                   3157: 
                   3158: =item *
                   3159: 
                   3160: symblist($mapname,%newhash) : update symbolic storage links
                   3161: 
                   3162: =item *
                   3163: 
                   3164: symbread($filename) : return symbolic list entry (filename argument optional);
                   3165: returns the data handle
                   3166: 
                   3167: =item *
                   3168: 
                   3169: numval($salt) : return random seed value (addend for rndseed)
                   3170: 
                   3171: =item *
                   3172: 
                   3173: rndseed($symb,$courseid,$domain,$username) : create a random sum; returns
                   3174: a random seed, all arguments are optional, if they aren't sent it uses the
                   3175: environment to derive them. Note: if symb isn't sent and it can't get one
                   3176: from &symbread it will use the current time as its return value
                   3177: 
                   3178: =item *
                   3179: 
                   3180: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   3181: unfakeable, receipt
                   3182: 
                   3183: =item *
                   3184: 
                   3185: receipt() : API to ireceipt working off of ENV values; given out to users
                   3186: 
                   3187: =item *
                   3188: 
                   3189: getfile($file) : serves up a file, returns the contents of a file or -1;
                   3190: replicates and subscribes to the file
                   3191: 
                   3192: =item *
                   3193: 
                   3194: filelocation($dir,$file) : returns file system location of a file based on URI;
                   3195: meant to be "fairly clean" absolute reference
                   3196: 
                   3197: =item *
                   3198: 
                   3199: hreflocation($dir,$file) : returns file system location or a URL; same as
                   3200: filelocation except for hrefs
                   3201: 
                   3202: =item *
                   3203: 
                   3204: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   3205: 
                   3206: =item *
                   3207: 
                   3208: escape() : unpack non-word characters into CGI-compatible hex codes
                   3209: 
                   3210: =item *
                   3211: 
                   3212: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   3213: 
                   3214: =item *
                   3215: 
                   3216: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   3217: as a PerlChildExitHandler
                   3218: 
                   3219: =back
                   3220: 
                   3221: =cut

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