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

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

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