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

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

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