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

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

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