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

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

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