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

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

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