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

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

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