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

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

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