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

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

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