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

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

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