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

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

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