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

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

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