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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.412   ! www         4: # $Id: lonnet.pm,v 1.411 2003/09/11 07:57:03 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
                     29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
                     30: # 11/8,11/16,11/18,11/22,11/23,12/22,
                     31: # 01/06,01/13,02/24,02/28,02/29,
                     32: # 03/01,03/02,03/06,03/07,03/13,
                     33: # 04/05,05/29,05/31,06/01,
                     34: # 06/05,06/26 Gerd Kortemeyer
                     35: # 06/26 Ben Tyszka
                     36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
                     37: # 08/14 Ben Tyszka
                     38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
                     39: # 10/04 Gerd Kortemeyer
                     40: # 10/04 Guy Albertelli
                     41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
                     42: # 10/30,10/31,
                     43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
                     44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
                     45: # 05/01/01 Guy Albertelli
                     46: # 05/01,06/01,09/01 Gerd Kortemeyer
                     47: # 09/01 Guy Albertelli
                     48: # 09/01,10/01,11/01 Gerd Kortemeyer
                     49: # YEAR=2001
                     50: # 3/2 Gerd Kortemeyer
                     51: # 3/19,3/20 Gerd Kortemeyer
                     52: # 5/26,5/28 Gerd Kortemeyer
                     53: # 5/30 H. K. Ng
                     54: # 6/1 Gerd Kortemeyer
                     55: # July Guy Albertelli
                     56: # 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,
                     57: # 10/2 Gerd Kortemeyer
1.179     www        58: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
1.182     matthew    59: # 12/5 Matthew Hall
1.184     www        60: # 12/5 Guy Albertelli
1.190     www        61: # 12/6,12/7,12/12 Gerd Kortemeyer
1.195     www        62: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
1.196     www        63: # YEAR=2002
1.200     www        64: # 1/4,2/4,2/7 Gerd Kortemeyer
1.171     www        65: #
1.169     harris41   66: ###
                     67: 
1.1       albertel   68: package Apache::lonnet;
                     69: 
                     70: use strict;
                     71: use Apache::File;
1.8       www        72: use LWP::UserAgent();
1.15      www        73: use HTTP::Headers;
1.11      www        74: use vars 
1.300     albertel   75: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
1.301     www        76:    %libserv %pr %prp %metacache %packagetab %titlecache 
1.349     www        77:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
1.352     www        78:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
1.403     www        79:    %domaindescription %domain_auth_def %domain_auth_arg_def 
                     80:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir);
                     81: 
1.1       albertel   82: use IO::Socket;
1.31      www        83: use GDBM_File;
1.8       www        84: use Apache::Constants qw(:common :http);
1.208     albertel   85: use HTML::LCParser;
1.88      www        86: use Fcntl qw(:flock);
1.294     matthew    87: use Apache::loncoursedata;
                     88: 
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.311     matthew   143:         #sleep 5; 
                    144:         #$answer=subreply($cmd,$server);
                    145:         #if ($answer eq 'con_lost') {
1.233     albertel  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=
1.305     www       216:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    217:             $dumpcount++;
1.1       albertel  218:             {
                    219:              my $dfh;
                    220:              if ($dfh=Apache::File->new(">$dfilename")) {
1.7       www       221:                 print $dfh "$cmd\n";
1.1       albertel  222: 	     }
                    223:             }
                    224:             sleep 2;
                    225:             my $wcmd='';
                    226:             {
                    227: 	     my $dfh;
                    228:              if ($dfh=Apache::File->new("$dfilename")) {
                    229:                 $wcmd=<$dfh>;
                    230: 	     }
                    231:             }
                    232:             chomp($wcmd);
1.7       www       233:             if ($wcmd eq $cmd) {
1.12      www       234: 		&logthis("<font color=blue>WARNING: ".
                    235:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  236:                 &logperm("D:$server:$cmd");
                    237: 	        return 'con_delayed';
                    238:             } else {
1.12      www       239:                 &logthis("<font color=red>CRITICAL:"
                    240:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  241:                 &logperm("F:$server:$cmd");
                    242:                 return 'con_failed';
                    243:             }
                    244:         }
                    245:     }
                    246:     return $answer;
1.405     albertel  247: }
                    248: 
1.412   ! www       249: #
1.405     albertel  250: # -------------- Remove all key from the env that start witha lowercase letter
1.412   ! www       251: #                (Which is always a lon-capa value)
        !           252: 
1.405     albertel  253: sub cleanenv {
1.412   ! www       254: #    unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; }
        !           255: #    unless (&Apache::exists_config_define("MODPERL2")) { return; }
1.405     albertel  256:     foreach my $key (keys(%ENV)) {
                    257: 	if ($key =~ /^[a-z]/) {
                    258: 	    delete($ENV{$key});
                    259: 	}
                    260:     }
1.374     www       261: }
                    262:  
                    263: # ------------------------------------------- Transfer profile into environment
                    264: 
                    265: sub transfer_profile_to_env {
                    266:     my ($lonidsdir,$handle)=@_;
                    267:     my @profile;
                    268:     {
                    269: 	my $idf=Apache::File->new("$lonidsdir/$handle.id");
                    270: 	flock($idf,LOCK_SH);
                    271: 	@profile=<$idf>;
                    272: 	$idf->close();
                    273:     }
                    274:     my $envi;
                    275:     for ($envi=0;$envi<=$#profile;$envi++) {
                    276: 	chomp($profile[$envi]);
                    277: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
                    278: 	$ENV{$envname} = $envvalue;
                    279:     }
                    280:     $ENV{'user.environment'} = "$lonidsdir/$handle.id";
1.1       albertel  281: }
                    282: 
1.5       www       283: # ---------------------------------------------------------- Append Environment
                    284: 
                    285: sub appenv {
1.6       www       286:     my %newenv=@_;
1.191     harris41  287:     foreach (keys %newenv) {
1.35      www       288: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    289:             &logthis("<font color=blue>WARNING: ".
1.151     www       290:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    291:                 .'</font>');
1.35      www       292: 	    delete($newenv{$_});
                    293:         } else {
                    294:             $ENV{$_}=$newenv{$_};
                    295:         }
1.191     harris41  296:     }
1.95      www       297: 
                    298:     my $lockfh;
                    299:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       300:        return 'error: '.$!;
1.95      www       301:     }
                    302:     unless (flock($lockfh,LOCK_EX)) {
                    303:          &logthis("<font color=blue>WARNING: ".
                    304:                   'Could not obtain exclusive lock in appenv: '.$!);
                    305:          $lockfh->close();
                    306:          return 'error: '.$!;
                    307:     }
                    308: 
1.6       www       309:     my @oldenv;
                    310:     {
                    311:      my $fh;
                    312:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
1.97      www       313: 	return 'error: '.$!;
1.6       www       314:      }
                    315:      @oldenv=<$fh>;
1.89      www       316:      $fh->close();
1.6       www       317:     }
                    318:     for (my $i=0; $i<=$#oldenv; $i++) {
                    319:         chomp($oldenv[$i]);
1.9       www       320:         if ($oldenv[$i] ne '') {
                    321:            my ($name,$value)=split(/=/,$oldenv[$i]);
1.24      www       322:            unless (defined($newenv{$name})) {
                    323: 	      $newenv{$name}=$value;
                    324: 	   }
1.9       www       325:         }
1.6       www       326:     }
                    327:     {
                    328:      my $fh;
                    329:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    330: 	return 'error';
                    331:      }
                    332:      my $newname;
1.93      www       333:      foreach $newname (keys %newenv) {
1.6       www       334: 	 print $fh "$newname=$newenv{$newname}\n";
                    335:      }
1.86      albertel  336:      $fh->close();
1.56      www       337:     }
1.95      www       338: 
                    339:     $lockfh->close();
1.56      www       340:     return 'ok';
                    341: }
                    342: # ----------------------------------------------------- Delete from Environment
                    343: 
                    344: sub delenv {
                    345:     my $delthis=shift;
                    346:     my %newenv=();
                    347:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    348:         &logthis("<font color=blue>WARNING: ".
                    349:                 "Attempt to delete from environment ".$delthis);
                    350:         return 'error';
                    351:     }
                    352:     my @oldenv;
                    353:     {
                    354:      my $fh;
                    355:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
                    356: 	return 'error';
                    357:      }
1.89      www       358:      unless (flock($fh,LOCK_SH)) {
                    359:          &logthis("<font color=blue>WARNING: ".
                    360:                   'Could not obtain shared lock in delenv: '.$!);
                    361:          $fh->close();
                    362:          return 'error: '.$!;
                    363:      }
1.56      www       364:      @oldenv=<$fh>;
1.89      www       365:      $fh->close();
1.56      www       366:     }
                    367:     {
                    368:      my $fh;
                    369:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
                    370: 	return 'error';
                    371:      }
1.89      www       372:      unless (flock($fh,LOCK_EX)) {
                    373:          &logthis("<font color=blue>WARNING: ".
                    374:                   'Could not obtain exclusive lock in delenv: '.$!);
                    375:          $fh->close();
                    376:          return 'error: '.$!;
                    377:      }
1.191     harris41  378:      foreach (@oldenv) {
1.56      www       379: 	 unless ($_=~/^$delthis/) { print $fh $_; }
1.191     harris41  380:      }
1.87      www       381:      $fh->close();
1.5       www       382:     }
                    383:     return 'ok';
1.369     albertel  384: }
                    385: 
                    386: # ------------------------------------------ Find out current server userload
                    387: # there is a copy in lond
                    388: sub userload {
                    389:     my $numusers=0;
                    390:     {
                    391: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    392: 	my $filename;
                    393: 	my $curtime=time;
                    394: 	while ($filename=readdir(LONIDS)) {
                    395: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  396: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
                    397: 	    if ($curtime-$mtime < 3600) { $numusers++; }
1.369     albertel  398: 	}
                    399: 	closedir(LONIDS);
                    400:     }
                    401:     my $userloadpercent=0;
                    402:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    403:     if ($maxuserload) {
1.371     albertel  404: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  405:     }
1.372     albertel  406:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  407:     return $userloadpercent;
1.283     www       408: }
                    409: 
                    410: # ------------------------------------------ Fight off request when overloaded
                    411: 
                    412: sub overloaderror {
                    413:     my ($r,$checkserver)=@_;
                    414:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    415:     my $loadavg;
                    416:     if ($checkserver eq $perlvar{'lonHostID'}) {
                    417:        my $loadfile=Apache::File->new('/proc/loadavg');
                    418:        $loadavg=<$loadfile>;
                    419:        $loadavg =~ s/\s.*//g;
1.285     matthew   420:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.283     www       421:     } else {
                    422:        $loadavg=&reply('load',$checkserver);
                    423:     }
1.285     matthew   424:     my $overload=$loadavg-100;
1.283     www       425:     if ($overload>0) {
1.285     matthew   426: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       427:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
                    428:         return 413;
                    429:     }    
                    430:     return '';
1.5       www       431: }
1.1       albertel  432: 
                    433: # ------------------------------ Find server with least workload from spare.tab
1.11      www       434: 
1.1       albertel  435: sub spareserver {
1.370     albertel  436:     my ($loadpercent,$userloadpercent) = @_;
1.1       albertel  437:     my $tryserver;
                    438:     my $spareserver='';
1.370     albertel  439:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    440:     my $lowestserver=$loadpercent > $userloadpercent?
                    441: 	             $loadpercent :  $userloadpercent;
1.1       albertel  442:     foreach $tryserver (keys %spareid) {
1.411     albertel  443: 	my $loadans=reply('load',$tryserver);
                    444: 	my $userloadans=reply('userload',$tryserver);
                    445: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    446: 	    next; #didn't get a number from the server
                    447: 	}
                    448: 	my $answer;
                    449: 	if ($loadans =~ /\d/) {
                    450: 	    if ($userloadans =~ /\d/) {
                    451: 		#both are numbers, pick the bigger one
                    452: 		$answer=$loadans > $userloadans?
                    453: 		    $loadans :  $userloadans;
                    454: 	    } else {
                    455: 		$answer = $loadans;
                    456: 	    }
                    457: 	} else {
                    458: 	    $answer = $userloadans;
                    459: 	}
                    460: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    461: 	    $spareserver="http://$hostname{$tryserver}";
                    462: 	    $lowestserver=$answer;
                    463: 	}
1.370     albertel  464:     }
1.1       albertel  465:     return $spareserver;
1.202     matthew   466: }
                    467: 
                    468: # --------------------------------------------- Try to change a user's password
                    469: 
                    470: sub changepass {
                    471:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    472:     $currentpass = &escape($currentpass);
                    473:     $newpass     = &escape($newpass);
                    474:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    475: 		       $server);
                    476:     if (! $answer) {
                    477: 	&logthis("No reply on password change request to $server ".
                    478: 		 "by $uname in domain $udom.");
                    479:     } elsif ($answer =~ "^ok") {
                    480:         &logthis("$uname in $udom successfully changed their password ".
                    481: 		 "on $server.");
                    482:     } elsif ($answer =~ "^pwchange_failure") {
                    483: 	&logthis("$uname in $udom was unable to change their password ".
                    484: 		 "on $server.  The action was blocked by either lcpasswd ".
                    485: 		 "or pwchange");
                    486:     } elsif ($answer =~ "^non_authorized") {
                    487:         &logthis("$uname in $udom did not get their password correct when ".
                    488: 		 "attempting to change it on $server.");
                    489:     } elsif ($answer =~ "^auth_mode_error") {
                    490:         &logthis("$uname in $udom attempted to change their password despite ".
                    491: 		 "not being locally or internally authenticated on $server.");
                    492:     } elsif ($answer =~ "^unknown_user") {
                    493:         &logthis("$uname in $udom attempted to change their password ".
                    494: 		 "on $server but were unable to because $server is not ".
                    495: 		 "their home server.");
                    496:     } elsif ($answer =~ "^refused") {
                    497: 	&logthis("$server refused to change $uname in $udom password because ".
                    498: 		 "it was sent an unencrypted request to change the password.");
                    499:     }
                    500:     return $answer;
1.1       albertel  501: }
                    502: 
1.169     harris41  503: # ----------------------- Try to determine user's current authentication scheme
                    504: 
                    505: sub queryauthenticate {
                    506:     my ($uname,$udom)=@_;
                    507:     if (($perlvar{'lonRole'} eq 'library') && 
                    508:         ($udom eq $perlvar{'lonDefDomain'})) {
                    509: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
                    510: 			 $perlvar{'lonHostID'});
                    511: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    512: 	    if (length($answer)) {
                    513: 		return $answer;
                    514: 	    }
                    515: 	    else {
                    516: 	&logthis("User $uname at $udom lacks an authentication mechanism");
                    517: 		return 'no_host';
                    518: 	    }
                    519: 	}
                    520:     }
                    521: 
                    522:     my $tryserver;
                    523:     foreach $tryserver (keys %libserv) {
                    524: 	if ($hostdom{$tryserver} eq $udom) {
                    525:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
                    526: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
                    527: 	       if (length($answer)) {
                    528: 		   return $answer;
                    529: 	       }
                    530: 	       else {
                    531: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
                    532: 		   return 'no_host';
                    533: 	       }
                    534: 	   }
                    535:        }
                    536:     }
                    537:     &logthis("User $uname at $udom lacks an authentication mechanism");    
                    538:     return 'no_host';
                    539: }
                    540: 
1.1       albertel  541: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       542: 
1.1       albertel  543: sub authenticate {
                    544:     my ($uname,$upass,$udom)=@_;
1.12      www       545:     $upass=escape($upass);
1.199     www       546:     $uname=~s/\W//g;
1.1       albertel  547:     if (($perlvar{'lonRole'} eq 'library') && 
                    548:         ($udom eq $perlvar{'lonDefDomain'})) {
1.3       www       549:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2       www       550:         if ($answer =~ /authorized/) {
1.9       www       551:               if ($answer eq 'authorized') {
                    552:                  &logthis("User $uname at $udom authorized by local server"); 
                    553:                  return $perlvar{'lonHostID'}; 
                    554:               }
                    555:               if ($answer eq 'non_authorized') {
                    556:                  &logthis("User $uname at $udom rejected by local server"); 
                    557:                  return 'no_host'; 
                    558:               }
1.2       www       559: 	}
1.1       albertel  560:     }
                    561: 
                    562:     my $tryserver;
                    563:     foreach $tryserver (keys %libserv) {
                    564: 	if ($hostdom{$tryserver} eq $udom) {
1.10      www       565:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1       albertel  566:            if ($answer =~ /authorized/) {
1.9       www       567:               if ($answer eq 'authorized') {
                    568:                  &logthis("User $uname at $udom authorized by $tryserver"); 
                    569:                  return $tryserver; 
                    570:               }
                    571:               if ($answer eq 'non_authorized') {
                    572:                  &logthis("User $uname at $udom rejected by $tryserver");
                    573:                  return 'no_host';
                    574:               } 
1.1       albertel  575: 	   }
                    576:        }
1.9       www       577:     }
                    578:     &logthis("User $uname at $udom could not be authenticated");    
1.1       albertel  579:     return 'no_host';
                    580: }
                    581: 
                    582: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       583: 
1.1       albertel  584: sub homeserver {
1.230     stredwic  585:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  586:     my $index="$uname:$udom";
1.221     matthew   587:     if ($homecache{$index}) { 
                    588:         return "$homecache{$index}"; 
                    589:     }
1.1       albertel  590:     my $tryserver;
                    591:     foreach $tryserver (keys %libserv) {
1.230     stredwic  592:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  593: 		 exists($badServerCache{$tryserver}));
1.1       albertel  594: 	if ($hostdom{$tryserver} eq $udom) {
                    595:            my $answer=reply("home:$udom:$uname",$tryserver);
                    596:            if ($answer eq 'found') { 
1.221     matthew   597:               $homecache{$index}=$tryserver;
1.1       albertel  598:               return $tryserver; 
1.231     stredwic  599:            } elsif ($answer eq 'no_host') {
                    600: 	       $badServerCache{$tryserver}=1;
1.221     matthew   601:            }
1.1       albertel  602:        }
                    603:     }    
                    604:     return 'no_host';
1.70      www       605: }
                    606: 
                    607: # ------------------------------------- Find the usernames behind a list of IDs
                    608: 
                    609: sub idget {
                    610:     my ($udom,@ids)=@_;
                    611:     my %returnhash=();
                    612:     
                    613:     my $tryserver;
                    614:     foreach $tryserver (keys %libserv) {
                    615:        if ($hostdom{$tryserver} eq $udom) {
                    616: 	  my $idlist=join('&',@ids);
                    617:           $idlist=~tr/A-Z/a-z/; 
                    618: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    619:           my @answer=();
1.76      www       620:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       621: 	      @answer=split(/\&/,$reply);
                    622:           }                    ;
                    623:           my $i;
                    624:           for ($i=0;$i<=$#ids;$i++) {
                    625:               if ($answer[$i]) {
                    626: 		  $returnhash{$ids[$i]}=$answer[$i];
                    627:               } 
                    628:           }
                    629:        }
                    630:     }    
                    631:     return %returnhash;
                    632: }
                    633: 
                    634: # ------------------------------------- Find the IDs behind a list of usernames
                    635: 
                    636: sub idrget {
                    637:     my ($udom,@unames)=@_;
                    638:     my %returnhash=();
1.191     harris41  639:     foreach (@unames) {
1.70      www       640:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  641:     }
1.70      www       642:     return %returnhash;
                    643: }
                    644: 
                    645: # ------------------------------- Store away a list of names and associated IDs
                    646: 
                    647: sub idput {
                    648:     my ($udom,%ids)=@_;
                    649:     my %servers=();
1.191     harris41  650:     foreach (keys %ids) {
1.70      www       651:         my $uhom=&homeserver($_,$udom);
                    652:         if ($uhom ne 'no_host') {
                    653:             my $id=&escape($ids{$_});
                    654:             $id=~tr/A-Z/a-z/;
                    655:             my $unam=&escape($_);
                    656: 	    if ($servers{$uhom}) {
                    657: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    658:             } else {
                    659:                 $servers{$uhom}=$id.'='.$unam;
                    660:             }
                    661:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
                    662:         }
1.191     harris41  663:     }
                    664:     foreach (keys %servers) {
1.70      www       665:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  666:     }
1.344     www       667: }
                    668: 
                    669: # --------------------------------------------------- Assign a key to a student
                    670: 
                    671: sub assign_access_key {
1.364     www       672: #
                    673: # a valid key looks like uname:udom#comments
                    674: # comments are being appended
                    675: #
                    676:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1.344     www       677:     $cdom=
                    678:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    679:     $cnum=
                    680:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    681:     $udom=$ENV{'user.name'} unless (defined($udom));
                    682:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       683:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       684:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
                    685:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
                    686:                                                   # assigned to this person
                    687:                                                   # - this should not happen,
1.345     www       688:                                                   # unless something went wrong
                    689:                                                   # the first time around
                    690: # ready to assign
1.364     www       691:         $logentry=$1.'; '.$logentry;
                    692:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
                    693:                                                  $cdom,$cnum) eq 'ok') {
1.345     www       694: # key now belongs to user
1.346     www       695: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       696:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    697:                 &appenv('environment.'.$envkey => $ckey);
                    698:                 return 'ok';
                    699:             } else {
                    700:                 return 
                    701:   'error: Count not permanently assign key, will need to be re-entered later.';
                    702: 	    }
                    703:         } else {
                    704:             return 'error: Could not assign key, try again later.';
                    705:         }
1.364     www       706:     } elsif (!$existing{$ckey}) {
1.345     www       707: # the key does not exist
                    708: 	return 'error: The key does not exist';
                    709:     } else {
                    710: # the key is somebody else's
                    711: 	return 'error: The key is already in use';
                    712:     }
1.344     www       713: }
                    714: 
1.364     www       715: # ------------------------------------------ put an additional comment on a key
                    716: 
                    717: sub comment_access_key {
                    718: #
                    719: # a valid key looks like uname:udom#comments
                    720: # comments are being appended
                    721: #
                    722:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    723:     $cdom=
                    724:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    725:     $cnum=
                    726:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    727:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    728:     if ($existing{$ckey}) {
                    729:         $existing{$ckey}.='; '.$logentry;
                    730: # ready to assign
1.367     www       731:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       732:                                                  $cdom,$cnum) eq 'ok') {
                    733: 	    return 'ok';
                    734:         } else {
                    735: 	    return 'error: Count not store comment.';
                    736:         }
                    737:     } else {
                    738: # the key does not exist
                    739: 	return 'error: The key does not exist';
                    740:     }
                    741: }
                    742: 
1.344     www       743: # ------------------------------------------------------ Generate a set of keys
                    744: 
                    745: sub generate_access_keys {
1.364     www       746:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       747:     $cdom=
                    748:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    749:     $cnum=
                    750:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       751:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       752:     unless (($cdom) && ($cnum)) { return 0; }
                    753:     if ($number>10000) { return 0; }
                    754:     sleep(2); # make sure don't get same seed twice
                    755:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    756:     my $total=0;
                    757:     for (my $i=1;$i<=$number;$i++) {
                    758:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    759:                   sprintf("%lx",int(100000*rand)).'-'.
                    760:                   sprintf("%lx",int(100000*rand));
                    761:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    762:        $newkey=~s/0/h/g; # and also 0 and O
                    763:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    764:        if ($existing{$newkey}) {
                    765:            $i--;
                    766:        } else {
1.364     www       767: 	  if (&put('accesskeys',
                    768:               { $newkey => '# generated '.localtime().
                    769:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
                    770:                            '; '.$logentry },
                    771: 		   $cdom,$cnum) eq 'ok') {
1.344     www       772:               $total++;
                    773: 	  }
                    774:        }
                    775:     }
                    776:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                    777:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    778:     return $total;
                    779: }
                    780: 
                    781: # ------------------------------------------------------- Validate an accesskey
                    782: 
                    783: sub validate_access_key {
                    784:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    785:     $cdom=
                    786:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
                    787:     $cnum=
                    788:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
                    789:     $udom=$ENV{'user.name'} unless (defined($udom));
                    790:     $uname=$ENV{'user.domain'} unless (defined($uname));
1.345     www       791:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364     www       792:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
1.70      www       793: }
                    794: 
                    795: # ------------------------------------- Find the section of student in a course
1.298     matthew   796: 
                    797: sub getsection {
                    798:     my ($udom,$unam,$courseid)=@_;
                    799:     $courseid=~s/\_/\//g;
                    800:     $courseid=~s/^(\w)/\/$1/;
                    801:     my %Pending; 
                    802:     my %Expired;
                    803:     #
                    804:     # Each role can either have not started yet (pending), be active, 
                    805:     #    or have expired.
                    806:     #
                    807:     # If there is an active role, we are done.
                    808:     #
                    809:     # If there is more than one role which has not started yet, 
                    810:     #     choose the one which will start sooner
                    811:     # If there is one role which has not started yet, return it.
                    812:     #
                    813:     # If there is more than one expired role, choose the one which ended last.
                    814:     # If there is a role which has expired, return it.
                    815:     #
                    816:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    817:                         &homeserver($unam,$udom)))) {
                    818:         my ($key,$value)=split(/\=/,$_);
                    819:         $key=&unescape($key);
                    820:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
                    821:         my $section=$1;
                    822:         if ($key eq $courseid.'_st') { $section=''; }
                    823:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    824:         my $now=time;
                    825:         if (defined($end) && ($now > $end)) {
                    826:             $Expired{$end}=$section;
                    827:             next;
                    828:         }
                    829:         if (defined($start) && ($now < $start)) {
                    830:             $Pending{$start}=$section;
                    831:             next;
                    832:         }
                    833:         return $section;
                    834:     }
                    835:     #
                    836:     # Presumedly there will be few matching roles from the above
                    837:     # loop and the sorting time will be negligible.
                    838:     if (scalar(keys(%Pending))) {
                    839:         my ($time) = sort {$a <=> $b} keys(%Pending);
                    840:         return $Pending{$time};
                    841:     } 
                    842:     if (scalar(keys(%Expired))) {
                    843:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    844:         my $time = pop(@sorted);
                    845:         return $Expired{$time};
                    846:     }
                    847:     return '-1';
                    848: }
1.70      www       849: 
                    850: sub usection {
                    851:     my ($udom,$unam,$courseid)=@_;
                    852:     $courseid=~s/\_/\//g;
                    853:     $courseid=~s/^(\w)/\/$1/;
1.191     harris41  854:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    855:                         &homeserver($unam,$udom)))) {
1.70      www       856:         my ($key,$value)=split(/\=/,$_);
                    857:         $key=&unescape($key);
                    858:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
                    859:             my $section=$1;
                    860:             if ($key eq $courseid.'_st') { $section=''; }
                    861: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    862:             my $now=time;
                    863:             my $notactive=0;
                    864:             if ($start) {
                    865: 		if ($now<$start) { $notactive=1; }
                    866:             }
                    867:             if ($end) {
                    868:                 if ($now>$end) { $notactive=1; }
                    869:             } 
                    870:             unless ($notactive) { return $section; }
                    871:         }
1.191     harris41  872:     }
1.70      www       873:     return '-1';
                    874: }
                    875: 
                    876: # ------------------------------------- Read an entry from a user's environment
                    877: 
                    878: sub userenvironment {
                    879:     my ($udom,$unam,@what)=@_;
                    880:     my %returnhash=();
                    881:     my @answer=split(/\&/,
                    882:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    883:                       &homeserver($unam,$udom)));
                    884:     my $i;
                    885:     for ($i=0;$i<=$#what;$i++) {
                    886: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    887:     }
                    888:     return %returnhash;
1.1       albertel  889: }
                    890: 
1.263     www       891: # -------------------------------------------------------------------- New chat
                    892: 
                    893: sub chatsend {
                    894:     my ($newentry,$anon)=@_;
                    895:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                    896:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                    897:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                    898:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
                    899: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
                    900: 		   &escape($newentry)),$chome);
1.292     www       901: }
                    902: 
                    903: # ------------------------------------------ Find current version of a resource
                    904: 
                    905: sub getversion {
                    906:     my $fname=&clutter(shift);
                    907:     unless ($fname=~/^\/res\//) { return -1; }
                    908:     return &currentversion(&filelocation('',$fname));
                    909: }
                    910: 
                    911: sub currentversion {
                    912:     my $fname=shift;
                    913:     my $author=$fname;
                    914:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    915:     my ($udom,$uname)=split(/\//,$author);
                    916:     my $home=homeserver($uname,$udom);
                    917:     if ($home eq 'no_host') { 
                    918:         return -1; 
                    919:     }
                    920:     my $answer=reply("currentversion:$fname",$home);
                    921:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    922: 	return -1;
                    923:     }
                    924:     return $answer;
1.263     www       925: }
                    926: 
1.1       albertel  927: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       928: 
1.1       albertel  929: sub subscribe {
                    930:     my $fname=shift;
1.312     www       931:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.1       albertel  932:     my $author=$fname;
                    933:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    934:     my ($udom,$uname)=split(/\//,$author);
                    935:     my $home=homeserver($uname,$udom);
1.335     albertel  936:     if ($home eq 'no_host') {
                    937:         return 'not_found';
1.1       albertel  938:     }
                    939:     my $answer=reply("sub:$fname",$home);
1.64      www       940:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    941: 	$answer.=' by '.$home;
                    942:     }
1.1       albertel  943:     return $answer;
                    944: }
                    945:     
1.8       www       946: # -------------------------------------------------------------- Replicate file
                    947: 
                    948: sub repcopy {
                    949:     my $filename=shift;
1.23      www       950:     $filename=~s/\/+/\//g;
1.214     www       951:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8       www       952:     my $transname="$filename.in.transfer";
1.17      www       953:     if ((-e $filename) || (-e $transname)) { return OK; }
1.8       www       954:     my $remoteurl=subscribe($filename);
1.64      www       955:     if ($remoteurl =~ /^con_lost by/) {
                    956: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       957:            return HTTP_SERVICE_UNAVAILABLE;
                    958:     } elsif ($remoteurl eq 'not_found') {
                    959: 	   &logthis("Subscribe returned not_found: $filename");
                    960: 	   return HTTP_NOT_FOUND;
1.64      www       961:     } elsif ($remoteurl =~ /^rejected by/) {
                    962: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.8       www       963:            return FORBIDDEN;
1.20      www       964:     } elsif ($remoteurl eq 'directory') {
                    965:            return OK;
1.8       www       966:     } else {
1.290     www       967:         my $author=$filename;
                    968:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    969:         my ($udom,$uname)=split(/\//,$author);
                    970:         my $home=homeserver($uname,$udom);
                    971:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www       972:            my @parts=split(/\//,$filename);
                    973:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                    974:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                    975:                &logthis("Malconfiguration for replication: $filename");
                    976: 	       return HTTP_BAD_REQUEST;
                    977:            }
                    978:            my $count;
                    979:            for ($count=5;$count<$#parts;$count++) {
                    980:                $path.="/$parts[$count]";
                    981:                if ((-e $path)!=1) {
                    982: 		   mkdir($path,0777);
                    983:                }
                    984:            }
                    985:            my $ua=new LWP::UserAgent;
                    986:            my $request=new HTTP::Request('GET',"$remoteurl");
                    987:            my $response=$ua->request($request,$transname);
                    988:            if ($response->is_error()) {
                    989: 	       unlink($transname);
                    990:                my $message=$response->status_line;
1.12      www       991:                &logthis("<font color=blue>WARNING:"
                    992:                        ." LWP get: $message: $filename</font>");
1.8       www       993:                return HTTP_SERVICE_UNAVAILABLE;
                    994:            } else {
1.16      www       995: 	       if ($remoteurl!~/\.meta$/) {
                    996:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                    997:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                    998:                   if ($mresponse->is_error()) {
                    999: 		      unlink($filename.'.meta');
                   1000:                       &logthis(
                   1001:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                   1002:                   }
                   1003: 	       }
1.8       www      1004:                rename($transname,$filename);
                   1005:                return OK;
                   1006:            }
1.290     www      1007:        }
1.8       www      1008:     }
1.330     www      1009: }
                   1010: 
                   1011: # ------------------------------------------------ Get server side include body
                   1012: sub ssi_body {
1.381     albertel 1013:     my ($filelink,%form)=@_;
1.330     www      1014:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1015:                                      &ssi($filelink,%form));
1.330     www      1016:     $output=~s/^.*\<body[^\>]*\>//si;
                   1017:     $output=~s/\<\/body\s*\>.*$//si;
1.331     www      1018:     $output=~
                   1019:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
1.330     www      1020:     return $output;
1.8       www      1021: }
                   1022: 
1.15      www      1023: # --------------------------------------------------------- Server Side Include
                   1024: 
                   1025: sub ssi {
                   1026: 
1.23      www      1027:     my ($fn,%form)=@_;
1.15      www      1028: 
                   1029:     my $ua=new LWP::UserAgent;
1.23      www      1030:     
                   1031:     my $request;
                   1032:     
                   1033:     if (%form) {
                   1034:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1035:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1036:     } else {
                   1037:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1038:     }
                   1039: 
1.15      www      1040:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1041:     my $response=$ua->request($request);
                   1042: 
1.324     www      1043:     return $response->content;
                   1044: }
                   1045: 
                   1046: sub externalssi {
                   1047:     my ($url)=@_;
                   1048:     my $ua=new LWP::UserAgent;
                   1049:     my $request=new HTTP::Request('GET',$url);
                   1050:     my $response=$ua->request($request);
1.15      www      1051:     return $response->content;
                   1052: }
1.254     www      1053: 
                   1054: # ------- Add a token to a remote URI's query string to vouch for access rights
                   1055: 
                   1056: sub tokenwrapper {
                   1057:     my $uri=shift;
1.259     www      1058:     $uri=~s/^http\:\/\/([^\/]+)//;
                   1059:     $uri=~s/^\///;
                   1060:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
                   1061:     my $token=$1;
                   1062:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
                   1063: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
                   1064:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
1.304     www      1065:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   1066:                                '&tokenissued='.$perlvar{'lonHostID'};
1.259     www      1067:     } else {
                   1068: 	return '/adm/notfound.html';
                   1069:     }
1.254     www      1070: }
                   1071:     
1.257     www      1072: # --------------- Take an uploaded file and put it into the userfiles directory
1.259     www      1073: # input: name of form element, coursedoc=1 means this is for the course
1.257     www      1074: # output: url of file in userspace
                   1075: 
                   1076: sub userfileupload {
1.259     www      1077:     my ($formname,$coursedoc)=@_;
1.257     www      1078:     my $fname=$ENV{'form.'.$formname.'.filename'};
1.315     www      1079: # Replace Windows backslashes by forward slashes
1.257     www      1080:     $fname=~s/\\/\//g;
1.315     www      1081: # Get rid of everything but the actual filename
1.257     www      1082:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1083: # Replace spaces by underscores
                   1084:     $fname=~s/\s+/\_/g;
                   1085: # Replace all other weird characters by nothing
1.317     www      1086:     $fname=~s/[^\w\.\-]//g;
1.315     www      1087: # See if there is anything left
1.257     www      1088:     unless ($fname) { return 'error: no uploaded file'; }
                   1089:     chop($ENV{'form.'.$formname});
1.258     www      1090: # Create the directory if not present
1.259     www      1091:     my $docuname='';
                   1092:     my $docudom='';
                   1093:     my $docuhome='';
                   1094:     if ($coursedoc) {
                   1095: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1096: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1097: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
                   1098:     } else {
                   1099:         $docuname=$ENV{'user.name'};
                   1100:         $docudom=$ENV{'user.domain'};
                   1101:         $docuhome=$ENV{'user.home'};
                   1102:     }
1.271     www      1103:     return 
                   1104:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
                   1105: }
                   1106: 
                   1107: sub finishuserfileupload {
                   1108:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1.259     www      1109:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1110:     my $filepath=$perlvar{'lonDocRoot'};
1.259     www      1111:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1112:     my $count;
                   1113:     for ($count=4;$count<=$#parts;$count++) {
                   1114:         $filepath.="/$parts[$count]";
                   1115:         if ((-e $filepath)!=1) {
                   1116: 	    mkdir($filepath,0777);
                   1117:         }
                   1118:     }
                   1119: # Save the file
                   1120:     {
                   1121:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
                   1122:        print $fh $ENV{'form.'.$formname};
                   1123:     }
1.259     www      1124: # Notify homeserver to grep it
                   1125: #
1.295     www      1126:     
                   1127:     my $fetchresult= 
                   1128:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
                   1129:     if ($fetchresult eq 'ok') {
1.259     www      1130: #
1.258     www      1131: # Return the URL to it
1.263     www      1132:         return '/uploaded/'.$path.$fname;
                   1133:     } else {
1.295     www      1134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
                   1135:          ' to host '.$docuhome.': '.$fetchresult);
1.263     www      1136:         return '/adm/notfound.html';
                   1137:     }    
1.257     www      1138: }
1.15      www      1139: 
1.14      www      1140: # ------------------------------------------------------------------------- Log
                   1141: 
                   1142: sub log {
                   1143:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1144:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1145: }
                   1146: 
                   1147: # ------------------------------------------------------------------ Course Log
1.352     www      1148: #
                   1149: # This routine flushes several buffers of non-mission-critical nature
                   1150: #
1.157     www      1151: 
                   1152: sub flushcourselogs {
1.352     www      1153:     &logthis('Flushing log buffers');
                   1154: #
                   1155: # course logs
                   1156: # This is a log of all transactions in a course, which can be used
                   1157: # for data mining purposes
                   1158: #
                   1159: # It also collects the courseid database, which lists last transaction
                   1160: # times and course titles for all courseids
                   1161: #
                   1162:     my %courseidbuffer=();
1.191     harris41 1163:     foreach (keys %courselogs) {
1.157     www      1164:         my $crsid=$_;
1.352     www      1165:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1166: 		          &escape($courselogs{$crsid}),
                   1167: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1168: 	    delete $courselogs{$crsid};
                   1169:         } else {
                   1170:             &logthis('Failed to flush log buffer for '.$crsid);
                   1171:             if (length($courselogs{$crsid})>40000) {
                   1172:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                   1173:                         " exceeded maximum size, deleting.</font>");
                   1174:                delete $courselogs{$crsid};
                   1175:             }
1.352     www      1176:         }
                   1177:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1178:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
                   1179: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1180:         } else {
                   1181:            $courseidbuffer{$coursehombuf{$crsid}}=
                   1182: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
                   1183:         }    
1.191     harris41 1184:     }
1.352     www      1185: #
                   1186: # Write course id database (reverse lookup) to homeserver of courses 
                   1187: # Is used in pickcourse
                   1188: #
                   1189:     foreach (keys %courseidbuffer) {
1.353     www      1190:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1191:     }
                   1192: #
                   1193: # File accesses
                   1194: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1195: #
1.191     harris41 1196:     foreach (keys %accesshash) {
1.185     www      1197:         my $entry=$_;
                   1198:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
                   1199:         my %temphash=($entry => $accesshash{$entry});
1.266     albertel 1200:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
1.185     www      1201: 	    delete $accesshash{$entry};
                   1202:         }
1.191     harris41 1203:     }
1.352     www      1204: #
                   1205: # Roles
                   1206: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1207: #
1.349     www      1208:     foreach (keys %userrolehash) {
                   1209:         my $entry=$_;
1.351     www      1210:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1211: 	    split(/\:/,$entry);
                   1212:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1213:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1214:                 $rudom,$runame) eq 'ok') {
                   1215: 	    delete $userrolehash{$entry};
                   1216:         }
                   1217:     }
1.186     www      1218:     $dumpcount++;
1.157     www      1219: }
                   1220: 
                   1221: sub courselog {
                   1222:     my $what=shift;
1.158     www      1223:     $what=time.':'.$what;
1.157     www      1224:     unless ($ENV{'request.course.id'}) { return ''; }
1.188     www      1225:     $coursedombuf{$ENV{'request.course.id'}}=
1.352     www      1226:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1227:     $coursenumbuf{$ENV{'request.course.id'}}=
1.188     www      1228:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1229:     $coursehombuf{$ENV{'request.course.id'}}=
                   1230:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.352     www      1231:     $coursedescrbuf{$ENV{'request.course.id'}}=
                   1232:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.157     www      1233:     if (defined $courselogs{$ENV{'request.course.id'}}) {
                   1234: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
                   1235:     } else {
                   1236: 	$courselogs{$ENV{'request.course.id'}}.=$what;
                   1237:     }
                   1238:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
                   1239: 	&flushcourselogs();
                   1240:     }
1.158     www      1241: }
                   1242: 
                   1243: sub courseacclog {
                   1244:     my $fnsymb=shift;
                   1245:     unless ($ENV{'request.course.id'}) { return ''; }
                   1246:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.408     www      1247:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187     www      1248:         $what.=':POST';
1.191     harris41 1249: 	foreach (keys %ENV) {
1.158     www      1250:             if ($_=~/^form\.(.*)/) {
                   1251: 		$what.=':'.$1.'='.$ENV{$_};
                   1252:             }
1.191     harris41 1253:         }
1.158     www      1254:     }
                   1255:     &courselog($what);
1.149     www      1256: }
                   1257: 
1.185     www      1258: sub countacc {
                   1259:     my $url=&declutter(shift);
                   1260:     unless ($ENV{'request.course.id'}) { return ''; }
                   1261:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1262:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.185     www      1263:     if (defined($accesshash{$key})) {
                   1264: 	$accesshash{$key}++;
                   1265:     } else {
                   1266:         $accesshash{$key}=1;
                   1267:     }
                   1268: }
1.349     www      1269: 
1.361     www      1270: sub linklog {
                   1271:     my ($from,$to)=@_;
                   1272:     $from=&declutter($from);
                   1273:     $to=&declutter($to);
                   1274:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1275:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1276: }
                   1277:   
1.349     www      1278: sub userrolelog {
                   1279:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
                   1280:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
                   1281:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   1282:         ($trole=~/^cr/)) {
1.350     www      1283:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1284:        $userrolehash
                   1285:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1286:                     =$tend.':'.$tstart;
                   1287:    }
1.351     www      1288: }
                   1289: 
                   1290: sub get_course_adv_roles {
                   1291:     my $cid=shift;
                   1292:     $cid=$ENV{'request.course.id'} unless (defined($cid));
                   1293:     my %coursehash=&coursedescription($cid);
                   1294:     my %returnhash=();
                   1295:     my %dumphash=
                   1296:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1297:     my $now=time;
                   1298:     foreach (keys %dumphash) {
                   1299: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1300:         if (($tstart) && ($tstart<0)) { next; }
                   1301:         if (($tend) && ($tend<$now)) { next; }
                   1302:         if (($tstart) && ($now<$tstart)) { next; }
                   1303:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1304:         my $key=&plaintext($role);
                   1305:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1306:         if ($returnhash{$key}) {
                   1307: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1308:         } else {
                   1309:             $returnhash{$key}=$username.':'.$domain;
                   1310:         }
1.400     www      1311:      }
                   1312:     return %returnhash;
                   1313: }
                   1314: 
                   1315: sub get_my_roles {
                   1316:     my ($uname,$udom)=@_;
                   1317:     unless (defined($uname)) { $uname=$ENV{'user.name'}; }
                   1318:     unless (defined($udom)) { $udom=$ENV{'user.domain'}; }
                   1319:     my %dumphash=
                   1320:             &dump('nohist_userroles',$udom,$uname);
                   1321:     my %returnhash=();
                   1322:     my $now=time;
                   1323:     foreach (keys %dumphash) {
                   1324: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1325:         if (($tstart) && ($tstart<0)) { next; }
                   1326:         if (($tend) && ($tend<$now)) { next; }
                   1327:         if (($tstart) && ($now<$tstart)) { next; }
                   1328:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1329: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1330:      }
                   1331:     return %returnhash;
1.399     www      1332: }
                   1333: 
                   1334: # ----------------------------------------------------- Frontpage Announcements
                   1335: #
                   1336: #
                   1337: 
                   1338: sub postannounce {
                   1339:     my ($server,$text)=@_;
                   1340:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1341:     unless ($text=~/\w/) { $text=''; }
                   1342:     return &reply('setannounce:'.&escape($text),$server);
                   1343: }
                   1344: 
                   1345: sub getannounce {
                   1346:     if (my $fh=Apache::File->new($perlvar{'lonDocRoot'}.'/announcement.txt')) {
                   1347: 	my $announcement='';
                   1348: 	while (<$fh>) { $announcement .=$_; }
                   1349: 	$fh->close();
                   1350: 	if ($announcement=~/\w/) { 
                   1351: 	    return 
                   1352:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
                   1353:    '<tr><td bgcolor="#FFFFFF"><pre>'.$announcement.'</pre></td></tr></table>'; 
                   1354: 	} else {
                   1355: 	    return '';
                   1356: 	}
                   1357:     } else {
                   1358: 	return '';
                   1359:     }
1.351     www      1360: }
1.353     www      1361: 
                   1362: # ---------------------------------------------------------- Course ID routines
                   1363: # Deal with domain's nohist_courseid.db files
                   1364: #
                   1365: 
                   1366: sub courseidput {
                   1367:     my ($domain,$what,$coursehome)=@_;
                   1368:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1369: }
                   1370: 
                   1371: sub courseiddump {
                   1372:     my ($domfilter,$descfilter,$sincefilter)=@_;
                   1373:     my %returnhash=();
1.355     www      1374:     unless ($domfilter) { $domfilter=''; }
1.353     www      1375:     foreach my $tryserver (keys %libserv) {
1.355     www      1376: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.353     www      1377: 	    foreach (
                   1378:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.354     www      1379: 			       $sincefilter.':'.&escape($descfilter),
                   1380:                                $tryserver))) {
1.353     www      1381: 		my ($key,$value)=split(/\=/,$_);
                   1382:                 if (($key) && ($value)) {
                   1383: 		    $returnhash{&unescape($key)}=&unescape($value);
                   1384:                 }
                   1385:             }
                   1386: 
                   1387:         }
                   1388:     }
                   1389:     return %returnhash;
                   1390: }
                   1391: 
                   1392: #
1.149     www      1393: # ----------------------------------------------------------- Check out an item
                   1394: 
                   1395: sub checkout {
                   1396:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1397:     my $now=time;
                   1398:     my $lonhost=$perlvar{'lonHostID'};
                   1399:     my $infostr=&escape(
1.234     www      1400:                  'CHECKOUTTOKEN&'.
1.149     www      1401:                  $tuname.'&'.
                   1402:                  $tudom.'&'.
                   1403:                  $tcrsid.'&'.
                   1404:                  $symb.'&'.
                   1405: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1406:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1407:     if ($token=~/^error\:/) { 
                   1408:         &logthis("<font color=blue>WARNING: ".
                   1409:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1410:                  "</font>");
                   1411:         return ''; 
                   1412:     }
                   1413: 
1.149     www      1414:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1415:     $token=~tr/a-z/A-Z/;
                   1416: 
1.153     www      1417:     my %infohash=('resource.0.outtoken' => $token,
                   1418:                   'resource.0.checkouttime' => $now,
                   1419:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1420: 
                   1421:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1422:        return '';
1.151     www      1423:     } else {
                   1424:         &logthis("<font color=blue>WARNING: ".
                   1425:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1426:                  "</font>");
1.149     www      1427:     }    
                   1428: 
                   1429:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1430:                          &escape('Checkout '.$infostr.' - '.
                   1431:                                                  $token)) ne 'ok') {
                   1432: 	return '';
1.151     www      1433:     } else {
                   1434:         &logthis("<font color=blue>WARNING: ".
                   1435:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1436:                  "</font>");
1.149     www      1437:     }
1.151     www      1438:     return $token;
1.149     www      1439: }
                   1440: 
                   1441: # ------------------------------------------------------------ Check in an item
                   1442: 
                   1443: sub checkin {
                   1444:     my $token=shift;
1.150     www      1445:     my $now=time;
                   1446:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1447:     $lonhost=~tr/A-Z/a-z/;
                   1448:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
                   1449:     $dtoken=~s/\W/\_/g;
1.234     www      1450:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      1451:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1452: 
1.154     www      1453:     unless (($tuname) && ($tudom)) {
                   1454:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1455:         return '';
                   1456:     }
                   1457:     
                   1458:     unless (&allowed('mgr',$tcrsid)) {
                   1459:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   1460:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
                   1461:         return '';
                   1462:     }
                   1463: 
1.153     www      1464:     my %infohash=('resource.0.intoken' => $token,
                   1465:                   'resource.0.checkintime' => $now,
                   1466:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1467: 
                   1468:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1469:        return '';
                   1470:     }    
                   1471: 
                   1472:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1473:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1474: 	return '';
                   1475:     }
                   1476: 
                   1477:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1478: }
                   1479: 
                   1480: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1481: 
                   1482: sub expirespread {
                   1483:     my ($uname,$udom,$stype,$usymb)=@_;
                   1484:     my $cid=$ENV{'request.course.id'}; 
                   1485:     if ($cid) {
                   1486:        my $now=time;
                   1487:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   1488:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
                   1489:                             $ENV{'course.'.$cid.'.num'}.
                   1490: 	        	    ':nohist_expirationdates:'.
                   1491:                             &escape($key).'='.$now,
                   1492:                             $ENV{'course.'.$cid.'.home'})
                   1493:     }
                   1494:     return 'ok';
1.14      www      1495: }
                   1496: 
1.109     www      1497: # ----------------------------------------------------- Devalidate Spreadsheets
                   1498: 
                   1499: sub devalidate {
1.325     www      1500:     my ($symb,$uname,$udom)=@_;
1.109     www      1501:     my $cid=$ENV{'request.course.id'}; 
                   1502:     if ($cid) {
1.391     matthew  1503:         # delete the stored spreadsheets for
                   1504:         # - the student level sheet of this user in course's homespace
                   1505:         # - the assessment level sheet for this resource 
                   1506:         #   for this user in user's homespace
1.325     www      1507: 	my $key=$uname.':'.$udom.':';
1.109     www      1508:         my $status=
1.299     matthew  1509: 	    &del('nohist_calculatedsheets',
1.391     matthew  1510: 		 [$key.'studentcalc:'],
1.133     albertel 1511: 		 $ENV{'course.'.$cid.'.domain'},
                   1512: 		 $ENV{'course.'.$cid.'.num'})
                   1513: 		.' '.
                   1514: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  1515: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      1516:         unless ($status eq 'ok ok') {
                   1517:            &logthis('Could not devalidate spreadsheet '.
1.325     www      1518:                     $uname.' at '.$udom.' for '.
1.109     www      1519: 		    $symb.': '.$status);
1.133     albertel 1520:         }
1.109     www      1521:     }
                   1522: }
                   1523: 
1.265     albertel 1524: sub get_scalar {
                   1525:     my ($string,$end) = @_;
                   1526:     my $value;
                   1527:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1528: 	$value = $1;
                   1529:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1530: 	$value = $1;
                   1531:     }
                   1532:     return &unescape($value);
                   1533: }
                   1534: 
                   1535: sub array2str {
                   1536:   my (@array) = @_;
                   1537:   my $result=&arrayref2str(\@array);
                   1538:   $result=~s/^__ARRAY_REF__//;
                   1539:   $result=~s/__END_ARRAY_REF__$//;
                   1540:   return $result;
                   1541: }
                   1542: 
1.204     albertel 1543: sub arrayref2str {
                   1544:   my ($arrayref) = @_;
1.265     albertel 1545:   my $result='__ARRAY_REF__';
1.204     albertel 1546:   foreach my $elem (@$arrayref) {
1.265     albertel 1547:     if(ref($elem) eq 'ARRAY') {
                   1548:       $result.=&arrayref2str($elem).'&';
                   1549:     } elsif(ref($elem) eq 'HASH') {
                   1550:       $result.=&hashref2str($elem).'&';
                   1551:     } elsif(ref($elem)) {
                   1552:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 1553:     } else {
                   1554:       $result.=&escape($elem).'&';
                   1555:     }
                   1556:   }
                   1557:   $result=~s/\&$//;
1.265     albertel 1558:   $result .= '__END_ARRAY_REF__';
1.204     albertel 1559:   return $result;
                   1560: }
                   1561: 
1.168     albertel 1562: sub hash2str {
1.204     albertel 1563:   my (%hash) = @_;
                   1564:   my $result=&hashref2str(\%hash);
1.265     albertel 1565:   $result=~s/^__HASH_REF__//;
                   1566:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 1567:   return $result;
                   1568: }
                   1569: 
                   1570: sub hashref2str {
                   1571:   my ($hashref)=@_;
1.265     albertel 1572:   my $result='__HASH_REF__';
1.204     albertel 1573:   foreach (keys(%$hashref)) {
                   1574:     if (ref($_) eq 'ARRAY') {
1.265     albertel 1575:       $result.=&arrayref2str($_).'=';
1.204     albertel 1576:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 1577:       $result.=&hashref2str($_).'=';
1.204     albertel 1578:     } elsif (ref($_)) {
1.265     albertel 1579:       $result.='=';
                   1580:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 1581:     } else {
1.265     albertel 1582: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 1583:     }
                   1584: 
1.265     albertel 1585:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   1586:       $result.=&arrayref2str($hashref->{$_}).'&';
                   1587:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   1588:       $result.=&hashref2str($hashref->{$_}).'&';
                   1589:     } elsif(ref($hashref->{$_})) {
                   1590:        $result.='&';
                   1591:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 1592:     } else {
1.265     albertel 1593:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 1594:     }
                   1595:   }
1.168     albertel 1596:   $result=~s/\&$//;
1.265     albertel 1597:   $result .= '__END_HASH_REF__';
1.168     albertel 1598:   return $result;
                   1599: }
                   1600: 
                   1601: sub str2hash {
1.265     albertel 1602:     my ($string)=@_;
                   1603:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   1604:     return %$hash;
                   1605: }
                   1606: 
                   1607: sub str2hashref {
1.168     albertel 1608:   my ($string) = @_;
1.265     albertel 1609: 
                   1610:   my %hash;
                   1611: 
                   1612:   if($string !~ /^__HASH_REF__/) {
                   1613:       if (! ($string eq '' || !defined($string))) {
                   1614: 	  $hash{'error'}='Not hash reference';
                   1615:       }
                   1616:       return (\%hash, $string);
                   1617:   }
                   1618: 
                   1619:   $string =~ s/^__HASH_REF__//;
                   1620: 
                   1621:   while($string !~ /^__END_HASH_REF__/) {
                   1622:       #key
                   1623:       my $key='';
                   1624:       if($string =~ /^__HASH_REF__/) {
                   1625:           ($key, $string)=&str2hashref($string);
                   1626:           if(defined($key->{'error'})) {
                   1627:               $hash{'error'}='Bad data';
                   1628:               return (\%hash, $string);
                   1629:           }
                   1630:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1631:           ($key, $string)=&str2arrayref($string);
                   1632:           if($key->[0] eq 'Array reference error') {
                   1633:               $hash{'error'}='Bad data';
                   1634:               return (\%hash, $string);
                   1635:           }
                   1636:       } else {
                   1637:           $string =~ s/^(.*?)=//;
1.267     albertel 1638: 	  $key=&unescape($1);
1.265     albertel 1639:       }
                   1640:       $string =~ s/^=//;
                   1641: 
                   1642:       #value
                   1643:       my $value='';
                   1644:       if($string =~ /^__HASH_REF__/) {
                   1645:           ($value, $string)=&str2hashref($string);
                   1646:           if(defined($value->{'error'})) {
                   1647:               $hash{'error'}='Bad data';
                   1648:               return (\%hash, $string);
                   1649:           }
                   1650:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1651:           ($value, $string)=&str2arrayref($string);
                   1652:           if($value->[0] eq 'Array reference error') {
                   1653:               $hash{'error'}='Bad data';
                   1654:               return (\%hash, $string);
                   1655:           }
                   1656:       } else {
                   1657: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   1658:       }
                   1659:       $string =~ s/^&//;
                   1660: 
                   1661:       $hash{$key}=$value;
1.204     albertel 1662:   }
1.265     albertel 1663: 
                   1664:   $string =~ s/^__END_HASH_REF__//;
                   1665: 
                   1666:   return (\%hash, $string);
1.204     albertel 1667: }
                   1668: 
                   1669: sub str2array {
1.265     albertel 1670:     my ($string)=@_;
                   1671:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   1672:     return @$array;
                   1673: }
                   1674: 
                   1675: sub str2arrayref {
1.204     albertel 1676:   my ($string) = @_;
1.265     albertel 1677:   my @array;
                   1678: 
                   1679:   if($string !~ /^__ARRAY_REF__/) {
                   1680:       if (! ($string eq '' || !defined($string))) {
                   1681: 	  $array[0]='Array reference error';
                   1682:       }
                   1683:       return (\@array, $string);
                   1684:   }
                   1685: 
                   1686:   $string =~ s/^__ARRAY_REF__//;
                   1687: 
                   1688:   while($string !~ /^__END_ARRAY_REF__/) {
                   1689:       my $value='';
                   1690:       if($string =~ /^__HASH_REF__/) {
                   1691:           ($value, $string)=&str2hashref($string);
                   1692:           if(defined($value->{'error'})) {
                   1693:               $array[0] ='Array reference error';
                   1694:               return (\@array, $string);
                   1695:           }
                   1696:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1697:           ($value, $string)=&str2arrayref($string);
                   1698:           if($value->[0] eq 'Array reference error') {
                   1699:               $array[0] ='Array reference error';
                   1700:               return (\@array, $string);
                   1701:           }
                   1702:       } else {
                   1703: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   1704:       }
                   1705:       $string =~ s/^&//;
                   1706: 
                   1707:       push(@array, $value);
1.191     harris41 1708:   }
1.265     albertel 1709: 
                   1710:   $string =~ s/^__END_ARRAY_REF__//;
                   1711: 
                   1712:   return (\@array, $string);
1.168     albertel 1713: }
                   1714: 
1.167     albertel 1715: # -------------------------------------------------------------------Temp Store
                   1716: 
1.168     albertel 1717: sub tmpreset {
                   1718:   my ($symb,$namespace,$domain,$stuname) = @_;
                   1719:   if (!$symb) {
                   1720:     $symb=&symbread();
1.380     albertel 1721:     if (!$symb) { $symb= $ENV{'request.url'}; }
1.168     albertel 1722:   }
                   1723:   $symb=escape($symb);
                   1724: 
                   1725:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1726:   $namespace=~s/\//\_/g;
                   1727:   $namespace=~s/\W//g;
                   1728: 
                   1729:   #FIXME needs to do something for /pub resources
                   1730:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1731:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1732:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1733:   my %hash;
                   1734:   if (tie(%hash,'GDBM_File',
                   1735: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1736: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1737:     foreach my $key (keys %hash) {
1.180     albertel 1738:       if ($key=~ /:$symb/) {
1.168     albertel 1739: 	delete($hash{$key});
                   1740:       }
                   1741:     }
                   1742:   }
                   1743: }
                   1744: 
1.167     albertel 1745: sub tmpstore {
1.168     albertel 1746:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1747: 
                   1748:   if (!$symb) {
                   1749:     $symb=&symbread();
                   1750:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1751:   }
                   1752:   $symb=escape($symb);
                   1753: 
                   1754:   if (!$namespace) {
                   1755:     # I don't think we would ever want to store this for a course.
                   1756:     # it seems this will only be used if we don't have a course.
                   1757:     #$namespace=$ENV{'request.course.id'};
                   1758:     #if (!$namespace) {
                   1759:       $namespace=$ENV{'request.state'};
                   1760:     #}
                   1761:   }
                   1762:   $namespace=~s/\//\_/g;
                   1763:   $namespace=~s/\W//g;
                   1764: #FIXME needs to do something for /pub resources
                   1765:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1766:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1767:   my $now=time;
                   1768:   my %hash;
                   1769:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1770:   if (tie(%hash,'GDBM_File',
                   1771: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1772: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 1773:     $hash{"version:$symb"}++;
                   1774:     my $version=$hash{"version:$symb"};
                   1775:     my $allkeys=''; 
                   1776:     foreach my $key (keys(%$storehash)) {
                   1777:       $allkeys.=$key.':';
                   1778:       $hash{"$version:$symb:$key"}=$$storehash{$key};
                   1779:     }
                   1780:     $hash{"$version:$symb:timestamp"}=$now;
                   1781:     $allkeys.='timestamp';
                   1782:     $hash{"$version:keys:$symb"}=$allkeys;
                   1783:     if (untie(%hash)) {
                   1784:       return 'ok';
                   1785:     } else {
                   1786:       return "error:$!";
                   1787:     }
                   1788:   } else {
                   1789:     return "error:$!";
                   1790:   }
                   1791: }
1.167     albertel 1792: 
1.168     albertel 1793: # -----------------------------------------------------------------Temp Restore
1.167     albertel 1794: 
1.168     albertel 1795: sub tmprestore {
                   1796:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 1797: 
1.168     albertel 1798:   if (!$symb) {
                   1799:     $symb=&symbread();
                   1800:     if (!$symb) { $symb= $ENV{'request.url'}; }
                   1801:   }
                   1802:   $symb=escape($symb);
                   1803: 
                   1804:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
                   1805:   #FIXME needs to do something for /pub resources
                   1806:   if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1807:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1808: 
                   1809:   my %returnhash;
                   1810:   $namespace=~s/\//\_/g;
                   1811:   $namespace=~s/\W//g;
                   1812:   my %hash;
                   1813:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   1814:   if (tie(%hash,'GDBM_File',
                   1815: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 1816: 	  &GDBM_READER(),0640)) {
1.168     albertel 1817:     my $version=$hash{"version:$symb"};
                   1818:     $returnhash{'version'}=$version;
                   1819:     my $scope;
                   1820:     for ($scope=1;$scope<=$version;$scope++) {
                   1821:       my $vkeys=$hash{"$scope:keys:$symb"};
                   1822:       my @keys=split(/:/,$vkeys);
                   1823:       my $key;
                   1824:       $returnhash{"$scope:keys"}=$vkeys;
                   1825:       foreach $key (@keys) {
                   1826: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
                   1827: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167     albertel 1828:       }
                   1829:     }
1.168     albertel 1830:     if (!(untie(%hash))) {
                   1831:       return "error:$!";
                   1832:     }
                   1833:   } else {
                   1834:     return "error:$!";
                   1835:   }
                   1836:   return %returnhash;
1.167     albertel 1837: }
                   1838: 
1.9       www      1839: # ----------------------------------------------------------------------- Store
                   1840: 
                   1841: sub store {
1.124     www      1842:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1843:     my $home='';
                   1844: 
1.168     albertel 1845:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1846: 
1.213     www      1847:     $symb=&symbclean($symb);
1.122     albertel 1848:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1849: 
1.325     www      1850:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1851:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1852: 
                   1853:     &devalidate($symb,$stuname,$domain);
1.109     www      1854: 
                   1855:     $symb=escape($symb);
1.187     www      1856:     if (!$namespace) { 
                   1857:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1858:           return ''; 
                   1859:        } 
                   1860:     }
1.122     albertel 1861:     if (!$home) { $home=$ENV{'user.home'}; }
1.12      www      1862:     my $namevalue='';
1.191     harris41 1863:     foreach (keys %$storehash) {
1.122     albertel 1864:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1865:     }
1.12      www      1866:     $namevalue=~s/\&$//;
1.187     www      1867:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      1868:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      1869: }
                   1870: 
1.47      www      1871: # -------------------------------------------------------------- Critical Store
                   1872: 
                   1873: sub cstore {
1.124     www      1874:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   1875:     my $home='';
                   1876: 
1.168     albertel 1877:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1878: 
1.213     www      1879:     $symb=&symbclean($symb);
1.122     albertel 1880:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      1881: 
1.325     www      1882:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1883:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1884: 
                   1885:     &devalidate($symb,$stuname,$domain);
1.109     www      1886: 
                   1887:     $symb=escape($symb);
1.187     www      1888:     if (!$namespace) { 
                   1889:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1890:           return ''; 
                   1891:        } 
                   1892:     }
1.122     albertel 1893:     if (!$home) { $home=$ENV{'user.home'}; }
                   1894: 
1.47      www      1895:     my $namevalue='';
1.191     harris41 1896:     foreach (keys %$storehash) {
1.122     albertel 1897:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 1898:     }
1.47      www      1899:     $namevalue=~s/\&$//;
1.187     www      1900:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      1901:     return critical
                   1902:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      1903: }
                   1904: 
1.9       www      1905: # --------------------------------------------------------------------- Restore
                   1906: 
                   1907: sub restore {
1.124     www      1908:     my ($symb,$namespace,$domain,$stuname) = @_;
                   1909:     my $home='';
                   1910: 
1.168     albertel 1911:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      1912: 
1.122     albertel 1913:     if (!$symb) {
                   1914:       unless ($symb=escape(&symbread())) { return ''; }
                   1915:     } else {
1.213     www      1916:       $symb=&escape(&symbclean($symb));
1.122     albertel 1917:     }
1.188     www      1918:     if (!$namespace) { 
                   1919:        unless ($namespace=$ENV{'request.course.id'}) { 
                   1920:           return ''; 
                   1921:        } 
                   1922:     }
1.122     albertel 1923:     if (!$domain) { $domain=$ENV{'user.domain'}; }
                   1924:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
                   1925:     if (!$home) { $home=$ENV{'user.home'}; }
                   1926:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   1927: 
1.12      www      1928:     my %returnhash=();
1.191     harris41 1929:     foreach (split(/\&/,$answer)) {
1.12      www      1930: 	my ($name,$value)=split(/\=/,$_);
                   1931:         $returnhash{&unescape($name)}=&unescape($value);
1.191     harris41 1932:     }
1.75      www      1933:     my $version;
                   1934:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 1935:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      1936:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 1937:        }
1.75      www      1938:     }
1.13      www      1939:     return %returnhash;
1.34      www      1940: }
                   1941: 
                   1942: # ---------------------------------------------------------- Course Description
                   1943: 
                   1944: sub coursedescription {
                   1945:     my $courseid=shift;
                   1946:     $courseid=~s/^\///;
1.49      www      1947:     $courseid=~s/\_/\//g;
1.34      www      1948:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 1949:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 1950:     my $normalid=$cdomain.'_'.$cnum;
                   1951:     # need to always cache even if we get errors otherwise we keep 
                   1952:     # trying and trying and trying to get the course description.
                   1953:     my %envhash=();
                   1954:     my %returnhash=();
                   1955:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      1956:     if ($chome ne 'no_host') {
1.302     albertel 1957:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 1958:        if (!exists($returnhash{'con_lost'})) {
                   1959:            $returnhash{'home'}= $chome;
                   1960: 	   $returnhash{'domain'} = $cdomain;
                   1961: 	   $returnhash{'num'} = $cnum;
1.130     albertel 1962:            while (my ($name,$value) = each %returnhash) {
1.53      www      1963:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 1964:            }
1.270     www      1965:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      1966:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38      www      1967: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      1968:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   1969:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   1970:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      1971:        }
                   1972:     }
1.302     albertel 1973:     &appenv(%envhash);
                   1974:     return %returnhash;
1.9       www      1975: }
1.1       albertel 1976: 
1.103     harris41 1977: # -------------------------------------------------------- Get user privileges
1.11      www      1978: 
                   1979: sub rolesinit {
                   1980:     my ($domain,$username,$authhost)=@_;
                   1981:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      1982:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      1983:     my %allroles=();
                   1984:     my %thesepriv=();
                   1985:     my $now=time;
1.21      www      1986:     my $userroles="user.login.time=$now\n";
1.11      www      1987:     my $thesestr;
                   1988: 
                   1989:     if ($rolesdump ne '') {
1.191     harris41 1990:         foreach (split(/&/,$rolesdump)) {
1.21      www      1991: 	  if ($_!~/^rolesdef\&/) {
1.11      www      1992:             my ($area,$role)=split(/=/,$_);
1.21      www      1993:             $area=~s/\_\w\w$//;
1.11      www      1994:             my ($trole,$tend,$tstart)=split(/_/,$role);
1.21      www      1995:             $userroles.='user.role.'.$trole.'.'.$area.'='.
                   1996:                         $tstart.'.'.$tend."\n";
1.349     www      1997: # log the associated role with the area
                   1998:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.11      www      1999:             if ($tend!=0) {
                   2000: 	        if ($tend<$now) {
                   2001: 	            $trole='';
                   2002:                 } 
                   2003:             }
                   2004:             if ($tstart!=0) {
                   2005:                 if ($tstart>$now) {
                   2006:                    $trole='';        
                   2007:                 }
                   2008:             }
                   2009:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2010: 		my $spec=$trole.'.'.$area;
                   2011: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2012: 		if ($trole =~ /^cr\//) {
                   2013: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.392     www      2014:  		    my $homsvr=homeserver($rauthor,$rdomain);
1.347     albertel 2015: 		    if ($hostname{$homsvr} ne '') {
1.392     www      2016: 			my ($rdummy,$roledef)=
                   2017: 			   &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2018: 				
                   2019: 			if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.347     albertel 2020: 			    my ($syspriv,$dompriv,$coursepriv)=
1.392     www      2021: 				split(/\_/,$roledef);
1.347     albertel 2022: 			    if (defined($syspriv)) {
                   2023: 				$allroles{'cm./'}.=':'.$syspriv;
                   2024: 				$allroles{$spec.'./'}.=':'.$syspriv;
                   2025: 			    }
                   2026: 			    if ($tdomain ne '') {
                   2027: 				if (defined($dompriv)) {
                   2028: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2029: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2030: 				}
                   2031: 				if ($trest ne '') {
                   2032: 				    if (defined($coursepriv)) {
                   2033: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2034: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2035: 				    }
                   2036: 				}
                   2037: 			    }
                   2038: 			}
                   2039: 		    }
                   2040: 		} else {
                   2041: 		    if (defined($pr{$trole.':s'})) {
                   2042: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2043: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2044: 		    }
                   2045: 		    if ($tdomain ne '') {
                   2046: 			if (defined($pr{$trole.':d'})) {
                   2047: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2048: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2049: 			}
                   2050: 			if ($trest ne '') {
                   2051: 			    if (defined($pr{$trole.':c'})) {
                   2052: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2053: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2054: 			    }
                   2055: 			}
                   2056: 		    }
                   2057: 		}
1.12      www      2058:             }
                   2059:           } 
1.191     harris41 2060:         }
1.125     www      2061:         my $adv=0;
1.128     www      2062:         my $author=0;
1.191     harris41 2063:         foreach (keys %allroles) {
1.11      www      2064:             %thesepriv=();
1.146     www      2065:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128     www      2066:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191     harris41 2067:             foreach (split(/:/,$allroles{$_})) {
1.11      www      2068:                 if ($_ ne '') {
1.103     harris41 2069: 		    my ($privilege,$restrictions)=split(/&/,$_);
1.11      www      2070:                     if ($restrictions eq '') {
1.103     harris41 2071: 			$thesepriv{$privilege}='F';
1.11      www      2072:                     } else {
1.103     harris41 2073:                         if ($thesepriv{$privilege} ne 'F') {
                   2074: 			    $thesepriv{$privilege}.=$restrictions;
1.11      www      2075:                         }
                   2076:                     }
                   2077:                 }
1.191     harris41 2078:             }
1.11      www      2079:             $thesestr='';
1.191     harris41 2080:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11      www      2081:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191     harris41 2082:         }
1.128     www      2083:         $userroles.='user.adv='.$adv."\n".
                   2084: 	            'user.author='.$author."\n";
1.126     www      2085:         $ENV{'user.adv'}=$adv;
1.11      www      2086:     }
                   2087:     return $userroles;  
                   2088: }
                   2089: 
1.12      www      2090: # --------------------------------------------------------------- get interface
                   2091: 
                   2092: sub get {
1.131     albertel 2093:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2094:    my $items='';
1.191     harris41 2095:    foreach (@$storearr) {
1.12      www      2096:        $items.=escape($_).'&';
1.191     harris41 2097:    }
1.12      www      2098:    $items=~s/\&$//;
1.131     albertel 2099:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2100:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2101:    my $uhome=&homeserver($uname,$udomain);
                   2102: 
1.133     albertel 2103:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2104:    my @pairs=split(/\&/,$rep);
1.273     albertel 2105:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2106:      return @pairs;
                   2107:    }
1.15      www      2108:    my %returnhash=();
1.42      www      2109:    my $i=0;
1.191     harris41 2110:    foreach (@$storearr) {
1.42      www      2111:       $returnhash{$_}=unescape($pairs[$i]);
                   2112:       $i++;
1.191     harris41 2113:    }
1.15      www      2114:    return %returnhash;
1.27      www      2115: }
                   2116: 
                   2117: # --------------------------------------------------------------- del interface
                   2118: 
                   2119: sub del {
1.133     albertel 2120:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2121:    my $items='';
1.191     harris41 2122:    foreach (@$storearr) {
1.27      www      2123:        $items.=escape($_).'&';
1.191     harris41 2124:    }
1.27      www      2125:    $items=~s/\&$//;
1.133     albertel 2126:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2127:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2128:    my $uhome=&homeserver($uname,$udomain);
                   2129: 
                   2130:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2131: }
                   2132: 
                   2133: # -------------------------------------------------------------- dump interface
                   2134: 
                   2135: sub dump {
1.193     www      2136:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.129     albertel 2137:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2138:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2139:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2140:    if ($regexp) {
                   2141:        $regexp=&escape($regexp);
                   2142:    } else {
                   2143:        $regexp='.';
                   2144:    }
                   2145:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2146:    my @pairs=split(/\&/,$rep);
                   2147:    my %returnhash=();
1.191     harris41 2148:    foreach (@pairs) {
1.12      www      2149:       my ($key,$value)=split(/=/,$_);
1.29      www      2150:       $returnhash{unescape($key)}=unescape($value);
1.318     matthew  2151:    }
                   2152:    return %returnhash;
1.407     www      2153: }
                   2154: 
                   2155: # -------------------------------------------------------------- keys interface
                   2156: 
                   2157: sub getkeys {
                   2158:    my ($namespace,$udomain,$uname)=@_;
                   2159:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2160:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2161:    my $uhome=&homeserver($uname,$udomain);
                   2162:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2163:    my @keyarray=();
                   2164:    foreach (split(/\&/,$rep)) {
                   2165:       push (@keyarray,&unescape($_));
                   2166:    }
                   2167:    return @keyarray;
1.318     matthew  2168: }
                   2169: 
1.319     matthew  2170: # --------------------------------------------------------------- currentdump
                   2171: sub currentdump {
1.328     matthew  2172:    my ($courseid,$sdom,$sname)=@_;
1.326     matthew  2173:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2174:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
                   2175:    $sname    = $ENV{'user.name'}         if (! defined($sname));
                   2176:    my $uhome = &homeserver($sname,$sdom);
                   2177:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2178:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2179:    #
1.318     matthew  2180:    my %returnhash=();
1.319     matthew  2181:    #
                   2182:    if ($rep eq "unknown_cmd") { 
                   2183:        # an old lond will not know currentdump
                   2184:        # Do a dump and make it look like a currentdump
1.326     matthew  2185:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2186:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2187:        my %hash = @tmp;
                   2188:        @tmp=();
                   2189:        # Code ripped from lond, essentially.  The only difference
                   2190:        # here is the unescaping done by lonnet::dump().  Conceivably
                   2191:        # we might run in to problems with parameter names =~ /^v\./
                   2192:        while (my ($key,$value) = each(%hash)) {
                   2193:            my ($v,$symb,$param) = split(/:/,$key);
                   2194:            next if ($v eq 'version' || $symb eq 'keys');
                   2195:            next if (exists($returnhash{$symb}) &&
                   2196:                     exists($returnhash{$symb}->{$param}) &&
                   2197:                     $returnhash{$symb}->{'v.'.$param} > $v);
                   2198:            $returnhash{$symb}->{$param}=$value;
                   2199:            $returnhash{$symb}->{'v.'.$param}=$v;
                   2200:        }
                   2201:        #
                   2202:        # Remove all of the keys in the hashes which keep track of
                   2203:        # the version of the parameter.
                   2204:        while (my ($symb,$param_hash) = each(%returnhash)) {
                   2205:            # use a foreach because we are going to delete from the hash.
                   2206:            foreach my $key (keys(%$param_hash)) {
                   2207:                delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2208:            }
                   2209:        }
                   2210:    } else {
                   2211:        my @pairs=split(/\&/,$rep);
                   2212:        foreach (@pairs) {
                   2213:            my ($key,$value)=split(/=/,$_);
                   2214:            my ($symb,$param) = split(/:/,$key);
                   2215:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
                   2216:                                                           &unescape($value);
                   2217:        }
1.191     harris41 2218:    }
1.12      www      2219:    return %returnhash;
                   2220: }
                   2221: 
                   2222: # --------------------------------------------------------------- put interface
                   2223: 
                   2224: sub put {
1.134     albertel 2225:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2226:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2227:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2228:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2229:    my $items='';
1.191     harris41 2230:    foreach (keys %$storehash) {
1.134     albertel 2231:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191     harris41 2232:    }
1.12      www      2233:    $items=~s/\&$//;
1.134     albertel 2234:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2235: }
                   2236: 
                   2237: # ------------------------------------------------------ critical put interface
                   2238: 
                   2239: sub cput {
1.134     albertel 2240:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2241:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2242:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2243:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2244:    my $items='';
1.191     harris41 2245:    foreach (keys %$storehash) {
1.134     albertel 2246:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191     harris41 2247:    }
1.47      www      2248:    $items=~s/\&$//;
1.134     albertel 2249:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2250: }
                   2251: 
                   2252: # -------------------------------------------------------------- eget interface
                   2253: 
                   2254: sub eget {
1.133     albertel 2255:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2256:    my $items='';
1.191     harris41 2257:    foreach (@$storearr) {
1.12      www      2258:        $items.=escape($_).'&';
1.191     harris41 2259:    }
1.12      www      2260:    $items=~s/\&$//;
1.133     albertel 2261:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
                   2262:    if (!$uname) { $uname=$ENV{'user.name'}; }
                   2263:    my $uhome=&homeserver($uname,$udomain);
                   2264:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2265:    my @pairs=split(/\&/,$rep);
                   2266:    my %returnhash=();
1.42      www      2267:    my $i=0;
1.191     harris41 2268:    foreach (@$storearr) {
1.42      www      2269:       $returnhash{$_}=unescape($pairs[$i]);
                   2270:       $i++;
1.191     harris41 2271:    }
1.12      www      2272:    return %returnhash;
                   2273: }
                   2274: 
1.341     www      2275: # ---------------------------------------------- Custom access rule evaluation
                   2276: 
                   2277: sub customaccess {
                   2278:     my ($priv,$uri)=@_;
1.342     www      2279:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343     www      2280:     $urealm=~s/^\W//;
                   2281:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2282:     my $access=0;
                   2283:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2284: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2285:         if ($role) {
                   2286: 	   if ($role ne $urole) { next; }
                   2287:         }
                   2288:         foreach (split(/\s*\,\s*/,$realm)) {
                   2289:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2290:             if ($tdom) {
                   2291: 		if ($tdom ne $udom) { next; }
                   2292:             }
                   2293:             if ($tcrs) {
                   2294: 		if ($tcrs ne $ucrs) { next; }
                   2295:             }
                   2296:             if ($tsec) {
                   2297: 		if ($tsec ne $usec) { next; }
                   2298:             }
                   2299:             $access=($effect eq 'allow');
                   2300:             last;
1.342     www      2301:         }
1.402     bowersj2 2302: 	if ($realm eq '' && $role eq '') {
                   2303:             $access=($effect eq 'allow');
                   2304: 	}
1.341     www      2305:     }
                   2306:     return $access;
                   2307: }
                   2308: 
1.103     harris41 2309: # ------------------------------------------------- Check for a user privilege
1.12      www      2310: 
                   2311: sub allowed {
                   2312:     my ($priv,$uri)=@_;
1.152     www      2313: 
                   2314:     my $orguri=$uri;
1.52      www      2315:     $uri=&declutter($uri);
1.29      www      2316: 
1.398     albertel 2317:     if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
1.54      www      2318: # Free bre access to adm and meta resources
1.29      www      2319: 
1.54      www      2320:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2321: 	return 'F';
1.159     www      2322:     }
                   2323: 
                   2324: # Free bre to public access
                   2325: 
                   2326:     if ($priv eq 'bre') {
1.238     www      2327:         my $copyright=&metadata($uri,'copyright');
1.301     www      2328: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
                   2329:            return 'F'; 
                   2330:         }
1.238     www      2331:         if ($copyright eq 'priv') {
                   2332:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2333: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
                   2334: 		return '';
                   2335:             }
                   2336:         }
                   2337:         if ($copyright eq 'domain') {
                   2338:             $uri=~/([^\/]+)\/([^\/]+)\//;
                   2339: 	    unless (($ENV{'user.domain'} eq $1) ||
                   2340:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
                   2341: 		return '';
                   2342:             }
1.262     matthew  2343:         }
                   2344:         if ($ENV{'request.role'}=~ /li\.\//) {
                   2345:             # Library role, so allow browsing of resources in this domain.
                   2346:             return 'F';
1.238     www      2347:         }
1.341     www      2348:         if ($copyright eq 'custom') {
                   2349: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2350:         }
1.14      www      2351:     }
1.264     matthew  2352:     # Domain coordinator is trying to create a course
                   2353:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
                   2354:         # uri is the requested domain in this case.
                   2355:         # comparison to 'request.role.domain' shows if the user has selected
                   2356:         # a role of dc for the domain in question. 
                   2357:         return 'F' if ($uri eq $ENV{'request.role.domain'});
                   2358:     }
1.29      www      2359: 
1.52      www      2360:     my $thisallowed='';
                   2361:     my $statecond=0;
                   2362:     my $courseprivid='';
                   2363: 
                   2364: # Course
                   2365: 
                   2366:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
                   2367:        $thisallowed.=$1;
                   2368:     }
1.29      www      2369: 
1.52      www      2370: # Domain
                   2371: 
                   2372:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
                   2373:        =~/$priv\&([^\:]*)/) {
1.12      www      2374:        $thisallowed.=$1;
                   2375:     }
1.52      www      2376: 
                   2377: # Course: uri itself is a course
1.66      www      2378:     my $courseuri=$uri;
                   2379:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2380:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2381: 
1.83      www      2382:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52      www      2383:        =~/$priv\&([^\:]*)/) {
1.12      www      2384:        $thisallowed.=$1;
                   2385:     }
1.29      www      2386: 
1.314     www      2387: # URI is an uploaded document for this course
                   2388: 
                   2389:     if (($priv eq 'bre') && 
                   2390:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
                   2391:         return 'F';
                   2392:     }
1.52      www      2393: # Full access at system, domain or course-wide level? Exit.
1.29      www      2394: 
                   2395:     if ($thisallowed=~/F/) {
                   2396: 	return 'F';
                   2397:     }
                   2398: 
1.52      www      2399: # If this is generating or modifying users, exit with special codes
1.29      www      2400: 
1.166     www      2401:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52      www      2402: 	return $thisallowed;
                   2403:     }
                   2404: #
1.103     harris41 2405: # Gathered so far: system, domain and course wide privileges
1.52      www      2406: #
                   2407: # Course: See if uri or referer is an individual resource that is part of 
                   2408: # the course
                   2409: 
                   2410:     if ($ENV{'request.course.id'}) {
1.232     www      2411: 
1.52      www      2412:        $courseprivid=$ENV{'request.course.id'};
                   2413:        if ($ENV{'request.course.sec'}) {
                   2414:           $courseprivid.='/'.$ENV{'request.course.sec'};
                   2415:        }
                   2416:        $courseprivid=~s/\_/\//;
                   2417:        my $checkreferer=1;
1.232     www      2418:        my ($match,$cond)=&is_on_map($uri);
                   2419:        if ($match) {
                   2420:            $statecond=$cond;
1.52      www      2421:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2422:                =~/$priv\&([^\:]*)/) {
                   2423:                $thisallowed.=$1;
                   2424:                $checkreferer=0;
                   2425:            }
1.29      www      2426:        }
1.83      www      2427:        
1.148     www      2428:        if ($checkreferer) {
1.152     www      2429: 	  my $refuri=$ENV{'httpref.'.$orguri};
1.148     www      2430:             unless ($refuri) {
1.191     harris41 2431:                 foreach (keys %ENV) {
1.148     www      2432: 		    if ($_=~/^httpref\..*\*/) {
                   2433: 			my $pattern=$_;
1.156     www      2434:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      2435:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   2436:                         $pattern=~s/\//\\\//g;
1.152     www      2437:                         if ($orguri=~/$pattern/) {
1.148     www      2438: 			    $refuri=$ENV{$_};
                   2439:                         }
                   2440:                     }
1.191     harris41 2441:                 }
1.148     www      2442:             }
1.232     www      2443: 
1.148     www      2444:          if ($refuri) { 
1.152     www      2445: 	  $refuri=&declutter($refuri);
1.232     www      2446:           my ($match,$cond)=&is_on_map($refuri);
                   2447:             if ($match) {
                   2448:               my $refstatecond=$cond;
1.52      www      2449:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
                   2450:                   =~/$priv\&([^\:]*)/) {
                   2451:                   $thisallowed.=$1;
1.53      www      2452:                   $uri=$refuri;
                   2453:                   $statecond=$refstatecond;
1.52      www      2454:               }
                   2455:           }
1.148     www      2456:         }
1.29      www      2457:        }
1.52      www      2458:    }
1.29      www      2459: 
1.52      www      2460: #
1.103     harris41 2461: # Gathered now: all privileges that could apply, and condition number
1.52      www      2462: # 
                   2463: #
                   2464: # Full or no access?
                   2465: #
1.29      www      2466: 
1.52      www      2467:     if ($thisallowed=~/F/) {
                   2468: 	return 'F';
                   2469:     }
1.29      www      2470: 
1.52      www      2471:     unless ($thisallowed) {
                   2472:         return '';
                   2473:     }
1.29      www      2474: 
1.52      www      2475: # Restrictions exist, deal with them
                   2476: #
                   2477: #   C:according to course preferences
                   2478: #   R:according to resource settings
                   2479: #   L:unless locked
                   2480: #   X:according to user session state
                   2481: #
                   2482: 
                   2483: # Possibly locked functionality, check all courses
1.54      www      2484: # Locks might take effect only after 10 minutes cache expiration for other
                   2485: # courses, and 2 minutes for current course
1.52      www      2486: 
                   2487:     my $envkey;
                   2488:     if ($thisallowed=~/L/) {
                   2489:         foreach $envkey (keys %ENV) {
1.54      www      2490:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   2491:                my $courseid=$2;
                   2492:                my $roleid=$1.'.'.$2;
1.92      www      2493:                $courseid=~s/^\///;
1.54      www      2494:                my $expiretime=600;
                   2495:                if ($ENV{'request.role'} eq $roleid) {
                   2496: 		  $expiretime=120;
                   2497:                }
                   2498: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   2499:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
                   2500:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
                   2501: 		   &coursedescription($courseid);
                   2502:                }
                   2503:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
                   2504:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   2505: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57      www      2506:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2507:                             $ENV{'user.home'},
1.57      www      2508:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      2509:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2510:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2511: 		       return '';
                   2512:                    }
                   2513:                }
1.54      www      2514:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
                   2515:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   2516: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57      www      2517:                        &log($ENV{'user.domain'},$ENV{'user.name'},
1.239     www      2518:                             $ENV{'user.home'},
1.57      www      2519:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      2520:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54      www      2521:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2522: 		       return '';
                   2523:                    }
                   2524:                }
                   2525: 	   }
1.29      www      2526:        }
1.52      www      2527:     }
                   2528:    
                   2529: #
                   2530: # Rest of the restrictions depend on selected course
                   2531: #
                   2532: 
                   2533:     unless ($ENV{'request.course.id'}) {
                   2534:        return '1';
                   2535:     }
1.29      www      2536: 
1.52      www      2537: #
                   2538: # Now user is definitely in a course
                   2539: #
1.53      www      2540: 
                   2541: 
                   2542: # Course preferences
                   2543: 
                   2544:    if ($thisallowed=~/C/) {
1.54      www      2545:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237     www      2546:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54      www      2547:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194     www      2548: 	   =~/$rolecode/) {
1.57      www      2549:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2550:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237     www      2551:                 $ENV{'request.course.id'});
                   2552:            return '';
                   2553:        }
                   2554: 
                   2555:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
                   2556: 	   =~/$unamedom/) {
                   2557:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
                   2558:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54      www      2559:                 $ENV{'request.course.id'});
                   2560:            return '';
                   2561:        }
1.53      www      2562:    }
                   2563: 
                   2564: # Resource preferences
                   2565: 
                   2566:    if ($thisallowed=~/R/) {
1.54      www      2567:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.341     www      2568:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
                   2569: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57      www      2570:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      2571:           return '';
1.54      www      2572:        }
1.53      www      2573:    }
1.30      www      2574: 
1.246     www      2575: # Restricted by state or randomout?
1.30      www      2576: 
1.52      www      2577:    if ($thisallowed=~/X/) {
1.247     www      2578:       if ($ENV{'acc.randomout'}) {
1.249     www      2579:          my $symb=&symbread($uri,1);
1.248     www      2580:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
                   2581:             return ''; 
                   2582:          }
1.247     www      2583:       }
                   2584:       if (&condval($statecond)) {
1.52      www      2585: 	 return '2';
                   2586:       } else {
                   2587:          return '';
                   2588:       }
                   2589:    }
1.30      www      2590: 
1.52      www      2591:    return 'F';
1.232     www      2592: }
                   2593: 
                   2594: # --------------------------------------------------- Is a resource on the map?
                   2595: 
                   2596: sub is_on_map {
                   2597:     my $uri=&declutter(shift);
                   2598:     my @uriparts=split(/\//,$uri);
                   2599:     my $filename=$uriparts[$#uriparts];
                   2600:     my $pathname=$uri;
1.289     bowersj2 2601:     $pathname=~s|/\Q$filename\E$||;
1.332     www      2602:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 2603:     #Trying to find the conditional for the file
1.232     www      2604:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 2605: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      2606:     if ($match) {
1.289     bowersj2 2607: 	return (1,$1);
                   2608:     } else {
                   2609: 	return (0,0);
                   2610:     }
1.12      www      2611: }
                   2612: 
                   2613: # ----------------------------------------------------------------- Define Role
                   2614: 
                   2615: sub definerole {
                   2616:   if (allowed('mcr','/')) {
                   2617:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      2618:     foreach (split(':',$sysrole)) {
1.21      www      2619: 	my ($crole,$cqual)=split(/\&/,$_);
                   2620:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
                   2621:         if ($pr{'cr:s'}=~/$crole\&/) {
                   2622: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
                   2623:                return "refused:s:$crole&$cqual"; 
                   2624:             }
                   2625:         }
1.191     harris41 2626:     }
1.392     www      2627:     foreach (split(':',$domrole)) {
1.21      www      2628: 	my ($crole,$cqual)=split(/\&/,$_);
                   2629:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
                   2630:         if ($pr{'cr:d'}=~/$crole\&/) {
                   2631: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
                   2632:                return "refused:d:$crole&$cqual"; 
                   2633:             }
                   2634:         }
1.191     harris41 2635:     }
1.392     www      2636:     foreach (split(':',$courole)) {
1.21      www      2637: 	my ($crole,$cqual)=split(/\&/,$_);
                   2638:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
                   2639:         if ($pr{'cr:c'}=~/$crole\&/) {
                   2640: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
                   2641:                return "refused:c:$crole&$cqual"; 
                   2642:             }
                   2643:         }
1.191     harris41 2644:     }
1.12      www      2645:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2646:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21      www      2647: 	        "rolesdef_$rolename=".
                   2648:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.12      www      2649:     return reply($command,$ENV{'user.home'});
                   2650:   } else {
                   2651:     return 'refused';
                   2652:   }
1.105     harris41 2653: }
                   2654: 
                   2655: # ---------------- Make a metadata query against the network of library servers
                   2656: 
                   2657: sub metadata_query {
1.244     matthew  2658:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 2659:     my %rhash;
1.244     matthew  2660:     my @server_list = (defined($server_array) ? @$server_array
                   2661:                                               : keys(%libserv) );
                   2662:     for my $server (@server_list) {
1.118     harris41 2663: 	unless ($custom or $customshow) {
                   2664: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   2665: 	    $rhash{$server}=$reply;
                   2666: 	}
                   2667: 	else {
                   2668: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   2669: 			     &escape($custom).':'.&escape($customshow),
                   2670: 			     $server);
                   2671: 	    $rhash{$server}=$reply;
                   2672: 	}
1.112     harris41 2673:     }
1.118     harris41 2674:     return \%rhash;
1.240     www      2675: }
                   2676: 
                   2677: # ----------------------------------------- Send log queries and wait for reply
                   2678: 
                   2679: sub log_query {
                   2680:     my ($uname,$udom,$query,%filters)=@_;
                   2681:     my $uhome=&homeserver($uname,$udom);
                   2682:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   2683:     my $uhost=$hostname{$uhome};
1.241     www      2684:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      2685:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   2686:                        $uhome);
                   2687:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242     www      2688:     return get_query_reply($queryid);
                   2689: }
                   2690: 
                   2691: sub get_query_reply {
                   2692:     my $queryid=shift;
1.240     www      2693:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   2694:     my $reply='';
                   2695:     for (1..100) {
                   2696: 	sleep 2;
                   2697:         if (-e $replyfile.'.end') {
                   2698: 	    if (my $fh=Apache::File->new($replyfile)) {
                   2699:                $reply.=<$fh>;
                   2700:                $fh->close;
                   2701: 	   } else { return 'error: reply_file_error'; }
1.242     www      2702:            return &unescape($reply);
                   2703: 	}
1.240     www      2704:     }
1.242     www      2705:     return 'timeout:'.$queryid;
1.240     www      2706: }
                   2707: 
                   2708: sub courselog_query {
1.241     www      2709: #
                   2710: # possible filters:
                   2711: # url: url or symb
                   2712: # username
                   2713: # domain
                   2714: # action: view, submit, grade
                   2715: # start: timestamp
                   2716: # end: timestamp
                   2717: #
1.240     www      2718:     my (%filters)=@_;
                   2719:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241     www      2720:     if ($filters{'url'}) {
                   2721: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   2722:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   2723:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   2724:     }
1.240     www      2725:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   2726:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   2727:     return &log_query($cname,$cdom,'courselog',%filters);
                   2728: }
                   2729: 
                   2730: sub userlog_query {
                   2731:     my ($uname,$udom,%filters)=@_;
                   2732:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      2733: }
                   2734: 
                   2735: # ------------------------------------------------------------------ Plain Text
                   2736: 
                   2737: sub plaintext {
1.22      www      2738:     my $short=shift;
                   2739:     return $prp{$short};
1.12      www      2740: }
                   2741: 
                   2742: # ----------------------------------------------------------------- Assign Role
                   2743: 
                   2744: sub assignrole {
1.357     www      2745:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      2746:     my $mrole;
                   2747:     if ($role =~ /^cr\//) {
1.393     www      2748:         my $cwosec=$url;
                   2749:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   2750: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      2751:            &logthis('Refused custom assignrole: '.
                   2752:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2753: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2754:            return 'refused'; 
                   2755:         }
1.21      www      2756:         $mrole='cr';
                   2757:     } else {
1.82      www      2758:         my $cwosec=$url;
1.83      www      2759:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      2760:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      2761:            &logthis('Refused assignrole: '.
                   2762:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   2763: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
                   2764:            return 'refused'; 
                   2765:         }
1.21      www      2766:         $mrole=$role;
                   2767:     }
                   2768:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2769:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      2770:     if ($end) { $command.='_'.$end; }
1.21      www      2771:     if ($start) {
                   2772: 	if ($end) { 
1.81      www      2773:            $command.='_'.$start; 
1.21      www      2774:         } else {
1.81      www      2775:            $command.='_0_'.$start;
1.21      www      2776:         }
                   2777:     }
1.357     www      2778: # actually delete
                   2779:     if ($deleteflag) {
1.373     www      2780: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      2781: # modify command to delete the role
                   2782:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
                   2783:                 "$udom:$uname:$url".'_'."$mrole";
1.373     www      2784: 	   &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      2785: # set start and finish to negative values for userrolelog
                   2786:            $start=-1;
                   2787:            $end=-1;
                   2788:         }
                   2789:     }
                   2790: # send command
1.349     www      2791:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      2792: # log new user role if status is ok
1.349     www      2793:     if ($answer eq 'ok') {
                   2794: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   2795:     }
                   2796:     return $answer;
1.169     harris41 2797: }
                   2798: 
                   2799: # -------------------------------------------------- Modify user authentication
1.197     www      2800: # Overrides without validation
                   2801: 
1.169     harris41 2802: sub modifyuserauth {
                   2803:     my ($udom,$uname,$umode,$upass)=@_;
                   2804:     my $uhome=&homeserver($uname,$udom);
1.197     www      2805:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   2806:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272     matthew  2807:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2808:              ' in domain '.$ENV{'request.role.domain'});  
1.169     harris41 2809:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   2810: 		     &escape($upass),$uhome);
1.197     www      2811:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
                   2812:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   2813:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   2814:     &log($udom,,$uname,$uhome,
                   2815:         'Authentication changed by '.$ENV{'user.domain'}.', '.
                   2816:                                      $ENV{'user.name'}.', '.$umode.
                   2817:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 2818:     unless ($reply eq 'ok') {
1.197     www      2819:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 2820: 	return 'error: '.$reply;
                   2821:     }   
1.170     harris41 2822:     return 'ok';
1.80      www      2823: }
                   2824: 
1.81      www      2825: # --------------------------------------------------------------- Modify a user
1.80      www      2826: 
1.81      www      2827: sub modifyuser {
1.206     matthew  2828:     my ($udom,    $uname, $uid,
                   2829:         $umode,   $upass, $first,
                   2830:         $middle,  $last,  $gene,
1.387     www      2831:         $forceid, $desiredhome, $email)=@_;
1.198     www      2832:     $udom=~s/\W//g;
                   2833:     $uname=~s/\W//g;
1.81      www      2834:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2835:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  2836: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   2837:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   2838:                                      ' desiredhome not specified'). 
1.272     matthew  2839:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
                   2840:              ' in domain '.$ENV{'request.role.domain'});
1.230     stredwic 2841:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      2842: # ----------------------------------------------------------------- Create User
1.406     albertel 2843:     if (($uhome eq 'no_host') && 
                   2844: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      2845:         my $unhome='';
1.209     matthew  2846:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   2847:             $unhome = $desiredhome;
                   2848: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80      www      2849: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209     matthew  2850:         } else { # load balancing routine for determining $unhome
1.80      www      2851:             my $tryserver;
1.81      www      2852:             my $loadm=10000000;
1.80      www      2853:             foreach $tryserver (keys %libserv) {
                   2854: 	       if ($hostdom{$tryserver} eq $udom) {
                   2855:                   my $answer=reply('load',$tryserver);
                   2856:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   2857: 		      $loadm=$answer;
                   2858:                       $unhome=$tryserver;
                   2859:                   }
                   2860: 	       }
                   2861: 	    }
                   2862:         }
                   2863:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  2864: 	    return 'error: unable to find a home server for '.$uname.
                   2865:                    ' in domain '.$udom;
1.80      www      2866:         }
                   2867:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   2868:                          &escape($upass),$unhome);
                   2869: 	unless ($reply eq 'ok') {
                   2870:             return 'error: '.$reply;
                   2871:         }   
1.230     stredwic 2872:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      2873:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  2874: 	    return 'error: unable verify users home machine.';
1.80      www      2875:         }
1.209     matthew  2876:     }   # End of creation of new user
1.80      www      2877: # ---------------------------------------------------------------------- Add ID
                   2878:     if ($uid) {
                   2879:        $uid=~tr/A-Z/a-z/;
                   2880:        my %uidhash=&idrget($udom,$uname);
1.196     www      2881:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   2882:          && (!$forceid)) {
1.80      www      2883: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  2884: 	      return 'error: user id "'.$uid.'" does not match '.
                   2885:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      2886:           }
                   2887:        } else {
                   2888: 	  &idput($udom,($uname => $uid));
                   2889:        }
                   2890:     }
                   2891: # -------------------------------------------------------------- Add names, etc
1.313     matthew  2892:     my @tmp=&get('environment',
1.134     albertel 2893: 		   ['firstname','middlename','lastname','generation'],
                   2894: 		   $udom,$uname);
1.313     matthew  2895:     my %names;
                   2896:     if ($tmp[0] =~ m/^error:.*/) { 
                   2897:         %names=(); 
                   2898:     } else {
                   2899:         %names = @tmp;
                   2900:     }
1.388     www      2901: #
                   2902: # Make sure to not trash student environment if instructor does not bother
                   2903: # to supply name and email information
                   2904: #
                   2905:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  2906:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      2907:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  2908:     if (defined($gene))   { $names{'generation'} = $gene; }
1.388     www      2909:     if ($email)  { $names{'notification'} = $email;
                   2910:                    $names{'critnotification'} = $email; }
1.387     www      2911: 
1.134     albertel 2912:     my $reply = &put('environment', \%names, $udom,$uname);
                   2913:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      2914:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      2915:              $umode.', '.$first.', '.$middle.', '.
                   2916: 	     $last.', '.$gene.' by '.
                   2917:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134     albertel 2918:     return 'ok';
1.80      www      2919: }
                   2920: 
1.81      www      2921: # -------------------------------------------------------------- Modify student
1.80      www      2922: 
1.81      www      2923: sub modifystudent {
                   2924:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.387     www      2925:         $end,$start,$forceid,$desiredhome,$email)=@_;
1.81      www      2926:     my $cid='';
                   2927:     unless ($cid=$ENV{'request.course.id'}) {
1.80      www      2928: 	return 'not_in_class';
                   2929:     }
                   2930: # --------------------------------------------------------------- Make the user
1.81      www      2931:     my $reply=&modifyuser
1.209     matthew  2932: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      2933:          $desiredhome,$email);
1.80      www      2934:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  2935:     # This will cause &modify_student_enrollment to get the uid from the
                   2936:     # students environment
                   2937:     $uid = undef if (!$forceid);
                   2938:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
                   2939:                                         $last,$gene,$usec,$end,$start);
                   2940:     return $reply;
                   2941: }
                   2942: 
                   2943: sub modify_student_enrollment {
                   2944:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
                   2945:     # Get the course id from the environment
                   2946:     my $cid='';
                   2947:     unless ($cid=$ENV{'request.course.id'}) {
                   2948: 	return 'not_in_class';
                   2949:     }
                   2950:     # Make sure the user exists
1.81      www      2951:     my $uhome=&homeserver($uname,$udom);
                   2952:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   2953: 	return 'error: no such user';
                   2954:     }
1.297     matthew  2955:     #
                   2956:     # Get student data if we were not given enough information
                   2957:     if (!defined($first)  || $first  eq '' || 
                   2958:         !defined($last)   || $last   eq '' || 
                   2959:         !defined($uid)    || $uid    eq '' || 
                   2960:         !defined($middle) || $middle eq '' || 
                   2961:         !defined($gene)   || $gene   eq '') {
1.294     matthew  2962:         # They did not supply us with enough data to enroll the student, so
                   2963:         # we need to pick up more information.
1.297     matthew  2964:         my %tmp = &get('environment',
1.294     matthew  2965:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  2966:                        ,$udom,$uname);
                   2967: 
                   2968:         foreach (keys(%tmp)) {
                   2969:             &logthis("key $_ = ".$tmp{$_});
                   2970:         }
1.294     matthew  2971:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   2972:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   2973:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  2974:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  2975:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   2976:     }
                   2977:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
                   2978:                                                            $first,$middle);
1.297     matthew  2979:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81      www      2980: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
                   2981:                       &escape($uname.':'.$udom).'='.
1.294     matthew  2982:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
1.81      www      2983: 	              $ENV{'course.'.$cid.'.home'});
                   2984:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   2985: 	return 'error: '.$reply;
                   2986:     }
1.297     matthew  2987:     # Add student role to user
1.83      www      2988:     my $uurl='/'.$cid;
1.81      www      2989:     $uurl=~s/\_/\//g;
                   2990:     if ($usec) {
                   2991: 	$uurl.='/'.$usec;
                   2992:     }
                   2993:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      2994: }
                   2995: 
1.84      www      2996: # ------------------------------------------------- Write to course preferences
                   2997: 
                   2998: sub writecoursepref {
                   2999:     my ($courseid,%prefs)=@_;
                   3000:     $courseid=~s/^\///;
                   3001:     $courseid=~s/\_/\//g;
                   3002:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   3003:     my $chome=homeserver($cnum,$cdomain);
                   3004:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   3005: 	return 'error: no such course';
                   3006:     }
                   3007:     my $cstring='';
1.191     harris41 3008:     foreach (keys %prefs) {
1.84      www      3009: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 3010:     }
1.84      www      3011:     $cstring=~s/\&$//;
                   3012:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   3013: }
                   3014: 
                   3015: # ---------------------------------------------------------- Make/modify course
                   3016: 
                   3017: sub createcourse {
1.271     www      3018:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84      www      3019:     $url=&declutter($url);
                   3020:     my $cid='';
1.264     matthew  3021:     unless (&allowed('ccc',$udom)) {
1.84      www      3022:         return 'refused';
                   3023:     }
                   3024: # ------------------------------------------------------------------- Create ID
                   3025:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3026:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   3027: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 3028:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      3029:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3030:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3031:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 3032:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      3033:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3034:            return 'error: unable to generate unique course-ID';
                   3035:        } 
                   3036:    }
1.264     matthew  3037: # ------------------------------------------------ Check supplied server name
                   3038:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
                   3039:     if (! exists($libserv{$course_server})) {
                   3040:         return 'error:bad server name '.$course_server;
                   3041:     }
1.84      www      3042: # ------------------------------------------------------------- Make the course
                   3043:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  3044:                       $course_server);
1.84      www      3045:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 3046:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      3047:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3048: 	return 'error: no such course';
                   3049:     }
1.271     www      3050: # ----------------------------------------------------------------- Course made
1.358     www      3051: # log existance
                   3052:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
                   3053:                  $uhome);
                   3054:     &flushcourselogs();
                   3055: # set toplevel url
1.271     www      3056:     my $topurl=$url;
                   3057:     unless ($nonstandard) {
                   3058: # ------------------------------------------ For standard courses, make top url
                   3059:         my $mapurl=&clutter($url);
1.278     www      3060:         if ($mapurl eq '/res/') { $mapurl=''; }
1.271     www      3061:         $ENV{'form.initmap'}=(<<ENDINITMAP);
                   3062: <map>
                   3063: <resource id="1" type="start"></resource>
                   3064: <resource id="2" src="$mapurl"></resource>
                   3065: <resource id="3" type="finish"></resource>
                   3066: <link index="1" from="1" to="2"></link>
                   3067: <link index="2" from="2" to="3"></link>
                   3068: </map>
                   3069: ENDINITMAP
                   3070:         $topurl=&declutter(
                   3071:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   3072:                           );
                   3073:     }
                   3074: # ----------------------------------------------------------- Write preferences
1.84      www      3075:     &writecoursepref($udom.'_'.$uname,
                   3076:                      ('description' => $description,
1.271     www      3077:                       'url'         => $topurl));
1.84      www      3078:     return '/'.$udom.'/'.$uname;
                   3079: }
                   3080: 
1.21      www      3081: # ---------------------------------------------------------- Assign Custom Role
                   3082: 
                   3083: sub assigncustomrole {
1.357     www      3084:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      3085:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      3086:                        $end,$start,$deleteflag);
1.21      www      3087: }
                   3088: 
                   3089: # ----------------------------------------------------------------- Revoke Role
                   3090: 
                   3091: sub revokerole {
1.357     www      3092:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      3093:     my $now=time;
1.357     www      3094:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      3095: }
                   3096: 
                   3097: # ---------------------------------------------------------- Revoke Custom Role
                   3098: 
                   3099: sub revokecustomrole {
1.357     www      3100:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      3101:     my $now=time;
1.357     www      3102:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   3103:            $deleteflag);
1.17      www      3104: }
                   3105: 
                   3106: # ------------------------------------------------------------ Directory lister
                   3107: 
                   3108: sub dirlist {
1.253     stredwic 3109:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   3110: 
1.18      www      3111:     $uri=~s/^\///;
                   3112:     $uri=~s/\/$//;
1.253     stredwic 3113:     my ($udom, $uname);
                   3114:     (undef,$udom,$uname)=split(/\//,$uri);
                   3115:     if(defined($userdomain)) {
                   3116:         $udom = $userdomain;
                   3117:     }
                   3118:     if(defined($username)) {
                   3119:         $uname = $username;
                   3120:     }
                   3121: 
                   3122:     my $dirRoot = $perlvar{'lonDocRoot'};
                   3123:     if(defined($alternateDirectoryRoot)) {
                   3124:         $dirRoot = $alternateDirectoryRoot;
                   3125:         $dirRoot =~ s/\/$//;
                   3126:     }
                   3127: 
                   3128:     if($udom) {
                   3129:         if($uname) {
                   3130:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   3131:                               homeserver($uname,$udom));
                   3132:             return split(/:/,$listing);
                   3133:         } elsif(!defined($alternateDirectoryRoot)) {
                   3134:             my $tryserver;
                   3135:             my %allusers=();
                   3136:             foreach $tryserver (keys %libserv) {
                   3137:                 if($hostdom{$tryserver} eq $udom) {
                   3138:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   3139:                                       $udom, $tryserver);
                   3140:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
                   3141:                         && ($listing ne 'con_lost')) {
                   3142:                         foreach (split(/:/,$listing)) {
                   3143:                             my ($entry,@stat)=split(/&/,$_);
                   3144:                             $allusers{$entry}=1;
                   3145:                         }
                   3146:                     }
1.191     harris41 3147:                 }
1.253     stredwic 3148:             }
                   3149:             my $alluserstr='';
                   3150:             foreach (sort keys %allusers) {
                   3151:                 $alluserstr.=$_.'&user:';
                   3152:             }
                   3153:             $alluserstr=~s/:$//;
                   3154:             return split(/:/,$alluserstr);
                   3155:         } else {
                   3156:             my @emptyResults = ();
                   3157:             push(@emptyResults, 'missing user name');
                   3158:             return split(':',@emptyResults);
                   3159:         }
                   3160:     } elsif(!defined($alternateDirectoryRoot)) {
                   3161:         my $tryserver;
                   3162:         my %alldom=();
                   3163:         foreach $tryserver (keys %libserv) {
                   3164:             $alldom{$hostdom{$tryserver}}=1;
                   3165:         }
                   3166:         my $alldomstr='';
                   3167:         foreach (sort keys %alldom) {
1.397     albertel 3168:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 3169:         }
                   3170:         $alldomstr=~s/:$//;
                   3171:         return split(/:/,$alldomstr);       
                   3172:     } else {
                   3173:         my @emptyResults = ();
                   3174:         push(@emptyResults, 'missing domain');
                   3175:         return split(':',@emptyResults);
1.275     stredwic 3176:     }
                   3177: }
                   3178: 
                   3179: # --------------------------------------------- GetFileTimestamp
                   3180: # This function utilizes dirlist and returns the date stamp for
                   3181: # when it was last modified.  It will also return an error of -1
                   3182: # if an error occurs
                   3183: 
1.410     matthew  3184: ##
                   3185: ## FIXME: This subroutine assumes its caller knows something about the
                   3186: ## directory structure of the home server for the student ($root).
                   3187: ## Not a good assumption to make.  Since this is for looking up files
                   3188: ## in user directories, the full path should be constructed by lond, not
                   3189: ## whatever machine we request data from.
                   3190: ##
1.275     stredwic 3191: sub GetFileTimestamp {
                   3192:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   3193:     $studentDomain=~s/\W//g;
                   3194:     $studentName=~s/\W//g;
                   3195:     my $subdir=$studentName.'__';
                   3196:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3197:     my $proname="$studentDomain/$subdir/$studentName";
                   3198:     $proname .= '/'.$filename;
1.375     matthew  3199:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   3200:                                               $studentName, $root);
1.275     stredwic 3201:     my @stats = split('&', $fileStat);
                   3202:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  3203:         # @stats contains first the filename, then the stat output
                   3204:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 3205:     } else {
                   3206:         return -1;
1.253     stredwic 3207:     }
1.26      www      3208: }
                   3209: 
                   3210: # -------------------------------------------------------- Value of a Condition
                   3211: 
1.40      www      3212: sub directcondval {
                   3213:     my $number=shift;
                   3214:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   3215:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   3216:     } else {
                   3217:        return 2;
                   3218:     }
                   3219: }
                   3220: 
1.26      www      3221: sub condval {
                   3222:     my $condidx=shift;
                   3223:     my $result=0;
1.54      www      3224:     my $allpathcond='';
1.191     harris41 3225:     foreach (split(/\|/,$condidx)) {
1.54      www      3226:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   3227: 	   $allpathcond.=
                   3228:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   3229:        }
1.191     harris41 3230:     }
1.54      www      3231:     $allpathcond=~s/\|$//;
1.33      www      3232:     if ($ENV{'request.course.id'}) {
1.54      www      3233:        if ($allpathcond) {
1.26      www      3234:           my $operand='|';
                   3235: 	  my @stack;
1.191     harris41 3236:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      3237:               if ($_ eq '(') {
                   3238:                  push @stack,($operand,$result)
                   3239:               } elsif ($_ eq ')') {
                   3240:                   my $before=pop @stack;
                   3241: 		  if (pop @stack eq '&') {
                   3242: 		      $result=$result>$before?$before:$result;
                   3243:                   } else {
                   3244:                       $result=$result>$before?$result:$before;
                   3245:                   }
                   3246:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   3247:                   $operand=$_;
                   3248:               } else {
1.40      www      3249:                   my $new=directcondval($_);
1.26      www      3250:                   if ($operand eq '&') {
                   3251:                      $result=$result>$new?$new:$result;
                   3252:                   } else {
                   3253:                      $result=$result>$new?$result:$new;
1.191     harris41 3254:                   }
1.26      www      3255:               }
1.191     harris41 3256:           }
1.26      www      3257:        }
                   3258:     }
                   3259:     return $result;
1.279     www      3260: }
                   3261: 
                   3262: # ---------------------------------------------------- Devalidate courseresdata
                   3263: 
                   3264: sub devalidatecourseresdata {
                   3265:     my ($coursenum,$coursedomain)=@_;
                   3266:     my $hashid=$coursenum.':'.$coursedomain;
                   3267:     delete $courseresdatacache{$hashid.'.time'};
1.28      www      3268: }
                   3269: 
1.200     www      3270: # --------------------------------------------------- Course Resourcedata Query
                   3271: 
                   3272: sub courseresdata {
                   3273:     my ($coursenum,$coursedomain,@which)=@_;
                   3274:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   3275:     my $hashid=$coursenum.':'.$coursedomain;
1.250     albertel 3276:     my $dodump=0;
                   3277:     if (!defined($courseresdatacache{$hashid.'.time'})) {
                   3278: 	$dodump=1;
                   3279:     } else {
                   3280: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
                   3281:     }
                   3282:     if ($dodump) {
1.251     albertel 3283: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
                   3284: 	my ($tmp) = keys(%dumpreply);
                   3285: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   3286: 	    $courseresdatacache{$hashid.'.time'}=time;
                   3287: 	    $courseresdatacache{$hashid}=\%dumpreply;
1.306     albertel 3288: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3289: 	    return $tmp;
1.250     albertel 3290: 	}
                   3291:     }
1.251     albertel 3292:     foreach my $item (@which) {
1.287     albertel 3293: 	if (defined($courseresdatacache{$hashid}->{$item})) {
1.251     albertel 3294: 	    return $courseresdatacache{$hashid}->{$item};
                   3295: 	}
1.250     albertel 3296:     }
1.291     albertel 3297:     return undef;
1.200     www      3298: }
                   3299: 
1.379     matthew  3300: #
                   3301: # EXT resource caching routines
                   3302: #
                   3303: 
                   3304: sub clear_EXT_cache_status {
1.383     albertel 3305:     &delenv('cache.EXT.');
1.379     matthew  3306: }
                   3307: 
                   3308: sub EXT_cache_status {
                   3309:     my ($target_domain,$target_user) = @_;
1.383     albertel 3310:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389     www      3311:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379     matthew  3312:         # We know already the user has no data
                   3313:         return 1;
                   3314:     } else {
                   3315:         return 0;
                   3316:     }
                   3317: }
                   3318: 
                   3319: sub EXT_cache_set {
                   3320:     my ($target_domain,$target_user) = @_;
1.383     albertel 3321:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379     matthew  3322:     &appenv($cachename => time);
                   3323: }
                   3324: 
1.28      www      3325: # --------------------------------------------------------- Value of a Variable
1.58      www      3326: sub EXT {
1.395     albertel 3327:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 3328: 
1.68      www      3329:     unless ($varname) { return ''; }
1.218     albertel 3330:     #get real user name/domain, courseid and symb
                   3331:     my $courseid;
1.359     albertel 3332:     my $publicuser;
1.218     albertel 3333:     if (!($uname && $udom)) {
1.360     albertel 3334:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  3335: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 3336:       if (!$symbparm) {	$symbparm=$cursymb; }
                   3337:     } else {
                   3338: 	$courseid=$ENV{'request.course.id'};
                   3339:     }
1.48      www      3340:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   3341:     my $rest;
1.320     albertel 3342:     if (defined($therest[0])) {
1.48      www      3343:        $rest=join('.',@therest);
                   3344:     } else {
                   3345:        $rest='';
                   3346:     }
1.320     albertel 3347: 
1.57      www      3348:     my $qualifierrest=$qualifier;
                   3349:     if ($rest) { $qualifierrest.='.'.$rest; }
                   3350:     my $spacequalifierrest=$space;
                   3351:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      3352:     if ($realm eq 'user') {
1.48      www      3353: # --------------------------------------------------------------- user.resource
                   3354: 	if ($space eq 'resource') {
1.335     albertel 3355: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
                   3356: 		return $Apache::lonhomework::history{$qualifierrest};
                   3357: 	    } else {
1.359     albertel 3358: 		my %restored;
                   3359: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
                   3360: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   3361: 		} else {
                   3362: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   3363: 		}
1.335     albertel 3364: 		return $restored{$qualifierrest};
                   3365: 	    }
1.48      www      3366: # ----------------------------------------------------------------- user.access
                   3367:         } elsif ($space eq 'access') {
1.218     albertel 3368: 	    # FIXME - not supporting calls for a specific user
1.48      www      3369:             return &allowed($qualifier,$rest);
                   3370: # ------------------------------------------ user.preferences, user.environment
                   3371:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 3372: 	    if (($uname eq $ENV{'user.name'}) &&
                   3373: 		($udom eq $ENV{'user.domain'})) {
                   3374: 		return $ENV{join('.',('environment',$qualifierrest))};
                   3375: 	    } else {
1.359     albertel 3376: 		my %returnhash;
                   3377: 		if (!$publicuser) {
                   3378: 		    %returnhash=&userenvironment($udom,$uname,
                   3379: 						 $qualifierrest);
                   3380: 		}
1.218     albertel 3381: 		return $returnhash{$qualifierrest};
                   3382: 	    }
1.48      www      3383: # ----------------------------------------------------------------- user.course
                   3384:         } elsif ($space eq 'course') {
1.218     albertel 3385: 	    # FIXME - not supporting calls for a specific user
1.48      www      3386:             return $ENV{join('.',('request.course',$qualifier))};
                   3387: # ------------------------------------------------------------------- user.role
                   3388:         } elsif ($space eq 'role') {
1.218     albertel 3389: 	    # FIXME - not supporting calls for a specific user
1.48      www      3390:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   3391:             if ($qualifier eq 'value') {
                   3392: 		return $role;
                   3393:             } elsif ($qualifier eq 'extent') {
                   3394:                 return $where;
                   3395:             }
                   3396: # ----------------------------------------------------------------- user.domain
                   3397:         } elsif ($space eq 'domain') {
1.218     albertel 3398:             return $udom;
1.48      www      3399: # ------------------------------------------------------------------- user.name
                   3400:         } elsif ($space eq 'name') {
1.218     albertel 3401:             return $uname;
1.48      www      3402: # ---------------------------------------------------- Any other user namespace
1.29      www      3403:         } else {
1.359     albertel 3404: 	    my %reply;
                   3405: 	    if (!$publicuser) {
                   3406: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   3407: 	    }
                   3408: 	    return $reply{$qualifierrest};
1.48      www      3409:         }
1.236     www      3410:     } elsif ($realm eq 'query') {
                   3411: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 3412:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   3413: 						[$spacequalifierrest]);
1.376     albertel 3414: 	return $ENV{'form.'.$spacequalifierrest}; 
1.236     www      3415:    } elsif ($realm eq 'request') {
1.48      www      3416: # ------------------------------------------------------------- request.browser
                   3417:         if ($space eq 'browser') {
                   3418: 	    return $ENV{'browser.'.$qualifier};
1.57      www      3419: # ------------------------------------------------------------ request.filename
                   3420:         } else {
                   3421:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      3422:         }
1.28      www      3423:     } elsif ($realm eq 'course') {
1.48      www      3424: # ---------------------------------------------------------- course.description
1.218     albertel 3425:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      3426:     } elsif ($realm eq 'resource') {
1.165     www      3427: 
1.395     albertel 3428: 	my $section;
1.359     albertel 3429: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.165     www      3430: 
1.218     albertel 3431: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      3432: 
1.60      www      3433: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 3434: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   3435: 	    my $symbp=$symbparm;
1.409     www      3436: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 3437: 
                   3438: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   3439: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   3440: 
                   3441: 	    if (($ENV{'user.name'} eq $uname) &&
                   3442: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 3443: 		$section=$ENV{'request.course.sec'};
1.218     albertel 3444: 	    } else {
1.377     matthew  3445:                 if (! defined($usection)) {
                   3446:                     $section=&usection($udom,$uname,$courseid);
                   3447:                 } else {
                   3448:                     $section = $usection;
                   3449:                 }
1.218     albertel 3450: 	    }
                   3451: 
                   3452: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   3453: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   3454: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   3455: 
                   3456: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
                   3457: 	    my $courselevelr=$courseid.'.'.$symbparm;
                   3458: 	    my $courselevelm=$courseid.'.'.$mapparm;
1.69      www      3459: 
1.60      www      3460: # ----------------------------------------------------------- first, check user
1.379     matthew  3461: 	    #most student don\'t have any data set, check if there is some data
1.308     albertel 3462:             #every thirty minutes
1.379     matthew  3463: 	    if (! &EXT_cache_status($udom,$uname)) {
1.308     albertel 3464: 		my %resourcedata=&get('resourcedata',
                   3465: 				      [$courselevelr,$courselevelm,$courselevel],
                   3466: 				      $udom,$uname);
                   3467: 		my ($tmp)=keys(%resourcedata);
                   3468: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   3469: 		    if ($resourcedata{$courselevelr}) {
                   3470: 			return $resourcedata{$courselevelr}; }
                   3471: 		    if ($resourcedata{$courselevelm}) {
                   3472: 			return $resourcedata{$courselevelm}; }
                   3473: 		    if ($resourcedata{$courselevel}) {
                   3474: 			return $resourcedata{$courselevel}; }
                   3475: 		} else {
                   3476: 		    if ($tmp!~/No such file/) {
                   3477: 			&logthis("<font color=blue>WARNING:".
                   3478: 				 " Trying to get resource data for ".
                   3479: 				 $uname." at ".$udom.": ".
                   3480: 				 $tmp."</font>");
                   3481: 		    } elsif ($tmp=~/error:No such file/) {
1.379     matthew  3482:                         &EXT_cache_set($udom,$uname);
1.308     albertel 3483: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   3484: 			return $tmp;
                   3485: 		    }
1.218     albertel 3486: 		}
                   3487: 	    }
1.95      www      3488: 
1.60      www      3489: # -------------------------------------------------------- second, check course
1.96      www      3490: 
1.218     albertel 3491: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   3492: 					  $ENV{'course.'.$courseid.'.domain'},
                   3493: 					  ($seclevelr,$seclevelm,$seclevel,
                   3494: 					   $courselevelr,$courselevelm,
                   3495: 					   $courselevel));
1.287     albertel 3496: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      3497: 
1.60      www      3498: # ------------------------------------------------------ third, check map parms
1.218     albertel 3499: 	    my %parmhash=();
                   3500: 	    my $thisparm='';
                   3501: 	    if (tie(%parmhash,'GDBM_File',
                   3502: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 3503: 		    &GDBM_READER(),0640)) {
1.218     albertel 3504: 		$thisparm=$parmhash{$symbparm};
                   3505: 		untie(%parmhash);
                   3506: 	    }
                   3507: 	    if ($thisparm) { return $thisparm; }
                   3508: 	}
1.60      www      3509: # --------------------------------------------- last, look in resource metadata
1.71      www      3510: 
1.218     albertel 3511: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 3512: 	my $filename;
                   3513: 	if (!$symbparm) { $symbparm=&symbread(); }
                   3514: 	if ($symbparm) {
1.409     www      3515: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 3516: 	} else {
                   3517: 	    $filename=$ENV{'request.filename'};
                   3518: 	}
                   3519: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 3520: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 3521: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 3522: 	if (defined($metadata)) { return $metadata; }
1.142     www      3523: 
1.145     www      3524: # ------------------------------------------------------------------ Cascade up
1.218     albertel 3525: 	unless ($space eq '0') {
1.336     albertel 3526: 	    my @parts=split(/_/,$space);
                   3527: 	    my $id=pop(@parts);
                   3528: 	    my $part=join('_',@parts);
                   3529: 	    if ($part eq '') { $part='0'; }
                   3530: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 3531: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 3532: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 3533: 	}
1.395     albertel 3534: 	if ($recurse) { return undef; }
                   3535: 	my $pack_def=&packages_tab_default($filename,$varname);
                   3536: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      3537: 
1.48      www      3538: # ---------------------------------------------------- Any other user namespace
                   3539:     } elsif ($realm eq 'environment') {
                   3540: # ----------------------------------------------------------------- environment
1.219     albertel 3541: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   3542: 	    return $ENV{'environment.'.$spacequalifierrest};
                   3543: 	} else {
                   3544: 	    my %returnhash=&userenvironment($udom,$uname,
                   3545: 					    $spacequalifierrest);
                   3546: 	    return $returnhash{$spacequalifierrest};
                   3547: 	}
1.28      www      3548:     } elsif ($realm eq 'system') {
1.48      www      3549: # ----------------------------------------------------------------- system.time
                   3550: 	if ($space eq 'time') {
                   3551: 	    return time;
                   3552:         }
1.28      www      3553:     }
1.48      www      3554:     return '';
1.61      www      3555: }
                   3556: 
1.395     albertel 3557: sub packages_tab_default {
                   3558:     my ($uri,$varname)=@_;
                   3559:     my (undef,$part,$name)=split(/\./,$varname);
                   3560:     my $packages=&metadata($uri,'packages');
                   3561:     foreach my $package (split(/,/,$packages)) {
                   3562: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
                   3563: 	if ($pack_part eq $part) {
                   3564: 	    return $packagetab{"$pack_type&$name&default"};
                   3565: 	}
                   3566:     }
                   3567:     return undef;
                   3568: }
                   3569: 
1.334     albertel 3570: sub add_prefix_and_part {
                   3571:     my ($prefix,$part)=@_;
                   3572:     my $keyroot;
                   3573:     if (defined($prefix) && $prefix !~ /^__/) {
                   3574: 	# prefix that has a part already
                   3575: 	$keyroot=$prefix;
                   3576:     } elsif (defined($prefix)) {
                   3577: 	# prefix that is missing a part
                   3578: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   3579:     } else {
                   3580: 	# no prefix at all
                   3581: 	if (defined($part)) { $keyroot='_'.$part; }
                   3582:     }
                   3583:     return $keyroot;
                   3584: }
                   3585: 
1.71      www      3586: # ---------------------------------------------------------------- Get metadata
                   3587: 
                   3588: sub metadata {
1.176     www      3589:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.78      www      3590: 
1.71      www      3591:     $uri=&declutter($uri);
1.288     albertel 3592:     # if it is a non metadata possible uri return quickly
1.293     matthew  3593:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
                   3594:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
1.288     albertel 3595: 	return '';
                   3596:     }
1.73      www      3597:     my $filename=$uri;
                   3598:     $uri=~s/\.meta$//;
1.172     www      3599: #
                   3600: # Is the metadata already cached?
1.177     www      3601: # Look at timestamp of caching
1.172     www      3602: # Everything is cached by the main uri, libraries are never directly cached
                   3603: #
1.277     albertel 3604:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
1.172     www      3605: #
                   3606: # Is this a recursive call for a library?
                   3607: #
1.171     www      3608:         if ($liburi) {
                   3609: 	    $liburi=&declutter($liburi);
                   3610:             $filename=$liburi;
1.401     bowersj2 3611:         } else {
                   3612: 	    delete($metacache{$uri.':packages'});
                   3613: 	}
1.140     www      3614:         my %metathesekeys=();
1.73      www      3615:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.335     albertel 3616: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
1.208     albertel 3617:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      3618:         my $token;
1.140     www      3619:         undef %metathesekeys;
1.71      www      3620:         while ($token=$parser->get_token) {
1.339     albertel 3621: 	    if ($token->[0] eq 'S') {
                   3622: 		if (defined($token->[2]->{'package'})) {
1.172     www      3623: #
                   3624: # This is a package - get package info
                   3625: #
1.339     albertel 3626: 		    my $package=$token->[2]->{'package'};
                   3627: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3628: 		    if (defined($token->[2]->{'id'})) { 
                   3629: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   3630: 		    }
                   3631: 		    if ($metacache{$uri.':packages'}) {
                   3632: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
                   3633: 		    } else {
                   3634: 			$metacache{$uri.':packages'}=$package.$keyroot;
                   3635: 		    }
                   3636: 		    foreach (keys %packagetab) {
                   3637: 			if ($_=~/^$package\&/) {
                   3638: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 3639: 			    # ignore package.tab specified default values
                   3640:                             # here &package_tab_default() will fetch those
                   3641: 			    if ($subp eq 'default') { next; }
1.339     albertel 3642: 			    my $value=$packagetab{$_};
                   3643: 			    my $part=$keyroot;
                   3644: 			    $part=~s/^\_//;
                   3645: 			    if ($subp eq 'display') {
                   3646: 				$value.=' [Part: '.$part.']';
                   3647: 			    }
                   3648: 			    my $unikey='parameter'.$keyroot.'_'.$name;
1.395     albertel 3649: 			    $metacache{$uri.':'.$unikey.'.part'}=$part;
                   3650: 			    $metathesekeys{$unikey}=1;
1.339     albertel 3651: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
                   3652: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
                   3653: 			    }
                   3654: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
                   3655: 				$metacache{$uri.':'.$unikey}=
1.356     albertel 3656: 				    $metacache{$uri.':'.$unikey.'.default'};
                   3657: 			    }
1.339     albertel 3658: 			}
                   3659: 		    }
                   3660: 		} else {
1.172     www      3661: #
                   3662: # This is not a package - some other kind of start tag
1.339     albertel 3663: #
                   3664: 		    my $entry=$token->[1];
                   3665: 		    my $unikey;
                   3666: 		    if ($entry eq 'import') {
                   3667: 			$unikey='';
                   3668: 		    } else {
                   3669: 			$unikey=$entry;
                   3670: 		    }
                   3671: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   3672: 
                   3673: 		    if (defined($token->[2]->{'id'})) { 
                   3674: 			$unikey.='_'.$token->[2]->{'id'}; 
                   3675: 		    }
1.175     www      3676: 
1.339     albertel 3677: 		    if ($entry eq 'import') {
1.175     www      3678: #
                   3679: # Importing a library here
1.339     albertel 3680: #
                   3681: 			if ($depthcount<20) {
                   3682: 			    my $location=$parser->get_text('/import');
                   3683: 			    my $dir=$filename;
                   3684: 			    $dir=~s|[^/]*$||;
                   3685: 			    $location=&filelocation($dir,$location);
                   3686: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3687: 							       $location,$unikey,
                   3688: 							       $depthcount+1)))) {
                   3689: 				$metathesekeys{$_}=1;
                   3690: 			    }
                   3691: 			}
                   3692: 		    } else { 
                   3693: 			
                   3694: 			if (defined($token->[2]->{'name'})) { 
                   3695: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   3696: 			}
                   3697: 			$metathesekeys{$unikey}=1;
                   3698: 			foreach (@{$token->[3]}) {
                   3699: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
                   3700: 			}
                   3701: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
                   3702: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
                   3703: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   3704: 		 # only ws inside the tag, and not in default, so use default
                   3705: 		 # as value
                   3706: 			    $metacache{$uri.':'.$unikey}=$default;
                   3707: 			} else {
1.321     albertel 3708: 		  # either something interesting inside the tag or default
                   3709:                   # uninteresting
1.339     albertel 3710: 			    $metacache{$uri.':'.$unikey}=$internaltext;
                   3711: 			}
1.172     www      3712: # end of not-a-package not-a-library import
1.339     albertel 3713: 		    }
1.172     www      3714: # end of not-a-package start tag
1.339     albertel 3715: 		}
1.172     www      3716: # the next is the end of "start tag"
1.339     albertel 3717: 	    }
                   3718: 	}
1.338     www      3719: # are there custom rights to evaluate
                   3720: 	if ($metacache{$uri.':copyright'} eq 'custom') {
1.339     albertel 3721: 
1.338     www      3722:     #
                   3723:     # Importing a rights file here
1.339     albertel 3724:     #
                   3725: 	    unless ($depthcount) {
                   3726: 		my $location=$metacache{$uri.':customdistributionfile'};
                   3727: 		my $dir=$filename;
                   3728: 		$dir=~s|[^/]*$||;
                   3729: 		$location=&filelocation($dir,$location);
                   3730: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   3731: 						   $location,'_rights',
                   3732: 						   $depthcount+1)))) {
                   3733: 		    $metathesekeys{$_}=1;
                   3734: 		}
                   3735: 	    }
                   3736: 	}
                   3737: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
1.261     albertel 3738: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
1.339     albertel 3739: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
                   3740: 	$metacache{$uri.':cachedtimestamp'}=time;
1.177     www      3741: # this is the end of "was not already recently cached
1.71      www      3742:     }
                   3743:     return $metacache{$uri.':'.$what};
1.261     albertel 3744: }
                   3745: 
                   3746: sub metadata_generate_part0 {
                   3747:     my ($metadata,$metacache,$uri) = @_;
                   3748:     my %allnames;
                   3749:     foreach my $metakey (sort keys %$metadata) {
                   3750: 	if ($metakey=~/^parameter\_(.*)/) {
                   3751: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
                   3752: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
1.356     albertel 3753: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 3754: 	    $allnames{$name}=$part;
                   3755: 	  }
                   3756: 	}
                   3757:     }
                   3758:     foreach my $name (keys(%allnames)) {
                   3759:       $$metadata{"parameter_0_$name"}=1;
                   3760:       my $key="$uri:parameter_0_$name";
                   3761:       $$metacache{"$key.part"}='0';
                   3762:       $$metacache{"$key.name"}=$name;
                   3763:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
                   3764: 					   $allnames{$name}.'_'.$name.
                   3765: 					   '.type'};
                   3766:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
                   3767: 			     '.display'};
                   3768:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
                   3769:       $olddis=~s/$expr/\[Part: 0\]/;
                   3770:       $$metacache{"$key.display"}=$olddis;
                   3771:     }
1.71      www      3772: }
                   3773: 
1.301     www      3774: # ------------------------------------------------- Get the title of a resource
                   3775: 
                   3776: sub gettitle {
                   3777:     my $urlsymb=shift;
                   3778:     my $symb=&symbread($urlsymb);
                   3779:     unless ($symb) {
                   3780: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
                   3781:         return &metadata($urlsymb,'title'); 
                   3782:     }
1.382     albertel 3783:     if ($titlecache{$symb}) {
                   3784: 	if (time < ($titlecache{$symb}[1] + 600)) {
                   3785: 	    return $titlecache{$symb}[0];
                   3786: 	} else {
                   3787: 	    delete($titlecache{$symb});
                   3788: 	}
                   3789:     }
1.409     www      3790:     my ($map,$resid,$url)=&decode_symb($symb);
1.301     www      3791:     my $title='';
                   3792:     my %bighash;
                   3793:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   3794:                             &GDBM_READER(),0640)) {
                   3795:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   3796:         $title=$bighash{'title_'.$mapid.'.'.$resid};
                   3797:         untie %bighash;
                   3798:     }
1.363     www      3799:     $title=~s/\&colon\;/\:/gs;
1.301     www      3800:     if ($title) {
1.382     albertel 3801:         $titlecache{$symb}=[$title,time];
1.301     www      3802:         return $title;
                   3803:     } else {
                   3804: 	return &metadata($urlsymb,'title');
                   3805:     }
                   3806: }
                   3807:     
1.31      www      3808: # ------------------------------------------------- Update symbolic store links
                   3809: 
                   3810: sub symblist {
                   3811:     my ($mapname,%newhash)=@_;
                   3812:     $mapname=declutter($mapname);
                   3813:     my %hash;
                   3814:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   3815:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3816:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 3817: 	    foreach (keys %newhash) {
1.211     www      3818:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
1.191     harris41 3819:             }
1.31      www      3820:             if (untie(%hash)) {
                   3821: 		return 'ok';
                   3822:             }
                   3823:         }
                   3824:     }
                   3825:     return 'error';
1.212     www      3826: }
                   3827: 
                   3828: # --------------------------------------------------------------- Verify a symb
                   3829: 
                   3830: sub symbverify {
                   3831:     my ($symb,$thisfn)=@_;
1.213     www      3832:     $thisfn=&declutter($thisfn);
1.215     www      3833: # direct jump to resource in page or to a sequence - will construct own symbs
                   3834:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   3835: # check URL part
1.409     www      3836:     my ($map,$resid,$url)=&decode_symb($symb);
1.213     www      3837:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
                   3838: 
1.216     www      3839:     $symb=&symbclean($symb);
1.213     www      3840: 
                   3841:     my %bighash;
                   3842:     my $okay=0;
                   3843:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3844:                             &GDBM_READER(),0640)) {
1.280     www      3845:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.216     www      3846:         unless ($ids) { 
                   3847:            $ids=$bighash{'ids_/'.$thisfn};
                   3848:         }
                   3849:         if ($ids) {
                   3850: # ------------------------------------------------------------------- Has ID(s)
                   3851: 	    foreach (split(/\,/,$ids)) {
                   3852:                my ($mapid,$resid)=split(/\./,$_);
                   3853:                if (
                   3854:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   3855:    eq $symb) { 
                   3856:                   $okay=1; 
                   3857:                }
                   3858: 	   }
                   3859:         }
1.213     www      3860: 	untie(%bighash);
                   3861:     }
                   3862:     return $okay;
1.31      www      3863: }
                   3864: 
1.210     www      3865: # --------------------------------------------------------------- Clean-up symb
                   3866: 
                   3867: sub symbclean {
                   3868:     my $symb=shift;
1.213     www      3869: 
1.210     www      3870: # remove version from map
                   3871:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      3872: 
1.210     www      3873: # remove version from URL
                   3874:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      3875: 
1.210     www      3876:     return $symb;
1.409     www      3877: }
                   3878: 
                   3879: # ---------------------------------------------- Split symb to find map and url
                   3880: 
                   3881: sub decode_symb {
                   3882:     return split(/\_\_\_/,shift);
1.210     www      3883: }
                   3884: 
1.31      www      3885: # ------------------------------------------------------ Return symb list entry
                   3886: 
                   3887: sub symbread {
1.249     www      3888:     my ($thisfn,$donotrecurse)=@_;
1.242     www      3889: # no filename provided? try from environment
1.44      www      3890:     unless ($thisfn) {
1.210     www      3891:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44      www      3892: 	$thisfn=$ENV{'request.filename'};
                   3893:     }
1.242     www      3894: # is that filename actually a symb? Verify, clean, and return
                   3895:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
                   3896: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
                   3897:     }
1.44      www      3898:     $thisfn=declutter($thisfn);
1.31      www      3899:     my %hash;
1.37      www      3900:     my %bighash;
                   3901:     my $syval='';
1.45      www      3902:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31      www      3903:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 3904:                       &GDBM_READER(),0640)) {
1.31      www      3905: 	    $syval=$hash{$thisfn};
1.37      www      3906:             untie(%hash);
                   3907:         }
                   3908: # ---------------------------------------------------------- There was an entry
                   3909:         if ($syval) {
                   3910:            unless ($syval=~/\_\d+$/) {
                   3911: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44      www      3912:                   &appenv('request.ambiguous' => $thisfn);
1.37      www      3913:                   return '';
                   3914:                }    
                   3915:                $syval.=$1;
                   3916: 	   }
                   3917:         } else {
                   3918: # ------------------------------------------------------- Was not in symb table
                   3919:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 3920:                             &GDBM_READER(),0640)) {
1.37      www      3921: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      3922:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      3923:               unless ($ids) { 
                   3924:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      3925:               }
                   3926:               unless ($ids) {
                   3927: # alias?
                   3928: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      3929:               }
1.37      www      3930:               if ($ids) {
                   3931: # ------------------------------------------------------------------- Has ID(s)
                   3932:                  my @possibilities=split(/\,/,$ids);
1.39      www      3933:                  if ($#possibilities==0) {
                   3934: # ----------------------------------------------- There is only one possibility
1.37      www      3935: 		     my ($mapid,$resid)=split(/\./,$ids);
                   3936:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      3937:                  } elsif (!$donotrecurse) {
1.39      www      3938: # ------------------------------------------ There is more than one possibility
                   3939:                      my $realpossible=0;
1.191     harris41 3940:                      foreach (@possibilities) {
1.39      www      3941: 			 my $file=$bighash{'src_'.$_};
                   3942:                          if (&allowed('bre',$file)) {
                   3943:          		    my ($mapid,$resid)=split(/\./,$_);
                   3944:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   3945: 				$realpossible++;
                   3946:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   3947:                                        '___'.$resid;
                   3948:                             }
                   3949: 			 }
1.191     harris41 3950:                      }
1.39      www      3951: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      3952:                  } else {
                   3953:                      $syval='';
1.37      www      3954:                  }
                   3955: 	      }
                   3956:               untie(%bighash)
                   3957:            } 
1.31      www      3958:         }
1.62      www      3959:         if ($syval) {
1.210     www      3960:            return &symbclean($syval.'___'.$thisfn); 
1.62      www      3961:         }
1.31      www      3962:     }
1.44      www      3963:     &appenv('request.ambiguous' => $thisfn);
1.31      www      3964:     return '';
                   3965: }
                   3966: 
                   3967: # ---------------------------------------------------------- Return random seed
                   3968: 
1.32      www      3969: sub numval {
                   3970:     my $txt=shift;
                   3971:     $txt=~tr/A-J/0-9/;
                   3972:     $txt=~tr/a-j/0-9/;
                   3973:     $txt=~tr/K-T/0-9/;
                   3974:     $txt=~tr/k-t/0-9/;
                   3975:     $txt=~tr/U-Z/0-5/;
                   3976:     $txt=~tr/u-z/0-5/;
                   3977:     $txt=~s/\D//g;
                   3978:     return int($txt);
1.368     albertel 3979: }
                   3980: 
                   3981: sub latest_rnd_algorithm_id {
                   3982:     return '64bit';
1.366     albertel 3983: }
1.32      www      3984: 
1.31      www      3985: sub rndseed {
1.155     albertel 3986:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 3987: 
                   3988:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 3989:     if (!$symb) {
1.366     albertel 3990: 	unless ($symb=$wsymb) { return time; }
                   3991:     }
                   3992:     if (!$courseid) { $courseid=$wcourseid; }
                   3993:     if (!$domain) { $domain=$wdomain; }
                   3994:     if (!$username) { $username=$wusername }
                   3995:     my $which=$ENV{"course.$courseid.rndseed"};
                   3996:     my $CODE=$ENV{'scantron.CODE'};
                   3997:     if (defined($CODE)) {
                   3998: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   3999:     } elsif ($which eq '64bit') {
                   4000: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   4001:     }
                   4002:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   4003: }
                   4004: 
                   4005: sub rndseed_32bit {
                   4006:     my ($symb,$courseid,$domain,$username)=@_;
                   4007:     {
                   4008: 	use integer;
                   4009: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   4010: 	my $symbseed=numval($symb) << 22;
                   4011: 	my $namechck=unpack("%32C*",$username) << 17;
                   4012: 	my $nameseed=numval($username) << 12;
                   4013: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   4014: 	my $courseseed=unpack("%32C*",$courseid);
                   4015: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   4016: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4017: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4018: 	return $num;
                   4019:     }
                   4020: }
                   4021: 
                   4022: sub rndseed_64bit {
                   4023:     my ($symb,$courseid,$domain,$username)=@_;
                   4024:     {
                   4025: 	use integer;
                   4026: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   4027: 	my $symbseed=numval($symb) << 10;
                   4028: 	my $namechck=unpack("%32S*",$username);
                   4029: 	
                   4030: 	my $nameseed=numval($username) << 21;
                   4031: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   4032: 	my $courseseed=unpack("%32S*",$courseid);
                   4033: 	
                   4034: 	my $num1=$symbchck+$symbseed+$namechck;
                   4035: 	my $num2=$nameseed+$domainseed+$courseseed;
                   4036: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   4037: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   4038: 	return "$num1,$num2";
1.155     albertel 4039:     }
1.366     albertel 4040: }
                   4041: 
                   4042: sub rndseed_CODE_64bit {
                   4043:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 4044:     {
1.366     albertel 4045: 	use integer;
                   4046: 	my $symbchck=unpack("%32S*",$symb) << 16;
                   4047: 	my $symbseed=numval($symb);
                   4048: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
                   4049: 	my $courseseed=unpack("%32S*",$courseid);
                   4050: 	my $num1=$symbseed+$CODEseed;
                   4051: 	my $num2=$courseseed+$symbchck;
                   4052: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
                   4053: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   4054: 	return "$num1,$num2";
                   4055:     }
                   4056: }
                   4057: 
                   4058: sub setup_random_from_rndseed {
                   4059:     my ($rndseed)=@_;
                   4060:     if ($rndseed =~/,/) {
                   4061: 	my ($num1,$num2)=split(/,/,$rndseed);
                   4062: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   4063:     } else {
                   4064: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 4065:     }
1.36      albertel 4066: }
                   4067: 
1.76      www      4068: sub ireceipt {
                   4069:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
                   4070:     my $cuname=unpack("%32C*",$funame);
                   4071:     my $cudom=unpack("%32C*",$fudom);
                   4072:     my $cucourseid=unpack("%32C*",$fucourseid);
                   4073:     my $cusymb=unpack("%32C*",$fusymb);
1.77      www      4074:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76      www      4075:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
                   4076:            ($cunique%$cuname+
                   4077:             $cunique%$cudom+
                   4078:             $cusymb%$cuname+
                   4079:             $cusymb%$cudom+
                   4080:             $cucourseid%$cuname+
                   4081:             $cucourseid%$cudom);
                   4082: }
                   4083: 
                   4084: sub receipt {
1.260     ng       4085:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   4086:   return &ireceipt($name,$domain,$courseid,$symb);
1.76      www      4087: }
1.260     ng       4088: 
1.36      albertel 4089: # ------------------------------------------------------------ Serves up a file
                   4090: # returns either the contents of the file or a -1
                   4091: sub getfile {
1.269     www      4092:  my $file=shift;
                   4093:  if ($file=~/^\/*uploaded\//) { # user file
                   4094:     my $ua=new LWP::UserAgent;
                   4095:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
                   4096:     my $response=$ua->request($request);
                   4097:     if ($response->is_success()) {
                   4098:        return $response->content;
                   4099:     } else { 
                   4100:        return -1; 
                   4101:     }
                   4102:  } else { # normal file from res space
1.37      www      4103:   &repcopy($file);
1.36      albertel 4104:   if (! -e $file ) { return -1; };
                   4105:   my $fh=Apache::File->new($file);
                   4106:   my $a='';
                   4107:   while (<$fh>) { $a .=$_; }
1.269     www      4108:   return $a;
                   4109:  }
1.36      albertel 4110: }
                   4111: 
                   4112: sub filelocation {
                   4113:   my ($dir,$file) = @_;
                   4114:   my $location;
                   4115:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59      albertel 4116:   if ($file=~m:^/~:) { # is a contruction space reference
                   4117:     $location = $file;
                   4118:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270     www      4119:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
                   4120:     $location=$file;
1.36      albertel 4121:   } else {
1.59      albertel 4122:     $file=~s/^$perlvar{'lonDocRoot'}//;
                   4123:     $file=~s:^/*res::;
                   4124:     if ( !( $file =~ m:^/:) ) {
                   4125:       $location = $dir. '/'.$file;
                   4126:     } else {
                   4127:       $location = '/home/httpd/html/res'.$file;
                   4128:     }
1.36      albertel 4129:   }
                   4130:   $location=~s://+:/:g; # remove duplicate /
1.46      www      4131:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   4132:   return $location;
                   4133: }
1.36      albertel 4134: 
1.46      www      4135: sub hreflocation {
                   4136:     my ($dir,$file)=@_;
1.191     harris41 4137:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46      www      4138:        my $finalpath=filelocation($dir,$file);
                   4139:        $finalpath=~s/^\/home\/httpd\/html//;
1.225     albertel 4140:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46      www      4141:        return $finalpath;
                   4142:     } else {
                   4143:        return $file;
                   4144:     }
1.31      www      4145: }
                   4146: 
                   4147: # ------------------------------------------------------------- Declutters URLs
                   4148: 
                   4149: sub declutter {
                   4150:     my $thisfn=shift;
                   4151:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
                   4152:     $thisfn=~s/^\///;
                   4153:     $thisfn=~s/^res\///;
1.235     www      4154:     $thisfn=~s/\?.+$//;
1.268     www      4155:     return $thisfn;
                   4156: }
                   4157: 
                   4158: # ------------------------------------------------------------- Clutter up URLs
                   4159: 
                   4160: sub clutter {
                   4161:     my $thisfn='/'.&declutter(shift);
1.270     www      4162:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
                   4163:        $thisfn='/res'.$thisfn; 
                   4164:     }
1.31      www      4165:     return $thisfn;
1.12      www      4166: }
                   4167: 
                   4168: # -------------------------------------------------------- Escape Special Chars
                   4169: 
                   4170: sub escape {
                   4171:     my $str=shift;
                   4172:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   4173:     return $str;
                   4174: }
                   4175: 
                   4176: # ----------------------------------------------------- Un-Escape Special Chars
                   4177: 
                   4178: sub unescape {
                   4179:     my $str=shift;
                   4180:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   4181:     return $str;
                   4182: }
1.11      www      4183: 
1.1       albertel 4184: # ================================================================ Main Program
                   4185: 
1.184     www      4186: sub goodbye {
1.204     albertel 4187:    &logthis("Starting Shut down");
1.184     www      4188:    &flushcourselogs();
                   4189:    &logthis("Shutting down");
1.362     albertel 4190:    return DONE;
1.184     www      4191: }
                   4192: 
1.179     www      4193: BEGIN {
1.228     harris41 4194: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      4195:     unless ($readit) {
1.217     harris41 4196: {
                   4197:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
                   4198: 
                   4199:     while (my $configline=<$config>) {
                   4200:         if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 4201: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      4202:            chomp($varvalue);
1.1       albertel 4203:            $perlvar{$varname}=$varvalue;
                   4204:         }
                   4205:     }
                   4206: }
1.227     harris41 4207: {
                   4208:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
                   4209: 
                   4210:     while (my $configline=<$config>) {
                   4211:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   4212: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   4213:            chomp($varvalue);
                   4214:            $perlvar{$varname}=$varvalue;
                   4215:         }
                   4216:     }
                   4217: }
1.1       albertel 4218: 
1.327     albertel 4219: # ------------------------------------------------------------ Read domain file
                   4220: {
                   4221:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
                   4222:                             '/domain.tab');
                   4223:     %domaindescription = ();
                   4224:     %domain_auth_def = ();
                   4225:     %domain_auth_arg_def = ();
                   4226:     if ($fh) {
                   4227:        while (<$fh>) {
1.390     matthew  4228:            next if (/^(\#|\s*$)/);
                   4229: #           next if /^\#/;
1.327     albertel 4230:            chomp;
1.403     www      4231:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   4232: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   4233: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 4234:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      4235: 	   $domaindescription{$domain}=$domain_description;
                   4236: 	   $domain_lang_def{$domain}=$def_lang;
                   4237: 	   $domain_city{$domain}=$city;
                   4238: 	   $domain_longi{$domain}=$longi;
                   4239: 	   $domain_lati{$domain}=$lati;
                   4240: 
1.327     albertel 4241: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
                   4242: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
                   4243:        }
                   4244:     }
                   4245: }
                   4246: 
                   4247: 
1.1       albertel 4248: # ------------------------------------------------------------- Read hosts file
                   4249: {
                   4250:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
                   4251: 
                   4252:     while (my $configline=<$config>) {
1.303     matthew  4253:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      4254:        chomp($configline);
1.245     www      4255:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252     albertel 4256:        if ($id && $domain && $role && $name && $ip) {
                   4257: 	 $hostname{$id}=$name;
                   4258: 	 $hostdom{$id}=$domain;
                   4259: 	 $hostip{$id}=$ip;
1.300     albertel 4260: 	 $iphost{$ip}=$id;
1.252     albertel 4261: 	 if ($role eq 'library') { $libserv{$id}=$name; }
                   4262:        } else {
                   4263: 	 if ($configline) {
                   4264: 	   &logthis("Skipping hosts.tab line -$configline-");
                   4265: 	 }
1.245     www      4266:        }
1.1       albertel 4267:     }
                   4268: }
                   4269: 
                   4270: # ------------------------------------------------------ Read spare server file
                   4271: {
                   4272:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
                   4273: 
                   4274:     while (my $configline=<$config>) {
                   4275:        chomp($configline);
1.284     matthew  4276:        if ($configline) {
1.1       albertel 4277:           $spareid{$configline}=1;
                   4278:        }
                   4279:     }
                   4280: }
1.11      www      4281: # ------------------------------------------------------------ Read permissions
                   4282: {
                   4283:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
                   4284: 
                   4285:     while (my $configline=<$config>) {
                   4286:        chomp($configline);
1.160     www      4287:       if ($configline) {
1.11      www      4288:        my ($role,$perm)=split(/ /,$configline);
                   4289:        if ($perm ne '') { $pr{$role}=$perm; }
1.160     www      4290:       }
1.11      www      4291:     }
                   4292: }
                   4293: 
                   4294: # -------------------------------------------- Read plain texts for permissions
                   4295: {
                   4296:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
                   4297: 
                   4298:     while (my $configline=<$config>) {
                   4299:        chomp($configline);
1.160     www      4300:       if ($configline) {
1.11      www      4301:        my ($short,$plain)=split(/:/,$configline);
                   4302:        if ($plain ne '') { $prp{$short}=$plain; }
1.160     www      4303:       }
1.135     www      4304:     }
                   4305: }
                   4306: 
                   4307: # ---------------------------------------------------------- Read package table
                   4308: {
                   4309:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
                   4310: 
                   4311:     while (my $configline=<$config>) {
                   4312:        chomp($configline);
                   4313:        my ($short,$plain)=split(/:/,$configline);
1.143     www      4314:        my ($pack,$name)=split(/\&/,$short);
                   4315:        if ($plain ne '') {
                   4316:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   4317:           $packagetab{$short}=$plain; 
1.25      www      4318:        }
1.11      www      4319:     }
1.329     matthew  4320: }
                   4321: 
                   4322: # ------------- set up temporary directory
                   4323: {
                   4324:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   4325: 
1.11      www      4326: }
                   4327: 
1.71      www      4328: %metacache=();
1.185     www      4329: 
1.281     www      4330: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      4331: $dumpcount=0;
1.22      www      4332: 
1.163     harris41 4333: &logtouch();
1.12      www      4334: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      4335: $readit=1;
                   4336: }
1.1       albertel 4337: }
1.179     www      4338: 
1.1       albertel 4339: 1;
1.191     harris41 4340: __END__
                   4341: 
1.243     albertel 4342: =pod
                   4343: 
1.191     harris41 4344: =head1 NAME
                   4345: 
1.243     albertel 4346: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 4347: 
                   4348: =head1 SYNOPSIS
                   4349: 
1.243     albertel 4350: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 4351: 
                   4352:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   4353: 
1.243     albertel 4354: Common parameters:
                   4355: 
                   4356: =over 4
                   4357: 
                   4358: =item *
                   4359: 
                   4360: $uname : an internal username (if $cname expecting a course Id specifically)
                   4361: 
                   4362: =item *
                   4363: 
                   4364: $udom : a domain (if $cdom expecting a course's domain specifically)
                   4365: 
                   4366: =item *
                   4367: 
                   4368: $symb : a resource instance identifier
                   4369: 
                   4370: =item *
                   4371: 
                   4372: $namespace : the name of a .db file that contains the data needed or
                   4373: being set.
                   4374: 
                   4375: =back
                   4376: 
1.394     bowersj2 4377: =head1 OVERVIEW
1.191     harris41 4378: 
1.394     bowersj2 4379: lonnet provides subroutines which interact with the
                   4380: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   4381: about classes, users, and resources.
1.243     albertel 4382: 
                   4383: For many of these objects you can also use this to store data about
                   4384: them or modify them in various ways.
1.191     harris41 4385: 
1.394     bowersj2 4386: =head2 Symbs
1.191     harris41 4387: 
1.394     bowersj2 4388: To identify a specific instance of a resource, LON-CAPA uses symbols
                   4389: or "symbs"X<symb>. These identifiers are built from the URL of the
                   4390: map, the resource number of the resource in the map, and the URL of
                   4391: the resource itself. The latter is somewhat redundant, but might help
                   4392: if maps change.
                   4393: 
                   4394: An example is
                   4395: 
                   4396:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   4397: 
                   4398: The respective map entry is
                   4399: 
                   4400:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   4401:   title="Problem 2">
                   4402:  </resource>
                   4403: 
                   4404: Symbs are used by the random number generator, as well as to store and
                   4405: restore data specific to a certain instance of for example a problem.
                   4406: 
                   4407: =head2 Storing And Retrieving Data
                   4408: 
                   4409: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   4410: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   4411: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   4412: is is the non-critical message twin of cstore. These functions are for
                   4413: handlers to store a perl hash to a user's permanent data space in an
                   4414: easy manner, and to retrieve it again on another call. It is expected
                   4415: that a handler would use this once at the beginning to retrieve data,
                   4416: and then again once at the end to send only the new data back.
                   4417: 
                   4418: The data is stored in the user's data directory on the user's
                   4419: homeserver under the ID of the course.
                   4420: 
                   4421: The hash that is returned by restore will have all of the previous
                   4422: value for all of the elements of the hash.
                   4423: 
                   4424: Example:
                   4425: 
                   4426:  #creating a hash
                   4427:  my %hash;
                   4428:  $hash{'foo'}='bar';
                   4429: 
                   4430:  #storing it
                   4431:  &Apache::lonnet::cstore(\%hash);
                   4432: 
                   4433:  #changing a value
                   4434:  $hash{'foo'}='notbar';
                   4435: 
                   4436:  #adding a new value
                   4437:  $hash{'bar'}='foo';
                   4438:  &Apache::lonnet::cstore(\%hash);
                   4439: 
                   4440:  #retrieving the hash
                   4441:  my %history=&Apache::lonnet::restore();
                   4442: 
                   4443:  #print the hash
                   4444:  foreach my $key (sort(keys(%history))) {
                   4445:    print("\%history{$key} = $history{$key}");
                   4446:  }
                   4447: 
                   4448: Will print out:
1.191     harris41 4449: 
1.394     bowersj2 4450:  %history{1:foo} = bar
                   4451:  %history{1:keys} = foo:timestamp
                   4452:  %history{1:timestamp} = 990455579
                   4453:  %history{2:bar} = foo
                   4454:  %history{2:foo} = notbar
                   4455:  %history{2:keys} = foo:bar:timestamp
                   4456:  %history{2:timestamp} = 990455580
                   4457:  %history{bar} = foo
                   4458:  %history{foo} = notbar
                   4459:  %history{timestamp} = 990455580
                   4460:  %history{version} = 2
                   4461: 
                   4462: Note that the special hash entries C<keys>, C<version> and
                   4463: C<timestamp> were added to the hash. C<version> will be equal to the
                   4464: total number of versions of the data that have been stored. The
                   4465: C<timestamp> attribute will be the UNIX time the hash was
                   4466: stored. C<keys> is available in every historical section to list which
                   4467: keys were added or changed at a specific historical revision of a
                   4468: hash.
                   4469: 
                   4470: B<Warning>: do not store the hash that restore returns directly. This
                   4471: will cause a mess since it will restore the historical keys as if the
                   4472: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 4473: 
1.394     bowersj2 4474: Calling convention:
1.191     harris41 4475: 
1.394     bowersj2 4476:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   4477:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 4478: 
1.394     bowersj2 4479: For more detailed information, see lonnet specific documentation.
1.191     harris41 4480: 
1.394     bowersj2 4481: =head1 RETURN MESSAGES
1.191     harris41 4482: 
1.394     bowersj2 4483: =over 4
1.191     harris41 4484: 
1.394     bowersj2 4485: =item * B<con_lost>: unable to contact remote host
1.191     harris41 4486: 
1.394     bowersj2 4487: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   4488: when the connection is brought back up
1.191     harris41 4489: 
1.394     bowersj2 4490: =item * B<con_failed>: unable to contact remote host and unable to save message
                   4491: for later delivery
1.191     harris41 4492: 
1.394     bowersj2 4493: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 4494: 
1.394     bowersj2 4495: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 4496: that was requested
1.191     harris41 4497: 
1.243     albertel 4498: =back
1.191     harris41 4499: 
1.243     albertel 4500: =head1 PUBLIC SUBROUTINES
1.191     harris41 4501: 
1.243     albertel 4502: =head2 Session Environment Functions
1.191     harris41 4503: 
1.243     albertel 4504: =over 4
1.191     harris41 4505: 
1.394     bowersj2 4506: =item * 
                   4507: X<appenv()>
                   4508: B<appenv(%hash)>: the value of %hash is written to
                   4509: the user envirnoment file, and will be restored for each access this
                   4510: user makes during this session, also modifies the %ENV for the current
                   4511: process
1.191     harris41 4512: 
                   4513: =item *
1.394     bowersj2 4514: X<delenv()>
                   4515: B<delenv($regexp)>: removes all items from the session
                   4516: environment file that matches the regular expression in $regexp. The
                   4517: values are also delted from the current processes %ENV.
1.191     harris41 4518: 
1.243     albertel 4519: =back
                   4520: 
                   4521: =head2 User Information
1.191     harris41 4522: 
1.243     albertel 4523: =over 4
1.191     harris41 4524: 
                   4525: =item *
1.394     bowersj2 4526: X<queryauthenticate()>
                   4527: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 4528: authentication scheme
                   4529: 
                   4530: =item *
1.394     bowersj2 4531: X<authenticate()>
                   4532: B<authenticate($uname,$upass,$udom)>: try to
                   4533: authenticate user from domain's lib servers (first use the current
                   4534: one). C<$upass> should be the users password.
1.191     harris41 4535: 
                   4536: =item *
1.394     bowersj2 4537: X<homeserver()>
                   4538: B<homeserver($uname,$udom)>: find the server which has
                   4539: the user's directory and files (there must be only one), this caches
                   4540: the answer, and also caches if there is a borken connection.
1.191     harris41 4541: 
                   4542: =item *
1.394     bowersj2 4543: X<idget()>
                   4544: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   4545: (IDs are a unique resource in a domain, there must be only 1 ID per
                   4546: username, and only 1 username per ID in a specific domain) (returns
                   4547: hash: id=>name,id=>name)
1.191     harris41 4548: 
                   4549: =item *
1.394     bowersj2 4550: X<idrget()>
                   4551: B<idrget($udom,@unames)>: find the IDs behind a list of
                   4552: usernames (returns hash: name=>id,name=>id)
1.191     harris41 4553: 
                   4554: =item *
1.394     bowersj2 4555: X<idput()>
                   4556: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 4557: 
                   4558: =item *
1.394     bowersj2 4559: X<rolesinit()>
                   4560: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 4561: 
                   4562: =item *
1.394     bowersj2 4563: X<usection()>
                   4564: B<usection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 4565: course $cname, return section name/number or '' for "not in course"
                   4566: and '-1' for "no section"
                   4567: 
                   4568: =item *
1.394     bowersj2 4569: X<userenvironment()>
                   4570: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 4571: passed in @what from the requested user's environment, returns a hash
                   4572: 
                   4573: =back
                   4574: 
                   4575: =head2 User Roles
                   4576: 
                   4577: =over 4
                   4578: 
                   4579: =item *
                   4580: 
                   4581: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   4582: actions
                   4583:  F: full access
                   4584:  U,I,K: authentication modes (cxx only)
                   4585:  '': forbidden
                   4586:  1: user needs to choose course
                   4587:  2: browse allowed
                   4588: 
                   4589: =item *
                   4590: 
                   4591: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   4592: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   4593: and course level
                   4594: 
                   4595: =item *
                   4596: 
                   4597: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   4598: explanation of a user role term
                   4599: 
                   4600: =back
                   4601: 
                   4602: =head2 User Modification
                   4603: 
                   4604: =over 4
                   4605: 
                   4606: =item *
                   4607: 
                   4608: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   4609: user for the level given by URL.  Optional start and end dates (leave empty
                   4610: string or zero for "no date")
1.191     harris41 4611: 
                   4612: =item *
                   4613: 
1.243     albertel 4614: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   4615: change a users, password, possible return values are: ok,
                   4616: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   4617: refused
1.191     harris41 4618: 
                   4619: =item *
                   4620: 
1.243     albertel 4621: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 4622: 
                   4623: =item *
                   4624: 
1.243     albertel 4625: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   4626: modify user
1.191     harris41 4627: 
                   4628: =item *
                   4629: 
1.286     matthew  4630: modifystudent
                   4631: 
                   4632: modify a students enrollment and identification information.
                   4633: The course id is resolved based on the current users environment.  
                   4634: This means the envoking user must be a course coordinator or otherwise
                   4635: associated with a course.
                   4636: 
1.297     matthew  4637: This call is essentially a wrapper for lonnet::modifyuser and
                   4638: lonnet::modify_student_enrollment
1.286     matthew  4639: 
                   4640: Inputs: 
                   4641: 
                   4642: =over 4
                   4643: 
                   4644: =item B<$udom> Students loncapa domain
                   4645: 
                   4646: =item B<$uname> Students loncapa login name
                   4647: 
                   4648: =item B<$uid> Students id/student number
                   4649: 
                   4650: =item B<$umode> Students authentication mode
                   4651: 
                   4652: =item B<$upass> Students password
                   4653: 
                   4654: =item B<$first> Students first name
                   4655: 
                   4656: =item B<$middle> Students middle name
                   4657: 
                   4658: =item B<$last> Students last name
                   4659: 
                   4660: =item B<$gene> Students generation
                   4661: 
                   4662: =item B<$usec> Students section in course
                   4663: 
                   4664: =item B<$end> Unix time of the roles expiration
                   4665: 
                   4666: =item B<$start> Unix time of the roles start date
                   4667: 
                   4668: =item B<$forceid> If defined, allow $uid to be changed
                   4669: 
                   4670: =item B<$desiredhome> server to use as home server for student
                   4671: 
                   4672: =back
1.297     matthew  4673: 
                   4674: =item *
                   4675: 
                   4676: modify_student_enrollment
                   4677: 
                   4678: Change a students enrollment status in a class.  The environment variable
                   4679: 'role.request.course' must be defined for this function to proceed.
                   4680: 
                   4681: Inputs:
                   4682: 
                   4683: =over 4
                   4684: 
                   4685: =item $udom, students domain
                   4686: 
                   4687: =item $uname, students name
                   4688: 
                   4689: =item $uid, students user id
                   4690: 
                   4691: =item $first, students first name
                   4692: 
                   4693: =item $middle
                   4694: 
                   4695: =item $last
                   4696: 
                   4697: =item $gene
                   4698: 
                   4699: =item $usec
                   4700: 
                   4701: =item $end
                   4702: 
                   4703: =item $start
                   4704: 
                   4705: =back
                   4706: 
1.191     harris41 4707: 
                   4708: =item *
                   4709: 
1.243     albertel 4710: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   4711: custom role; give a custom role to a user for the level given by URL.  Specify
                   4712: name and domain of role author, and role name
1.191     harris41 4713: 
                   4714: =item *
                   4715: 
1.243     albertel 4716: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 4717: 
                   4718: =item *
                   4719: 
1.243     albertel 4720: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   4721: 
                   4722: =back
                   4723: 
                   4724: =head2 Course Infomation
                   4725: 
                   4726: =over 4
1.191     harris41 4727: 
                   4728: =item *
                   4729: 
1.243     albertel 4730: coursedescription($courseid) : course description
1.191     harris41 4731: 
                   4732: =item *
                   4733: 
1.243     albertel 4734: courseresdata($coursenum,$coursedomain,@which) : request for current
                   4735: parameter setting for a specific course, @what should be a list of
                   4736: parameters to ask about. This routine caches answers for 5 minutes.
                   4737: 
                   4738: =back
                   4739: 
                   4740: =head2 Course Modification
                   4741: 
                   4742: =over 4
1.191     harris41 4743: 
                   4744: =item *
                   4745: 
1.243     albertel 4746: writecoursepref($courseid,%prefs) : write preferences (environment
                   4747: database) for a course
1.191     harris41 4748: 
                   4749: =item *
                   4750: 
1.243     albertel 4751: createcourse($udom,$description,$url) : make/modify course
                   4752: 
                   4753: =back
                   4754: 
                   4755: =head2 Resource Subroutines
                   4756: 
                   4757: =over 4
1.191     harris41 4758: 
                   4759: =item *
                   4760: 
1.243     albertel 4761: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 4762: 
                   4763: =item *
                   4764: 
1.243     albertel 4765: repcopy($filename) : subscribes to the requested file, and attempts to
                   4766: replicate from the owning library server, Might return
                   4767: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
                   4768: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
                   4769: resource. Expects the local filesystem pathname
                   4770: (/home/httpd/html/res/....)
                   4771: 
                   4772: =back
                   4773: 
                   4774: =head2 Resource Information
                   4775: 
                   4776: =over 4
1.191     harris41 4777: 
                   4778: =item *
                   4779: 
1.243     albertel 4780: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   4781: a vairety of different possible values, $varname should be a request
                   4782: string, and the other parameters can be used to specify who and what
                   4783: one is asking about.
                   4784: 
                   4785: Possible values for $varname are environment.lastname (or other item
                   4786: from the envirnment hash), user.name (or someother aspect about the
                   4787: user), resource.0.maxtries (or some other part and parameter of a
                   4788: resource)
1.204     albertel 4789: 
                   4790: =item *
                   4791: 
1.243     albertel 4792: directcondval($number) : get current value of a condition; reads from a state
                   4793: string
1.204     albertel 4794: 
                   4795: =item *
                   4796: 
1.243     albertel 4797: condval($condidx) : value of condition index based on state
1.204     albertel 4798: 
                   4799: =item *
                   4800: 
1.243     albertel 4801: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   4802: resource's metadata, $what should be either a specific key, or either
                   4803: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   4804: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   4805: 
                   4806: this function automatically caches all requests
1.191     harris41 4807: 
                   4808: =item *
                   4809: 
1.243     albertel 4810: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   4811: network of library servers; returns file handle of where SQL and regex results
                   4812: will be stored for query
1.191     harris41 4813: 
                   4814: =item *
                   4815: 
1.243     albertel 4816: symbread($filename) : return symbolic list entry (filename argument optional);
                   4817: returns the data handle
1.191     harris41 4818: 
                   4819: =item *
                   4820: 
1.243     albertel 4821: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
                   4822: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
                   4823: failure, user must be in a course, as it assumes the existance of the
                   4824: course initi hash, and uses $ENV('request.course.id'}
                   4825: 
1.191     harris41 4826: 
                   4827: =item *
                   4828: 
1.243     albertel 4829: symbclean($symb) : removes versions numbers from a symb, returns the
                   4830: cleaned symb
1.191     harris41 4831: 
                   4832: =item *
                   4833: 
1.243     albertel 4834: is_on_map($uri) : checks if the $uri is somewhere on the current
                   4835: course map, user must be in a course for it to work.
1.191     harris41 4836: 
                   4837: =item *
                   4838: 
1.243     albertel 4839: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 4840: 
                   4841: =item *
                   4842: 
1.243     albertel 4843: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   4844: a random seed, all arguments are optional, if they aren't sent it uses the
                   4845: environment to derive them. Note: if symb isn't sent and it can't get one
                   4846: from &symbread it will use the current time as its return value
1.191     harris41 4847: 
                   4848: =item *
                   4849: 
1.243     albertel 4850: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   4851: unfakeable, receipt
1.191     harris41 4852: 
                   4853: =item *
                   4854: 
1.243     albertel 4855: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 4856: 
                   4857: =item *
                   4858: 
1.243     albertel 4859: countacc($url) : count the number of accesses to a given URL
1.191     harris41 4860: 
                   4861: =item *
                   4862: 
1.243     albertel 4863: 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 4864: 
                   4865: =item *
                   4866: 
1.243     albertel 4867: 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 4868: 
                   4869: =item *
                   4870: 
1.243     albertel 4871: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 4872: 
                   4873: =item *
                   4874: 
1.243     albertel 4875: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   4876: forcing spreadsheet to reevaluate the resource scores next time.
                   4877: 
                   4878: =back
                   4879: 
                   4880: =head2 Storing/Retreiving Data
                   4881: 
                   4882: =over 4
1.191     harris41 4883: 
                   4884: =item *
                   4885: 
1.243     albertel 4886: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   4887: for this url; hashref needs to be given and should be a \%hashname; the
                   4888: remaining args aren't required and if they aren't passed or are '' they will
                   4889: be derived from the ENV
1.191     harris41 4890: 
                   4891: =item *
                   4892: 
1.243     albertel 4893: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   4894: uses critical subroutine
1.191     harris41 4895: 
                   4896: =item *
                   4897: 
1.243     albertel 4898: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   4899: all args are optional
1.191     harris41 4900: 
                   4901: =item *
                   4902: 
1.243     albertel 4903: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   4904: works very similar to store/cstore, but all data is stored in a
                   4905: temporary location and can be reset using tmpreset, $storehash should
                   4906: be a hash reference, returns nothing on success
1.191     harris41 4907: 
                   4908: =item *
                   4909: 
1.243     albertel 4910: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   4911: similar to restore, but all data is stored in a temporary location and
                   4912: can be reset using tmpreset. Returns a hash of values on success,
                   4913: error string otherwise.
1.191     harris41 4914: 
                   4915: =item *
                   4916: 
1.243     albertel 4917: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   4918: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 4919: 
                   4920: =item *
                   4921: 
1.243     albertel 4922: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   4923: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 4924: 
                   4925: =item *
                   4926: 
1.243     albertel 4927: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   4928: namesp ($udom and $uname are optional)
1.191     harris41 4929: 
                   4930: =item *
                   4931: 
1.243     albertel 4932: dump($namespace,$udom,$uname,$regexp) : 
                   4933: dumps the complete (or key matching regexp) namespace into a hash
                   4934: ($udom, $uname and $regexp are optional)
1.191     harris41 4935: 
                   4936: =item *
                   4937: 
1.243     albertel 4938: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   4939: ($udom and $uname are optional)
1.191     harris41 4940: 
                   4941: =item *
                   4942: 
1.243     albertel 4943: cput($namespace,$storehash,$udom,$uname) : critical put
                   4944: ($udom and $uname are optional)
1.191     harris41 4945: 
                   4946: =item *
                   4947: 
1.243     albertel 4948: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   4949: reference filled in from namesp (encrypts the return communication)
                   4950: ($udom and $uname are optional)
1.191     harris41 4951: 
                   4952: =item *
                   4953: 
1.243     albertel 4954: log($udom,$name,$home,$message) : write to permanent log for user; use
                   4955: critical subroutine
                   4956: 
                   4957: =back
                   4958: 
                   4959: =head2 Network Status Functions
                   4960: 
                   4961: =over 4
1.191     harris41 4962: 
                   4963: =item *
                   4964: 
                   4965: dirlist($uri) : return directory list based on URI
                   4966: 
                   4967: =item *
                   4968: 
1.243     albertel 4969: spareserver() : find server with least workload from spare.tab
                   4970: 
                   4971: =back
                   4972: 
                   4973: =head2 Apache Request
                   4974: 
                   4975: =over 4
1.191     harris41 4976: 
                   4977: =item *
                   4978: 
1.243     albertel 4979: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   4980: localhost, posts hash
                   4981: 
                   4982: =back
                   4983: 
                   4984: =head2 Data to String to Data
                   4985: 
                   4986: =over 4
1.191     harris41 4987: 
                   4988: =item *
                   4989: 
1.243     albertel 4990: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   4991: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 4992: 
                   4993: =item *
                   4994: 
1.243     albertel 4995: hashref2str($hashref) : convert a hashref into a string complete with
                   4996: escaping and '=' and '&' separators, supports elements that are
                   4997: arrayrefs and hashrefs
1.191     harris41 4998: 
                   4999: =item *
                   5000: 
1.243     albertel 5001: arrayref2str($arrayref) : convert an arrayref into a string complete
                   5002: with escaping and '&' separators, supports elements that are arrayrefs
                   5003: and hashrefs
1.191     harris41 5004: 
                   5005: =item *
                   5006: 
1.243     albertel 5007: str2hash($string) : convert string to hash using unescaping and
                   5008: splitting on '=' and '&', supports elements that are arrayrefs and
                   5009: hashrefs
1.191     harris41 5010: 
                   5011: =item *
                   5012: 
1.243     albertel 5013: str2array($string) : convert string to hash using unescaping and
                   5014: splitting on '&', supports elements that are arrayrefs and hashrefs
                   5015: 
                   5016: =back
                   5017: 
                   5018: =head2 Logging Routines
                   5019: 
                   5020: =over 4
                   5021: 
                   5022: These routines allow one to make log messages in the lonnet.log and
                   5023: lonnet.perm logfiles.
1.191     harris41 5024: 
                   5025: =item *
                   5026: 
1.243     albertel 5027: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 5028: 
                   5029: =item *
                   5030: 
1.243     albertel 5031: logthis() : append message to the normal lonnet.log file, it gets
                   5032: preiodically rolled over and deleted.
1.191     harris41 5033: 
                   5034: =item *
                   5035: 
1.243     albertel 5036: logperm() : append a permanent message to lonnet.perm.log, this log
                   5037: file never gets deleted by any automated portion of the system, only
                   5038: messages of critical importance should go in here.
                   5039: 
                   5040: =back
                   5041: 
                   5042: =head2 General File Helper Routines
                   5043: 
                   5044: =over 4
1.191     harris41 5045: 
                   5046: =item *
                   5047: 
1.243     albertel 5048: getfile($file) : returns the entire contents of a file or -1; it
                   5049: properly subscribes to and replicates the file if neccessary.
1.191     harris41 5050: 
                   5051: =item *
                   5052: 
1.243     albertel 5053: filelocation($dir,$file) : returns file system location of a file
                   5054: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   5055: directory that relative $file lookups are to looked in ($dir of /a/dir
                   5056: and a file of ../bob will become /a/bob)
1.191     harris41 5057: 
                   5058: =item *
                   5059: 
                   5060: hreflocation($dir,$file) : returns file system location or a URL; same as
                   5061: filelocation except for hrefs
                   5062: 
                   5063: =item *
                   5064: 
                   5065: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   5066: 
1.243     albertel 5067: =back
                   5068: 
                   5069: =head2 HTTP Helper Routines
                   5070: 
                   5071: =over 4
                   5072: 
1.191     harris41 5073: =item *
                   5074: 
                   5075: escape() : unpack non-word characters into CGI-compatible hex codes
                   5076: 
                   5077: =item *
                   5078: 
                   5079: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   5080: 
1.243     albertel 5081: =back
                   5082: 
                   5083: =head1 PRIVATE SUBROUTINES
                   5084: 
                   5085: =head2 Underlying communication routines (Shouldn't call)
                   5086: 
                   5087: =over 4
                   5088: 
                   5089: =item *
                   5090: 
                   5091: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   5092: 
                   5093: =item *
                   5094: 
                   5095: reply() : uses subreply to send a message to remote machine, logs all failures
                   5096: 
                   5097: =item *
                   5098: 
                   5099: critical() : passes a critical message to another server; if cannot
                   5100: get through then place message in connection buffer directory and
                   5101: returns con_delayed, if incapable of saving message, returns
                   5102: con_failed
                   5103: 
                   5104: =item *
                   5105: 
                   5106: reconlonc() : tries to reconnect lonc client processes.
                   5107: 
                   5108: =back
                   5109: 
                   5110: =head2 Resource Access Logging
                   5111: 
                   5112: =over 4
                   5113: 
                   5114: =item *
                   5115: 
                   5116: flushcourselogs() : flush (save) buffer logs and access logs
                   5117: 
                   5118: =item *
                   5119: 
                   5120: courselog($what) : save message for course in hash
                   5121: 
                   5122: =item *
                   5123: 
                   5124: courseacclog($what) : save message for course using &courselog().  Perform
                   5125: special processing for specific resource types (problems, exams, quizzes, etc).
                   5126: 
1.191     harris41 5127: =item *
                   5128: 
                   5129: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   5130: as a PerlChildExitHandler
1.243     albertel 5131: 
                   5132: =back
                   5133: 
                   5134: =head2 Other
                   5135: 
                   5136: =over 4
                   5137: 
                   5138: =item *
                   5139: 
                   5140: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 5141: 
                   5142: =back
                   5143: 
                   5144: =cut

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