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

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

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