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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.615   ! albertel    4: # $Id: lonnet.pm,v 1.614 2005/03/21 18:53:51 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.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.607     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
1.609     banghart 1000: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 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.607     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.607     raeburn  1009:            return 'unavailable';
1.8       www      1010:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1011: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1012: 	   return 'not_found';
1.64      www      1013:     } elsif ($remoteurl =~ /^rejected by/) {
                   1014: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1015:            return 'forbidden';
1.20      www      1016:     } elsif ($remoteurl eq 'directory') {
1.607     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.607     raeburn  1028: 	       return '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.607     raeburn  1045:                return '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.607     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.531     albertel 1202: sub clean_filename {
                   1203:     my ($fname)=@_;
1.315     www      1204: # Replace Windows backslashes by forward slashes
1.257     www      1205:     $fname=~s/\\/\//g;
1.315     www      1206: # Get rid of everything but the actual filename
1.257     www      1207:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1208: # Replace spaces by underscores
                   1209:     $fname=~s/\s+/\_/g;
                   1210: # Replace all other weird characters by nothing
1.317     www      1211:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1212: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1213: # numbers
                   1214:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1215:     return $fname;
                   1216: }
                   1217: 
1.608     albertel 1218: # --------------- Take an uploaded file and put it into the userfiles directory
                   1219: # input: name of form element, coursedoc=1 means this is for the course
                   1220: # output: url of file in userspace
                   1221: 
                   1222: 
1.531     albertel 1223: sub userfileupload {
                   1224:     my ($formname,$coursedoc,$subdir)=@_;
                   1225:     if (!defined($subdir)) { $subdir='unknown'; }
                   1226:     my $fname=$ENV{'form.'.$formname.'.filename'};
                   1227:     $fname=&clean_filename($fname);
1.315     www      1228: # See if there is anything left
1.257     www      1229:     unless ($fname) { return 'error: no uploaded file'; }
1.477     raeburn  1230:     chop($ENV{'form.'.$formname});
1.523     raeburn  1231:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1232:         my $now = time;
                   1233:         my $filepath = 'tmp/helprequests/'.$now;
                   1234:         my @parts=split(/\//,$filepath);
                   1235:         my $fullpath = $perlvar{'lonDaemons'};
                   1236:         for (my $i=0;$i<@parts;$i++) {
                   1237:             $fullpath .= '/'.$parts[$i];
                   1238:             if ((-e $fullpath)!=1) {
                   1239:                 mkdir($fullpath,0777);
                   1240:             }
                   1241:         }
                   1242:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1243:         print $fh $ENV{'form.'.$formname};
                   1244:         close($fh);
                   1245:         return $fullpath.'/'.$fname; 
                   1246:     }
1.258     www      1247: # Create the directory if not present
1.259     www      1248:     my $docuname='';
                   1249:     my $docudom='';
                   1250:     my $docuhome='';
1.493     albertel 1251:     $fname="$subdir/$fname";
1.259     www      1252:     if ($coursedoc) {
                   1253: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
                   1254: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
                   1255: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.481     raeburn  1256:         if ($ENV{'form.folder'} =~ m/^default/) {
1.485     raeburn  1257:             return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1.481     raeburn  1258:         } else {
                   1259:             $fname=$ENV{'form.folder'}.'/'.$fname;
1.485     raeburn  1260:             return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname);
1.481     raeburn  1261:         }
1.259     www      1262:     } else {
                   1263:         $docuname=$ENV{'user.name'};
                   1264:         $docudom=$ENV{'user.domain'};
                   1265:         $docuhome=$ENV{'user.home'};
1.485     raeburn  1266:         return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1.259     www      1267:     }
1.271     www      1268: }
                   1269: 
                   1270: sub finishuserfileupload {
1.477     raeburn  1271:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
                   1272:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1273:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1274:     my ($fnamepath,$file);
                   1275:     $file=$fname;
                   1276:     if ($fname=~m|/|) {
                   1277:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1278: 	$path.=$fnamepath.'/';
                   1279:     }
1.259     www      1280:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1281:     my $count;
                   1282:     for ($count=4;$count<=$#parts;$count++) {
                   1283:         $filepath.="/$parts[$count]";
                   1284:         if ((-e $filepath)!=1) {
                   1285: 	    mkdir($filepath,0777);
                   1286:         }
                   1287:     }
                   1288: # Save the file
                   1289:     {
1.570     albertel 1290: 	open(FH,'>'.$filepath.'/'.$file);
                   1291: 	print FH $ENV{'form.'.$formname};
                   1292: 	close(FH);
1.258     www      1293:     }
1.259     www      1294: # Notify homeserver to grep it
                   1295: #
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);
1.613     albertel 1311:     return &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);
1.611     albertel 2709:     if (($space=~/^(uploaded|ediupload)$/) && ($ENV{'user.name'} eq $name) && 
1.546     albertel 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
1.611     albertel 2778: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 2779:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.612     albertel 2780: 	my $refuri=$ENV{'httpref.'.$orguri};
1.492     albertel 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;
1.613     albertel 3718:     my %locked = &get('file_permissions',\@check,
                   3719: 		      $ENV{'user.domain'},$ENV{'user.name'});
1.615   ! albertel 3720:     my ($tmp)=keys(%locked);
        !          3721:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 3722: 
1.566     banghart 3723:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   3724:         $is_locked = 'true';
                   3725:     } else {
                   3726:         $is_locked = 'false';
                   3727:     }
                   3728: }
                   3729: 
1.559     banghart 3730: # ------------------------------------------------------------- Mark as Read Only
                   3731: 
                   3732: sub mark_as_readonly {
                   3733:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 3734:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615   ! albertel 3735:     my ($tmp)=keys(%current_permissions);
        !          3736:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3737: 
1.560     banghart 3738:     foreach my $file (@{$files}) {
1.561     banghart 3739:         push(@{$current_permissions{$file}},$what);
1.559     banghart 3740:     }
1.613     albertel 3741:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3742:     return;
                   3743: }
                   3744: 
1.572     banghart 3745: # ------------------------------------------------------------Save Selected Files
                   3746: 
                   3747: sub save_selected_files {
                   3748:     my ($user, $path, @files) = @_;
                   3749:     my $filename = $user."savedfiles";
1.573     banghart 3750:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 3751:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3752:     foreach my $file (@files) {
1.574     banghart 3753:         print (OUT $ENV{'form.currentpath'}.$file."\n");
1.573     banghart 3754:     }
                   3755:     foreach my $file (@other_files) {
1.574     banghart 3756:         print (OUT $file."\n");
1.572     banghart 3757:     }
1.574     banghart 3758:     close (OUT);
1.572     banghart 3759:     return 'ok';
                   3760: }
                   3761: 
1.574     banghart 3762: sub clear_selected_files {
                   3763:     my ($user) = @_;
                   3764:     my $filename = $user."savedfiles";
                   3765:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   3766:     print (OUT undef);
                   3767:     close (OUT);
                   3768:     return ("ok");    
                   3769: }
                   3770: 
1.572     banghart 3771: sub files_in_path {
                   3772:     my ($user, $path) = @_;
                   3773:     my $filename = $user."savedfiles";
                   3774:     my %return_files;
1.574     banghart 3775:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3776:     while (my $line_in = <IN>) {
1.574     banghart 3777:         chomp ($line_in);
                   3778:         my @paths_and_file = split (m!/!, $line_in);
                   3779:         my $file_part = pop (@paths_and_file);
                   3780:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 3781:         $path_part.='/';
                   3782:         my $path_and_file = $path_part.$file_part;
                   3783:         if ($path_part eq $path) {
                   3784:             $return_files{$file_part}= 'selected';
                   3785:         }
                   3786:     }
1.574     banghart 3787:     close (IN);
                   3788:     return (\%return_files);
1.572     banghart 3789: }
                   3790: 
                   3791: # called in portfolio select mode, to show files selected NOT in current directory
                   3792: sub files_not_in_path {
                   3793:     my ($user, $path) = @_;
                   3794:     my $filename = $user."savedfiles";
                   3795:     my @return_files;
                   3796:     my $path_part;
1.574     banghart 3797:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 3798:     while (<IN>) {
                   3799:         #ok, I know it's clunky, but I want it to work
                   3800:         my @paths_and_file = split m!/!, $_;
1.574     banghart 3801:         my $file_part = pop (@paths_and_file);
                   3802:         chomp ($file_part);
                   3803:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 3804:         $path_part .= '/';
                   3805:         my $path_and_file = $path_part.$file_part;
                   3806:         if ($path_part ne $path) {
1.574     banghart 3807:             push (@return_files, ($path_and_file));
1.572     banghart 3808:         }
                   3809:     }
1.574     banghart 3810:     close (OUT);
                   3811:     return (@return_files);
1.572     banghart 3812: }
                   3813: 
1.561     banghart 3814: #--------------------------------------------------------------Get Marked as Read Only
                   3815: 
                   3816: sub get_marked_as_readonly {
                   3817:     my ($domain,$user,$what) = @_;
1.613     albertel 3818:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615   ! albertel 3819:     my ($tmp)=keys(%current_permissions);
        !          3820:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3821: 
1.563     banghart 3822:     my @readonly_files;
                   3823:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 3824:         if (ref($value) eq "ARRAY"){
                   3825:             foreach my $stored_what (@{$value}) {
                   3826:                 if ($stored_what eq $what) {
                   3827:                     push(@readonly_files, $file_name);
1.563     banghart 3828:                 } elsif (!defined($what)) {
                   3829:                     push(@readonly_files, $file_name);
1.561     banghart 3830:                 }
                   3831:             }
                   3832:         } 
                   3833:     }
                   3834:     return @readonly_files;
                   3835: }
1.577     banghart 3836: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 3837: 
1.577     banghart 3838: sub get_marked_as_readonly_hash {
                   3839:     my ($domain,$user,$what) = @_;
1.613     albertel 3840:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615   ! albertel 3841:     my ($tmp)=keys(%current_permissions);
        !          3842:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3843: 
1.577     banghart 3844:     my %readonly_files;
                   3845:     while (my ($file_name,$value) = each(%current_permissions)) {
                   3846:         if (ref($value) eq "ARRAY"){
                   3847:             foreach my $stored_what (@{$value}) {
                   3848:                 if ($stored_what eq $what) {
                   3849:                     $readonly_files{$file_name} = 'locked';
                   3850:                 } elsif (!defined($what)) {
                   3851:                     $readonly_files{$file_name} = 'locked';
                   3852:                 }
                   3853:             }
                   3854:         } 
                   3855:     }
                   3856:     return %readonly_files;
                   3857: }
1.559     banghart 3858: # ------------------------------------------------------------ Unmark as Read Only
                   3859: 
                   3860: sub unmark_as_readonly {
1.561     banghart 3861:     # unmarks all files locked by $what 
                   3862:     # for portfolio submissions, $what contains $crsid and $symb
                   3863:     my ($domain,$user,$what) = @_;
1.613     albertel 3864:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615   ! albertel 3865:     my ($tmp)=keys(%current_permissions);
        !          3866:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3867: 
                   3868:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.561     banghart 3869:     foreach my $file(@readonly_files){
1.563     banghart 3870:         my $current_locks = $current_permissions{$file};
                   3871:         my @new_locks;
                   3872:         my @del_keys;
                   3873:         if (ref($current_locks) eq "ARRAY"){
                   3874:             foreach my $locker (@{$current_locks}) {
                   3875:                 unless ($locker eq $what) {
                   3876:                     push(@new_locks, $what);
                   3877:                 }
                   3878:             }
                   3879:             if (@new_locks > 0) {
                   3880:                 $current_permissions{$file} = \@new_locks;
                   3881:             } else {
                   3882:                 push(@del_keys, $file);
1.613     albertel 3883:                 &del('file_permissions',\@del_keys, $domain, $user);
1.563     banghart 3884:                 delete $current_permissions{$file};
                   3885:             }
                   3886:         }
1.561     banghart 3887:     }
1.613     albertel 3888:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3889:     return;
                   3890: }
1.512     banghart 3891: 
1.17      www      3892: # ------------------------------------------------------------ Directory lister
                   3893: 
                   3894: sub dirlist {
1.253     stredwic 3895:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   3896: 
1.18      www      3897:     $uri=~s/^\///;
                   3898:     $uri=~s/\/$//;
1.253     stredwic 3899:     my ($udom, $uname);
                   3900:     (undef,$udom,$uname)=split(/\//,$uri);
                   3901:     if(defined($userdomain)) {
                   3902:         $udom = $userdomain;
                   3903:     }
                   3904:     if(defined($username)) {
                   3905:         $uname = $username;
                   3906:     }
                   3907: 
                   3908:     my $dirRoot = $perlvar{'lonDocRoot'};
                   3909:     if(defined($alternateDirectoryRoot)) {
                   3910:         $dirRoot = $alternateDirectoryRoot;
                   3911:         $dirRoot =~ s/\/$//;
                   3912:     }
                   3913: 
                   3914:     if($udom) {
                   3915:         if($uname) {
1.605     matthew  3916:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 3917:                               homeserver($uname,$udom));
1.605     matthew  3918:             my @listing_results;
                   3919:             if ($listing eq 'unknown_cmd') {
                   3920:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   3921:                                homeserver($uname,$udom));
                   3922:                 @listing_results = split(/:/,$listing);
                   3923:             } else {
                   3924:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   3925:             }
                   3926:             return @listing_results;
1.253     stredwic 3927:         } elsif(!defined($alternateDirectoryRoot)) {
                   3928:             my $tryserver;
                   3929:             my %allusers=();
                   3930:             foreach $tryserver (keys %libserv) {
                   3931:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  3932:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 3933:                                       $udom, $tryserver);
1.605     matthew  3934:                     my @listing_results;
                   3935:                     if ($listing eq 'unknown_cmd') {
                   3936:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   3937:                                        $udom, $tryserver);
                   3938:                         @listing_results = split(/:/,$listing);
                   3939:                     } else {
                   3940:                         @listing_results =
                   3941:                             map { &unescape($_); } split(/:/,$listing);
                   3942:                     }
                   3943:                     if ($listing_results[0] ne 'no_such_dir' && 
                   3944:                         $listing_results[0] ne 'empty'       &&
                   3945:                         $listing_results[0] ne 'con_lost') {
                   3946:                         foreach (@listing_results) {
1.253     stredwic 3947:                             my ($entry,@stat)=split(/&/,$_);
                   3948:                             $allusers{$entry}=1;
                   3949:                         }
                   3950:                     }
1.191     harris41 3951:                 }
1.253     stredwic 3952:             }
                   3953:             my $alluserstr='';
                   3954:             foreach (sort keys %allusers) {
                   3955:                 $alluserstr.=$_.'&user:';
                   3956:             }
                   3957:             $alluserstr=~s/:$//;
                   3958:             return split(/:/,$alluserstr);
                   3959:         } else {
                   3960:             my @emptyResults = ();
                   3961:             push(@emptyResults, 'missing user name');
                   3962:             return split(':',@emptyResults);
                   3963:         }
                   3964:     } elsif(!defined($alternateDirectoryRoot)) {
                   3965:         my $tryserver;
                   3966:         my %alldom=();
                   3967:         foreach $tryserver (keys %libserv) {
                   3968:             $alldom{$hostdom{$tryserver}}=1;
                   3969:         }
                   3970:         my $alldomstr='';
                   3971:         foreach (sort keys %alldom) {
1.397     albertel 3972:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 3973:         }
                   3974:         $alldomstr=~s/:$//;
                   3975:         return split(/:/,$alldomstr);       
                   3976:     } else {
                   3977:         my @emptyResults = ();
                   3978:         push(@emptyResults, 'missing domain');
                   3979:         return split(':',@emptyResults);
1.275     stredwic 3980:     }
                   3981: }
                   3982: 
                   3983: # --------------------------------------------- GetFileTimestamp
                   3984: # This function utilizes dirlist and returns the date stamp for
                   3985: # when it was last modified.  It will also return an error of -1
                   3986: # if an error occurs
                   3987: 
1.410     matthew  3988: ##
                   3989: ## FIXME: This subroutine assumes its caller knows something about the
                   3990: ## directory structure of the home server for the student ($root).
                   3991: ## Not a good assumption to make.  Since this is for looking up files
                   3992: ## in user directories, the full path should be constructed by lond, not
                   3993: ## whatever machine we request data from.
                   3994: ##
1.275     stredwic 3995: sub GetFileTimestamp {
                   3996:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   3997:     $studentDomain=~s/\W//g;
                   3998:     $studentName=~s/\W//g;
                   3999:     my $subdir=$studentName.'__';
                   4000:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4001:     my $proname="$studentDomain/$subdir/$studentName";
                   4002:     $proname .= '/'.$filename;
1.375     matthew  4003:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4004:                                               $studentName, $root);
1.275     stredwic 4005:     my @stats = split('&', $fileStat);
                   4006:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4007:         # @stats contains first the filename, then the stat output
                   4008:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4009:     } else {
                   4010:         return -1;
1.253     stredwic 4011:     }
1.26      www      4012: }
                   4013: 
                   4014: # -------------------------------------------------------- Value of a Condition
                   4015: 
1.40      www      4016: sub directcondval {
                   4017:     my $number=shift;
1.555     albertel 4018:     if (!defined($ENV{'user.state.'.$ENV{'request.course.id'}})) {
                   4019: 	&Apache::lonuserstate::evalstate();
                   4020:     }
1.40      www      4021:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
                   4022:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
                   4023:     } else {
                   4024:        return 2;
                   4025:     }
                   4026: }
                   4027: 
1.26      www      4028: sub condval {
                   4029:     my $condidx=shift;
                   4030:     my $result=0;
1.54      www      4031:     my $allpathcond='';
1.191     harris41 4032:     foreach (split(/\|/,$condidx)) {
1.54      www      4033:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
                   4034: 	   $allpathcond.=
                   4035:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
                   4036:        }
1.191     harris41 4037:     }
1.54      www      4038:     $allpathcond=~s/\|$//;
1.33      www      4039:     if ($ENV{'request.course.id'}) {
1.54      www      4040:        if ($allpathcond) {
1.26      www      4041:           my $operand='|';
                   4042: 	  my @stack;
1.191     harris41 4043:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      4044:               if ($_ eq '(') {
                   4045:                  push @stack,($operand,$result)
                   4046:               } elsif ($_ eq ')') {
                   4047:                   my $before=pop @stack;
                   4048: 		  if (pop @stack eq '&') {
                   4049: 		      $result=$result>$before?$before:$result;
                   4050:                   } else {
                   4051:                       $result=$result>$before?$result:$before;
                   4052:                   }
                   4053:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   4054:                   $operand=$_;
                   4055:               } else {
1.40      www      4056:                   my $new=directcondval($_);
1.26      www      4057:                   if ($operand eq '&') {
                   4058:                      $result=$result>$new?$new:$result;
                   4059:                   } else {
                   4060:                      $result=$result>$new?$result:$new;
1.191     harris41 4061:                   }
1.26      www      4062:               }
1.191     harris41 4063:           }
1.26      www      4064:        }
                   4065:     }
                   4066:     return $result;
1.421     albertel 4067: }
                   4068: 
                   4069: # ---------------------------------------------------- Devalidate courseresdata
                   4070: 
                   4071: sub devalidatecourseresdata {
                   4072:     my ($coursenum,$coursedomain)=@_;
                   4073:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4074:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4075: }
                   4076: 
1.200     www      4077: # --------------------------------------------------- Course Resourcedata Query
                   4078: 
                   4079: sub courseresdata {
                   4080:     my ($coursenum,$coursedomain,@which)=@_;
                   4081:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4082:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4083:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.417     albertel 4084:     unless (defined($cached)) {
1.251     albertel 4085: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4086: 	$result=\%dumpreply;
1.251     albertel 4087: 	my ($tmp) = keys(%dumpreply);
                   4088: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4089: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4090: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4091: 	    return $tmp;
1.416     albertel 4092: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4093: 	    $result=undef;
1.599     albertel 4094: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4095: 	}
                   4096:     }
1.251     albertel 4097:     foreach my $item (@which) {
1.417     albertel 4098: 	if (defined($result->{$item})) {
                   4099: 	    return $result->{$item};
1.251     albertel 4100: 	}
1.250     albertel 4101:     }
1.291     albertel 4102:     return undef;
1.200     www      4103: }
                   4104: 
1.379     matthew  4105: #
                   4106: # EXT resource caching routines
                   4107: #
                   4108: 
                   4109: sub clear_EXT_cache_status {
1.383     albertel 4110:     &delenv('cache.EXT.');
1.379     matthew  4111: }
                   4112: 
                   4113: sub EXT_cache_status {
                   4114:     my ($target_domain,$target_user) = @_;
1.383     albertel 4115:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389     www      4116:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379     matthew  4117:         # We know already the user has no data
                   4118:         return 1;
                   4119:     } else {
                   4120:         return 0;
                   4121:     }
                   4122: }
                   4123: 
                   4124: sub EXT_cache_set {
                   4125:     my ($target_domain,$target_user) = @_;
1.383     albertel 4126:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379     matthew  4127:     &appenv($cachename => time);
                   4128: }
                   4129: 
1.28      www      4130: # --------------------------------------------------------- Value of a Variable
1.58      www      4131: sub EXT {
1.395     albertel 4132:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 4133: 
1.68      www      4134:     unless ($varname) { return ''; }
1.218     albertel 4135:     #get real user name/domain, courseid and symb
                   4136:     my $courseid;
1.359     albertel 4137:     my $publicuser;
1.427     www      4138:     if ($symbparm) {
                   4139: 	$symbparm=&get_symb_from_alias($symbparm);
                   4140:     }
1.218     albertel 4141:     if (!($uname && $udom)) {
1.360     albertel 4142:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4143: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4144:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4145:     } else {
                   4146: 	$courseid=$ENV{'request.course.id'};
                   4147:     }
1.48      www      4148:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4149:     my $rest;
1.320     albertel 4150:     if (defined($therest[0])) {
1.48      www      4151:        $rest=join('.',@therest);
                   4152:     } else {
                   4153:        $rest='';
                   4154:     }
1.320     albertel 4155: 
1.57      www      4156:     my $qualifierrest=$qualifier;
                   4157:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4158:     my $spacequalifierrest=$space;
                   4159:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4160:     if ($realm eq 'user') {
1.48      www      4161: # --------------------------------------------------------------- user.resource
                   4162: 	if ($space eq 'resource') {
1.335     albertel 4163: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
                   4164: 		return $Apache::lonhomework::history{$qualifierrest};
                   4165: 	    } else {
1.359     albertel 4166: 		my %restored;
                   4167: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
                   4168: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   4169: 		} else {
                   4170: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   4171: 		}
1.335     albertel 4172: 		return $restored{$qualifierrest};
                   4173: 	    }
1.48      www      4174: # ----------------------------------------------------------------- user.access
                   4175:         } elsif ($space eq 'access') {
1.218     albertel 4176: 	    # FIXME - not supporting calls for a specific user
1.48      www      4177:             return &allowed($qualifier,$rest);
                   4178: # ------------------------------------------ user.preferences, user.environment
                   4179:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218     albertel 4180: 	    if (($uname eq $ENV{'user.name'}) &&
                   4181: 		($udom eq $ENV{'user.domain'})) {
                   4182: 		return $ENV{join('.',('environment',$qualifierrest))};
                   4183: 	    } else {
1.359     albertel 4184: 		my %returnhash;
                   4185: 		if (!$publicuser) {
                   4186: 		    %returnhash=&userenvironment($udom,$uname,
                   4187: 						 $qualifierrest);
                   4188: 		}
1.218     albertel 4189: 		return $returnhash{$qualifierrest};
                   4190: 	    }
1.48      www      4191: # ----------------------------------------------------------------- user.course
                   4192:         } elsif ($space eq 'course') {
1.218     albertel 4193: 	    # FIXME - not supporting calls for a specific user
1.48      www      4194:             return $ENV{join('.',('request.course',$qualifier))};
                   4195: # ------------------------------------------------------------------- user.role
                   4196:         } elsif ($space eq 'role') {
1.218     albertel 4197: 	    # FIXME - not supporting calls for a specific user
1.48      www      4198:             my ($role,$where)=split(/\./,$ENV{'request.role'});
                   4199:             if ($qualifier eq 'value') {
                   4200: 		return $role;
                   4201:             } elsif ($qualifier eq 'extent') {
                   4202:                 return $where;
                   4203:             }
                   4204: # ----------------------------------------------------------------- user.domain
                   4205:         } elsif ($space eq 'domain') {
1.218     albertel 4206:             return $udom;
1.48      www      4207: # ------------------------------------------------------------------- user.name
                   4208:         } elsif ($space eq 'name') {
1.218     albertel 4209:             return $uname;
1.48      www      4210: # ---------------------------------------------------- Any other user namespace
1.29      www      4211:         } else {
1.359     albertel 4212: 	    my %reply;
                   4213: 	    if (!$publicuser) {
                   4214: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   4215: 	    }
                   4216: 	    return $reply{$qualifierrest};
1.48      www      4217:         }
1.236     www      4218:     } elsif ($realm eq 'query') {
                   4219: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 4220:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   4221: 						[$spacequalifierrest]);
1.376     albertel 4222: 	return $ENV{'form.'.$spacequalifierrest}; 
1.236     www      4223:    } elsif ($realm eq 'request') {
1.48      www      4224: # ------------------------------------------------------------- request.browser
                   4225:         if ($space eq 'browser') {
1.430     www      4226: 	    if ($qualifier eq 'textremote') {
                   4227: 		if (&mt('textual_remote_display') eq 'on') {
                   4228: 		    return 1;
                   4229: 		} else {
                   4230: 		    return 0;
                   4231: 		}
                   4232: 	    } else {
                   4233: 		return $ENV{'browser.'.$qualifier};
                   4234: 	    }
1.57      www      4235: # ------------------------------------------------------------ request.filename
                   4236:         } else {
                   4237:             return $ENV{'request.'.$spacequalifierrest};
1.29      www      4238:         }
1.28      www      4239:     } elsif ($realm eq 'course') {
1.48      www      4240: # ---------------------------------------------------------- course.description
1.218     albertel 4241:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      4242:     } elsif ($realm eq 'resource') {
1.165     www      4243: 
1.395     albertel 4244: 	my $section;
1.359     albertel 4245: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.539     albertel 4246: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   4247: 	}
1.593     albertel 4248: 	my ($courselevelm,$courselevel);
1.539     albertel 4249: 	if ($symbparm && defined($courseid) && 
                   4250: 	    $courseid eq $ENV{'request.course.id'}) {
1.165     www      4251: 
1.218     albertel 4252: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      4253: 
1.60      www      4254: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 4255: 	    my $symbp=$symbparm;
1.409     www      4256: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 4257: 
                   4258: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   4259: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   4260: 
                   4261: 	    if (($ENV{'user.name'} eq $uname) &&
                   4262: 		($ENV{'user.domain'} eq $udom)) {
1.255     albertel 4263: 		$section=$ENV{'request.course.sec'};
1.218     albertel 4264: 	    } else {
1.539     albertel 4265: 		if (! defined($usection)) {
1.551     albertel 4266: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 4267: 		} else {
                   4268: 		    $section = $usection;
                   4269: 		}
1.218     albertel 4270: 	    }
                   4271: 
                   4272: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   4273: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   4274: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   4275: 
1.593     albertel 4276: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 4277: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 4278: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      4279: 
1.60      www      4280: # ----------------------------------------------------------- first, check user
1.379     matthew  4281: 	    #most student don\'t have any data set, check if there is some data
                   4282: 	    if (! &EXT_cache_status($udom,$uname)) {
1.420     albertel 4283: 		my $hashid="$udom:$uname";
1.599     albertel 4284: 		my ($result,$cached)=&is_cached_new('userres',$hashid);
1.454     albertel 4285: 		if (!defined($cached)) {
                   4286: 		    my %resourcedata=&dump('resourcedata',$udom,$uname);
1.420     albertel 4287: 		    $result=\%resourcedata;
1.599     albertel 4288: 		    &do_cache_new('userres',$hashid,$result);
1.420     albertel 4289: 		}
                   4290: 		my ($tmp)=keys(%$result);
1.308     albertel 4291: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
1.420     albertel 4292: 		    if ($$result{$courselevelr}) {
                   4293: 			return $$result{$courselevelr}; }
                   4294: 		    if ($$result{$courselevelm}) {
                   4295: 			return $$result{$courselevelm}; }
                   4296: 		    if ($$result{$courselevel}) {
                   4297: 			return $$result{$courselevel}; }
1.308     albertel 4298: 		} else {
1.459     albertel 4299: 		    #error 2 occurs when the .db doesn't exist
                   4300: 		    if ($tmp!~/error: 2 /) {
1.308     albertel 4301: 			&logthis("<font color=blue>WARNING:".
                   4302: 				 " Trying to get resource data for ".
                   4303: 				 $uname." at ".$udom.": ".
                   4304: 				 $tmp."</font>");
1.459     albertel 4305: 		    } elsif ($tmp=~/error: 2 /) {
1.539     albertel 4306: 			&EXT_cache_set($udom,$uname);
1.308     albertel 4307: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4308: 			return $tmp;
                   4309: 		    }
1.218     albertel 4310: 		}
                   4311: 	    }
1.95      www      4312: 
1.594     albertel 4313: # ------------------------------------------------ second, check some of course
1.96      www      4314: 
1.218     albertel 4315: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
1.539     albertel 4316: 					   $ENV{'course.'.$courseid.'.domain'},
                   4317: 					   ($seclevelr,$seclevelm,$seclevel,
1.593     albertel 4318: 					    $courselevelr));
1.287     albertel 4319: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      4320: 
1.60      www      4321: # ------------------------------------------------------ third, check map parms
1.218     albertel 4322: 	    my %parmhash=();
                   4323: 	    my $thisparm='';
                   4324: 	    if (tie(%parmhash,'GDBM_File',
                   4325: 		    $ENV{'request.course.fn'}.'_parms.db',
1.256     albertel 4326: 		    &GDBM_READER(),0640)) {
1.218     albertel 4327: 		$thisparm=$parmhash{$symbparm};
                   4328: 		untie(%parmhash);
                   4329: 	    }
                   4330: 	    if ($thisparm) { return $thisparm; }
                   4331: 	}
1.594     albertel 4332: # ------------------------------------------ fourth, look in resource metadata
1.71      www      4333: 
1.218     albertel 4334: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 4335: 	my $filename;
                   4336: 	if (!$symbparm) { $symbparm=&symbread(); }
                   4337: 	if ($symbparm) {
1.409     www      4338: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 4339: 	} else {
                   4340: 	    $filename=$ENV{'request.filename'};
                   4341: 	}
                   4342: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 4343: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 4344: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 4345: 	if (defined($metadata)) { return $metadata; }
1.142     www      4346: 
1.594     albertel 4347: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 4348: 	if ($symbparm && defined($courseid) && 
                   4349: 	    $courseid eq $ENV{'request.course.id'}) {
                   4350: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
                   4351: 					   $ENV{'course.'.$courseid.'.domain'},
                   4352: 					   ($courselevelm,$courselevel));
                   4353: 	    if (defined($coursereply)) { return $coursereply; }
                   4354: 	}
1.145     www      4355: # ------------------------------------------------------------------ Cascade up
1.218     albertel 4356: 	unless ($space eq '0') {
1.336     albertel 4357: 	    my @parts=split(/_/,$space);
                   4358: 	    my $id=pop(@parts);
                   4359: 	    my $part=join('_',@parts);
                   4360: 	    if ($part eq '') { $part='0'; }
                   4361: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 4362: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 4363: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 4364: 	}
1.395     albertel 4365: 	if ($recurse) { return undef; }
                   4366: 	my $pack_def=&packages_tab_default($filename,$varname);
                   4367: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      4368: 
1.48      www      4369: # ---------------------------------------------------- Any other user namespace
                   4370:     } elsif ($realm eq 'environment') {
                   4371: # ----------------------------------------------------------------- environment
1.219     albertel 4372: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
                   4373: 	    return $ENV{'environment.'.$spacequalifierrest};
                   4374: 	} else {
                   4375: 	    my %returnhash=&userenvironment($udom,$uname,
                   4376: 					    $spacequalifierrest);
                   4377: 	    return $returnhash{$spacequalifierrest};
                   4378: 	}
1.28      www      4379:     } elsif ($realm eq 'system') {
1.48      www      4380: # ----------------------------------------------------------------- system.time
                   4381: 	if ($space eq 'time') {
                   4382: 	    return time;
                   4383:         }
1.28      www      4384:     }
1.48      www      4385:     return '';
1.61      www      4386: }
                   4387: 
1.395     albertel 4388: sub packages_tab_default {
                   4389:     my ($uri,$varname)=@_;
                   4390:     my (undef,$part,$name)=split(/\./,$varname);
                   4391:     my $packages=&metadata($uri,'packages');
                   4392:     foreach my $package (split(/,/,$packages)) {
                   4393: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 4394: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   4395: 	    return $packagetab{"$pack_type&$name&default"};
                   4396: 	}
1.585     albertel 4397: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 4398: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   4399: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 4400: 	}
                   4401:     }
                   4402:     return undef;
                   4403: }
                   4404: 
1.334     albertel 4405: sub add_prefix_and_part {
                   4406:     my ($prefix,$part)=@_;
                   4407:     my $keyroot;
                   4408:     if (defined($prefix) && $prefix !~ /^__/) {
                   4409: 	# prefix that has a part already
                   4410: 	$keyroot=$prefix;
                   4411:     } elsif (defined($prefix)) {
                   4412: 	# prefix that is missing a part
                   4413: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   4414:     } else {
                   4415: 	# no prefix at all
                   4416: 	if (defined($part)) { $keyroot='_'.$part; }
                   4417:     }
                   4418:     return $keyroot;
                   4419: }
                   4420: 
1.71      www      4421: # ---------------------------------------------------------------- Get metadata
                   4422: 
1.599     albertel 4423: my %metaentry;
1.71      www      4424: sub metadata {
1.176     www      4425:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      4426:     $uri=&declutter($uri);
1.288     albertel 4427:     # if it is a non metadata possible uri return quickly
1.529     albertel 4428:     if (($uri eq '') || 
                   4429: 	(($uri =~ m|^/*adm/|) && 
                   4430: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 4431:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 4432: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 4433: 	return undef;
1.288     albertel 4434:     }
1.73      www      4435:     my $filename=$uri;
                   4436:     $uri=~s/\.meta$//;
1.172     www      4437: #
                   4438: # Is the metadata already cached?
1.177     www      4439: # Look at timestamp of caching
1.172     www      4440: # Everything is cached by the main uri, libraries are never directly cached
                   4441: #
1.428     albertel 4442:     if (!defined($liburi)) {
1.599     albertel 4443: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 4444: 	if (defined($cached)) { return $result->{':'.$what}; }
                   4445:     }
                   4446:     {
1.172     www      4447: #
                   4448: # Is this a recursive call for a library?
                   4449: #
1.599     albertel 4450: #	if (! exists($metacache{$uri})) {
                   4451: #	    $metacache{$uri}={};
                   4452: #	}
1.171     www      4453:         if ($liburi) {
                   4454: 	    $liburi=&declutter($liburi);
                   4455:             $filename=$liburi;
1.401     bowersj2 4456:         } else {
1.599     albertel 4457: 	    &devalidate_cache_new('meta',$uri);
                   4458: 	    undef(%metaentry);
1.401     bowersj2 4459: 	}
1.140     www      4460:         my %metathesekeys=();
1.73      www      4461:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 4462: 	my $metastring;
1.609     banghart 4463: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 4464: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 4465: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 4466: 	    $metastring=&getfile($file);
1.489     albertel 4467: 	}
1.208     albertel 4468:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      4469:         my $token;
1.140     www      4470:         undef %metathesekeys;
1.71      www      4471:         while ($token=$parser->get_token) {
1.339     albertel 4472: 	    if ($token->[0] eq 'S') {
                   4473: 		if (defined($token->[2]->{'package'})) {
1.172     www      4474: #
                   4475: # This is a package - get package info
                   4476: #
1.339     albertel 4477: 		    my $package=$token->[2]->{'package'};
                   4478: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4479: 		    if (defined($token->[2]->{'id'})) { 
                   4480: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   4481: 		    }
1.599     albertel 4482: 		    if ($metaentry{':packages'}) {
                   4483: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 4484: 		    } else {
1.599     albertel 4485: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 4486: 		    }
1.613     albertel 4487: 		    foreach (sort keys %packagetab) {
1.432     albertel 4488: 			my $part=$keyroot;
                   4489: 			$part=~s/^\_//;
                   4490: 			if ($_=~/^\Q$package\E\&/ || 
                   4491: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 4492: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 4493: 			    # ignore package.tab specified default values
                   4494:                             # here &package_tab_default() will fetch those
                   4495: 			    if ($subp eq 'default') { next; }
1.339     albertel 4496: 			    my $value=$packagetab{$_};
1.432     albertel 4497: 			    my $unikey;
                   4498: 			    if ($pack =~ /_0$/) {
                   4499: 				$unikey='parameter_0_'.$name;
                   4500: 				$part=0;
                   4501: 			    } else {
                   4502: 				$unikey='parameter'.$keyroot.'_'.$name;
                   4503: 			    }
1.339     albertel 4504: 			    if ($subp eq 'display') {
                   4505: 				$value.=' [Part: '.$part.']';
                   4506: 			    }
1.599     albertel 4507: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 4508: 			    $metathesekeys{$unikey}=1;
1.599     albertel 4509: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4510: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 4511: 			    }
1.599     albertel 4512: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   4513: 				$metaentry{':'.$unikey}=
                   4514: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 4515: 			    }
1.339     albertel 4516: 			}
                   4517: 		    }
                   4518: 		} else {
1.172     www      4519: #
                   4520: # This is not a package - some other kind of start tag
1.339     albertel 4521: #
                   4522: 		    my $entry=$token->[1];
                   4523: 		    my $unikey;
                   4524: 		    if ($entry eq 'import') {
                   4525: 			$unikey='';
                   4526: 		    } else {
                   4527: 			$unikey=$entry;
                   4528: 		    }
                   4529: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4530: 
                   4531: 		    if (defined($token->[2]->{'id'})) { 
                   4532: 			$unikey.='_'.$token->[2]->{'id'}; 
                   4533: 		    }
1.175     www      4534: 
1.339     albertel 4535: 		    if ($entry eq 'import') {
1.175     www      4536: #
                   4537: # Importing a library here
1.339     albertel 4538: #
                   4539: 			if ($depthcount<20) {
                   4540: 			    my $location=$parser->get_text('/import');
                   4541: 			    my $dir=$filename;
                   4542: 			    $dir=~s|[^/]*$||;
                   4543: 			    $location=&filelocation($dir,$location);
                   4544: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4545: 							       $location,$unikey,
                   4546: 							       $depthcount+1)))) {
1.599     albertel 4547: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 4548: 				$metathesekeys{$_}=1;
                   4549: 			    }
                   4550: 			}
                   4551: 		    } else { 
                   4552: 			
                   4553: 			if (defined($token->[2]->{'name'})) { 
                   4554: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   4555: 			}
                   4556: 			$metathesekeys{$unikey}=1;
                   4557: 			foreach (@{$token->[3]}) {
1.599     albertel 4558: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 4559: 			}
                   4560: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 4561: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 4562: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   4563: 		 # only ws inside the tag, and not in default, so use default
                   4564: 		 # as value
1.599     albertel 4565: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 4566: 			} else {
1.321     albertel 4567: 		  # either something interesting inside the tag or default
                   4568:                   # uninteresting
1.599     albertel 4569: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 4570: 			}
1.172     www      4571: # end of not-a-package not-a-library import
1.339     albertel 4572: 		    }
1.172     www      4573: # end of not-a-package start tag
1.339     albertel 4574: 		}
1.172     www      4575: # the next is the end of "start tag"
1.339     albertel 4576: 	    }
                   4577: 	}
1.483     albertel 4578: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   4579: 	foreach my $key (sort(keys(%packagetab))) {
                   4580: 	    #&logthis("extsion1 $extension $key !!");
                   4581: 	    #no specific packages #how's our extension
                   4582: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 4583: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 4584: 					 \%metathesekeys);
                   4585: 	}
1.599     albertel 4586: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 4587: 	    foreach my $key (sort(keys(%packagetab))) {
                   4588: 		#no specific packages well let's get default then
                   4589: 		if ($key!~/^default&/) { next; }
1.488     albertel 4590: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 4591: 					     \%metathesekeys);
                   4592: 	    }
                   4593: 	}
1.338     www      4594: # are there custom rights to evaluate
1.599     albertel 4595: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 4596: 
1.338     www      4597:     #
                   4598:     # Importing a rights file here
1.339     albertel 4599:     #
                   4600: 	    unless ($depthcount) {
1.599     albertel 4601: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 4602: 		my $dir=$filename;
                   4603: 		$dir=~s|[^/]*$||;
                   4604: 		$location=&filelocation($dir,$location);
                   4605: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4606: 						   $location,'_rights',
                   4607: 						   $depthcount+1)))) {
1.599     albertel 4608: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 4609: 		    $metathesekeys{$_}=1;
                   4610: 		}
                   4611: 	    }
                   4612: 	}
1.599     albertel 4613: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   4614: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   4615: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
                   4616: 	&do_cache_new('meta',$uri,\%metaentry);
1.177     www      4617: # this is the end of "was not already recently cached
1.71      www      4618:     }
1.599     albertel 4619:     return $metaentry{':'.$what};
1.261     albertel 4620: }
                   4621: 
1.488     albertel 4622: sub metadata_create_package_def {
1.483     albertel 4623:     my ($uri,$key,$package,$metathesekeys)=@_;
                   4624:     my ($pack,$name,$subp)=split(/\&/,$key);
                   4625:     if ($subp eq 'default') { next; }
                   4626:     
1.599     albertel 4627:     if (defined($metaentry{':packages'})) {
                   4628: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 4629:     } else {
1.599     albertel 4630: 	$metaentry{':packages'}=$package;
1.483     albertel 4631:     }
                   4632:     my $value=$packagetab{$key};
                   4633:     my $unikey;
                   4634:     $unikey='parameter_0_'.$name;
1.599     albertel 4635:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 4636:     $$metathesekeys{$unikey}=1;
1.599     albertel 4637:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4638: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 4639:     }
1.599     albertel 4640:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   4641: 	$metaentry{':'.$unikey}=
                   4642: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 4643:     }
                   4644: }
                   4645: 
1.261     albertel 4646: sub metadata_generate_part0 {
                   4647:     my ($metadata,$metacache,$uri) = @_;
                   4648:     my %allnames;
                   4649:     foreach my $metakey (sort keys %$metadata) {
                   4650: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 4651: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   4652: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 4653: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 4654: 	    $allnames{$name}=$part;
                   4655: 	  }
                   4656: 	}
                   4657:     }
                   4658:     foreach my $name (keys(%allnames)) {
                   4659:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 4660:       my $key=":parameter_0_$name";
1.261     albertel 4661:       $$metacache{"$key.part"}='0';
                   4662:       $$metacache{"$key.name"}=$name;
1.428     albertel 4663:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 4664: 					   $allnames{$name}.'_'.$name.
                   4665: 					   '.type'};
1.428     albertel 4666:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 4667: 			     '.display'};
                   4668:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
1.479     albertel 4669:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 4670:       $$metacache{"$key.display"}=$olddis;
                   4671:     }
1.71      www      4672: }
                   4673: 
1.301     www      4674: # ------------------------------------------------- Get the title of a resource
                   4675: 
                   4676: sub gettitle {
                   4677:     my $urlsymb=shift;
                   4678:     my $symb=&symbread($urlsymb);
1.534     albertel 4679:     if ($symb) {
1.599     albertel 4680: 	my $key=$ENV{'request.course.id'}."\0".$symb;
                   4681: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 4682: 	if (defined($cached)) { 
                   4683: 	    return $result;
                   4684: 	}
1.534     albertel 4685: 	my ($map,$resid,$url)=&decode_symb($symb);
                   4686: 	my $title='';
                   4687: 	my %bighash;
                   4688: 	if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                   4689: 		&GDBM_READER(),0640)) {
                   4690: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   4691: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   4692: 	    untie %bighash;
                   4693: 	}
                   4694: 	$title=~s/\&colon\;/\:/gs;
                   4695: 	if ($title) {
1.599     albertel 4696: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 4697: 	}
                   4698: 	$urlsymb=$url;
                   4699:     }
                   4700:     my $title=&metadata($urlsymb,'title');
                   4701:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   4702:     return $title;
1.301     www      4703: }
1.613     albertel 4704: 
1.614     albertel 4705: sub get_slot {
                   4706:     my ($which,$cnum,$cdom)=@_;
                   4707:     if (!$cnum || !$cdom) {
                   4708: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
                   4709: 	$cdom=$ENV{'course.'.$courseid.'.domain'};
                   4710: 	$cnum=$ENV{'course.'.$courseid.'.num'};
                   4711:     }
                   4712:     my %slotinfo=&get('slots',[$which],$cdom,$cnum);
                   4713:     &Apache::lonhomework::showhash(%slotinfo);
                   4714:     my ($tmp)=keys(%slotinfo);
                   4715:     if ($tmp=~/^error:/) { return (); }
                   4716:     return %{$slotinfo{$which}};
                   4717: }
1.31      www      4718: # ------------------------------------------------- Update symbolic store links
                   4719: 
                   4720: sub symblist {
                   4721:     my ($mapname,%newhash)=@_;
1.438     www      4722:     $mapname=&deversion(&declutter($mapname));
1.31      www      4723:     my %hash;
                   4724:     if (($ENV{'request.course.fn'}) && (%newhash)) {
                   4725:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 4726:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 4727: 	    foreach (keys %newhash) {
1.601     albertel 4728:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
                   4729: 						  $newhash{$_}->[0]);
1.191     harris41 4730:             }
1.31      www      4731:             if (untie(%hash)) {
                   4732: 		return 'ok';
                   4733:             }
                   4734:         }
                   4735:     }
                   4736:     return 'error';
1.212     www      4737: }
                   4738: 
                   4739: # --------------------------------------------------------------- Verify a symb
                   4740: 
                   4741: sub symbverify {
1.510     www      4742:     my ($symb,$thisurl)=@_;
                   4743:     my $thisfn=$thisurl;
                   4744: # wrapper not part of symbs
                   4745:     $thisfn=~s/^\/adm\/wrapper//;
1.439     www      4746:     $thisfn=&declutter($thisfn);
1.215     www      4747: # direct jump to resource in page or to a sequence - will construct own symbs
                   4748:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   4749: # check URL part
1.409     www      4750:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      4751: 
1.431     www      4752:     unless ($url eq $thisfn) { return 0; }
1.213     www      4753: 
1.216     www      4754:     $symb=&symbclean($symb);
1.510     www      4755:     $thisurl=&deversion($thisurl);
1.439     www      4756:     $thisfn=&deversion($thisfn);
1.213     www      4757: 
                   4758:     my %bighash;
                   4759:     my $okay=0;
1.431     www      4760: 
1.213     www      4761:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 4762:                             &GDBM_READER(),0640)) {
1.510     www      4763:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      4764:         unless ($ids) { 
1.510     www      4765:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      4766:         }
                   4767:         if ($ids) {
                   4768: # ------------------------------------------------------------------- Has ID(s)
                   4769: 	    foreach (split(/\,/,$ids)) {
                   4770:                my ($mapid,$resid)=split(/\./,$_);
                   4771:                if (
                   4772:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   4773:    eq $symb) { 
1.582     albertel 4774: 		   if (($ENV{'request.role.adv'}) ||
                   4775: 		       $bighash{'encrypted_'.$_} eq $ENV{'request.enc'}) {
                   4776: 		       $okay=1; 
                   4777: 		   }
                   4778: 	       }
1.216     www      4779: 	   }
                   4780:         }
1.213     www      4781: 	untie(%bighash);
                   4782:     }
                   4783:     return $okay;
1.31      www      4784: }
                   4785: 
1.210     www      4786: # --------------------------------------------------------------- Clean-up symb
                   4787: 
                   4788: sub symbclean {
                   4789:     my $symb=shift;
1.568     albertel 4790:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      4791: # remove version from map
                   4792:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      4793: 
1.210     www      4794: # remove version from URL
                   4795:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      4796: 
1.507     www      4797: # remove wrapper
                   4798: 
1.510     www      4799:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210     www      4800:     return $symb;
1.409     www      4801: }
                   4802: 
                   4803: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 4804: 
                   4805: sub encode_symb {
                   4806:     my ($map,$resid,$url)=@_;
                   4807:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   4808: }
1.409     www      4809: 
                   4810: sub decode_symb {
1.568     albertel 4811:     my $symb=shift;
                   4812:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   4813:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      4814:     return (&fixversion($map),$resid,&fixversion($url));
                   4815: }
                   4816: 
                   4817: sub fixversion {
                   4818:     my $fn=shift;
1.609     banghart 4819:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      4820:     my %bighash;
                   4821:     my $uri=&clutter($fn);
1.440     www      4822:     my $key=$ENV{'request.course.id'}.'_'.$uri;
                   4823: # is this cached?
1.599     albertel 4824:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      4825:     if (defined($cached)) { return $result; }
                   4826: # unfortunately not cached, or expired
1.435     www      4827:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.440     www      4828: 	    &GDBM_READER(),0640)) {
                   4829:  	if ($bighash{'version_'.$uri}) {
                   4830:  	    my $version=$bighash{'version_'.$uri};
1.444     www      4831:  	    unless (($version eq 'mostrecent') || 
                   4832: 		    ($version==&getversion($uri))) {
1.440     www      4833:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   4834:  	    }
                   4835:  	}
                   4836:  	untie %bighash;
1.413     www      4837:     }
1.599     albertel 4838:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      4839: }
                   4840: 
                   4841: sub deversion {
                   4842:     my $url=shift;
                   4843:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   4844:     return $url;
1.210     www      4845: }
                   4846: 
1.31      www      4847: # ------------------------------------------------------ Return symb list entry
                   4848: 
                   4849: sub symbread {
1.249     www      4850:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 4851:     my $cache_str='request.symbread.cached.'.$thisfn;
                   4852:     if (defined($ENV{$cache_str})) { return $ENV{$cache_str}; }
1.242     www      4853: # no filename provided? try from environment
1.44      www      4854:     unless ($thisfn) {
1.539     albertel 4855:         if ($ENV{'request.symb'}) {
1.542     albertel 4856: 	    return $ENV{$cache_str}=&symbclean($ENV{'request.symb'});
1.539     albertel 4857: 	}
1.44      www      4858: 	$thisfn=$ENV{'request.filename'};
                   4859:     }
1.569     albertel 4860:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      4861: # is that filename actually a symb? Verify, clean, and return
                   4862:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 4863: 	if (&symbverify($thisfn,$1)) {
1.542     albertel 4864: 	    return $ENV{$cache_str}=&symbclean($thisfn);
1.539     albertel 4865: 	}
1.242     www      4866:     }
1.44      www      4867:     $thisfn=declutter($thisfn);
1.31      www      4868:     my %hash;
1.37      www      4869:     my %bighash;
                   4870:     my $syval='';
1.45      www      4871:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  4872:         my $targetfn = $thisfn;
1.609     banghart 4873:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  4874:             $targetfn = 'adm/wrapper/'.$thisfn;
                   4875:         }
1.31      www      4876:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256     albertel 4877:                       &GDBM_READER(),0640)) {
1.481     raeburn  4878: 	    $syval=$hash{$targetfn};
1.37      www      4879:             untie(%hash);
                   4880:         }
                   4881: # ---------------------------------------------------------- There was an entry
                   4882:         if ($syval) {
1.601     albertel 4883: 	    #unless ($syval=~/\_\d+$/) {
                   4884: 		#unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
                   4885: 		    #&appenv('request.ambiguous' => $thisfn);
                   4886: 		    #return $ENV{$cache_str}='';
                   4887: 		#}    
                   4888: 		#$syval.=$1;
                   4889: 	    #}
1.37      www      4890:         } else {
                   4891: # ------------------------------------------------------- Was not in symb table
                   4892:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256     albertel 4893:                             &GDBM_READER(),0640)) {
1.37      www      4894: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      4895:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      4896:               unless ($ids) { 
                   4897:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      4898:               }
                   4899:               unless ($ids) {
                   4900: # alias?
                   4901: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      4902:               }
1.37      www      4903:               if ($ids) {
                   4904: # ------------------------------------------------------------------- Has ID(s)
                   4905:                  my @possibilities=split(/\,/,$ids);
1.39      www      4906:                  if ($#possibilities==0) {
                   4907: # ----------------------------------------------- There is only one possibility
1.37      www      4908: 		     my ($mapid,$resid)=split(/\./,$ids);
                   4909:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249     www      4910:                  } elsif (!$donotrecurse) {
1.39      www      4911: # ------------------------------------------ There is more than one possibility
                   4912:                      my $realpossible=0;
1.191     harris41 4913:                      foreach (@possibilities) {
1.39      www      4914: 			 my $file=$bighash{'src_'.$_};
                   4915:                          if (&allowed('bre',$file)) {
                   4916:          		    my ($mapid,$resid)=split(/\./,$_);
                   4917:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   4918: 				$realpossible++;
                   4919:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
                   4920:                                        '___'.$resid;
                   4921:                             }
                   4922: 			 }
1.191     harris41 4923:                      }
1.39      www      4924: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      4925:                  } else {
                   4926:                      $syval='';
1.37      www      4927:                  }
                   4928: 	      }
                   4929:               untie(%bighash)
1.481     raeburn  4930:            }
1.31      www      4931:         }
1.62      www      4932:         if ($syval) {
1.601     albertel 4933: 	    return $ENV{$cache_str}=$syval;
                   4934: 	    #return $ENV{$cache_str}=&symbclean($syval.'___'.$thisfn);
1.62      www      4935:         }
1.31      www      4936:     }
1.44      www      4937:     &appenv('request.ambiguous' => $thisfn);
1.542     albertel 4938:     return $ENV{$cache_str}='';
1.31      www      4939: }
                   4940: 
                   4941: # ---------------------------------------------------------- Return random seed
                   4942: 
1.32      www      4943: sub numval {
                   4944:     my $txt=shift;
                   4945:     $txt=~tr/A-J/0-9/;
                   4946:     $txt=~tr/a-j/0-9/;
                   4947:     $txt=~tr/K-T/0-9/;
                   4948:     $txt=~tr/k-t/0-9/;
                   4949:     $txt=~tr/U-Z/0-5/;
                   4950:     $txt=~tr/u-z/0-5/;
                   4951:     $txt=~s/\D//g;
1.564     albertel 4952:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      4953:     return int($txt);
1.368     albertel 4954: }
                   4955: 
1.484     albertel 4956: sub numval2 {
                   4957:     my $txt=shift;
                   4958:     $txt=~tr/A-J/0-9/;
                   4959:     $txt=~tr/a-j/0-9/;
                   4960:     $txt=~tr/K-T/0-9/;
                   4961:     $txt=~tr/k-t/0-9/;
                   4962:     $txt=~tr/U-Z/0-5/;
                   4963:     $txt=~tr/u-z/0-5/;
                   4964:     $txt=~s/\D//g;
                   4965:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   4966:     my $total;
                   4967:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 4968:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 4969:     return int($total);
                   4970: }
                   4971: 
1.575     albertel 4972: sub numval3 {
                   4973:     use integer;
                   4974:     my $txt=shift;
                   4975:     $txt=~tr/A-J/0-9/;
                   4976:     $txt=~tr/a-j/0-9/;
                   4977:     $txt=~tr/K-T/0-9/;
                   4978:     $txt=~tr/k-t/0-9/;
                   4979:     $txt=~tr/U-Z/0-5/;
                   4980:     $txt=~tr/u-z/0-5/;
                   4981:     $txt=~s/\D//g;
                   4982:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   4983:     my $total;
                   4984:     foreach my $val (@txts) { $total+=$val; }
                   4985:     if ($_64bit) { $total=(($total<<32)>>32); }
                   4986:     return $total;
                   4987: }
                   4988: 
1.368     albertel 4989: sub latest_rnd_algorithm_id {
1.575     albertel 4990:     return '64bit4';
1.366     albertel 4991: }
1.32      www      4992: 
1.503     albertel 4993: sub get_rand_alg {
                   4994:     my ($courseid)=@_;
                   4995:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   4996:     if ($courseid) {
                   4997: 	return $ENV{"course.$courseid.rndseed"};
                   4998:     }
                   4999:     return &latest_rnd_algorithm_id();
                   5000: }
                   5001: 
1.562     albertel 5002: sub validCODE {
                   5003:     my ($CODE)=@_;
                   5004:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5005:     return 0;
                   5006: }
                   5007: 
1.491     albertel 5008: sub getCODE {
1.562     albertel 5009:     if (&validCODE($ENV{'form.CODE'})) { return $ENV{'form.CODE'}; }
1.491     albertel 5010:     if (defined($Apache::lonhomework::parsing_a_problem) &&
1.562     albertel 5011: 	&validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5012: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5013:     }
                   5014:     return undef;
                   5015: }
                   5016: 
1.31      www      5017: sub rndseed {
1.155     albertel 5018:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5019: 
                   5020:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5021:     if (!$symb) {
1.366     albertel 5022: 	unless ($symb=$wsymb) { return time; }
                   5023:     }
                   5024:     if (!$courseid) { $courseid=$wcourseid; }
                   5025:     if (!$domain) { $domain=$wdomain; }
                   5026:     if (!$username) { $username=$wusername }
1.503     albertel 5027:     my $which=&get_rand_alg();
1.491     albertel 5028:     if (defined(&getCODE())) {
1.575     albertel 5029: 	if ($which eq '64bit4') {
                   5030: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5031: 	} else {
                   5032: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5033: 	}
                   5034:     } elsif ($which eq '64bit4') {
                   5035: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5036:     } elsif ($which eq '64bit3') {
                   5037: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5038:     } elsif ($which eq '64bit2') {
                   5039: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5040:     } elsif ($which eq '64bit') {
                   5041: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5042:     }
                   5043:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5044: }
                   5045: 
                   5046: sub rndseed_32bit {
                   5047:     my ($symb,$courseid,$domain,$username)=@_;
                   5048:     {
                   5049: 	use integer;
                   5050: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5051: 	my $symbseed=numval($symb) << 22;
                   5052: 	my $namechck=unpack("%32C*",$username) << 17;
                   5053: 	my $nameseed=numval($username) << 12;
                   5054: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5055: 	my $courseseed=unpack("%32C*",$courseid);
                   5056: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5057: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5058: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5059: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5060: 	return $num;
                   5061:     }
                   5062: }
                   5063: 
                   5064: sub rndseed_64bit {
                   5065:     my ($symb,$courseid,$domain,$username)=@_;
                   5066:     {
                   5067: 	use integer;
                   5068: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5069: 	my $symbseed=numval($symb) << 10;
                   5070: 	my $namechck=unpack("%32S*",$username);
                   5071: 	
                   5072: 	my $nameseed=numval($username) << 21;
                   5073: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5074: 	my $courseseed=unpack("%32S*",$courseid);
                   5075: 	
                   5076: 	my $num1=$symbchck+$symbseed+$namechck;
                   5077: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5078: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5079: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5080: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5081: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5082: 	return "$num1,$num2";
1.155     albertel 5083:     }
1.366     albertel 5084: }
                   5085: 
1.443     albertel 5086: sub rndseed_64bit2 {
                   5087:     my ($symb,$courseid,$domain,$username)=@_;
                   5088:     {
                   5089: 	use integer;
                   5090: 	# strings need to be an even # of cahracters long, it it is odd the
                   5091:         # last characters gets thrown away
                   5092: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5093: 	my $symbseed=numval($symb) << 10;
                   5094: 	my $namechck=unpack("%32S*",$username.' ');
                   5095: 	
                   5096: 	my $nameseed=numval($username) << 21;
1.501     albertel 5097: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5098: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5099: 	
                   5100: 	my $num1=$symbchck+$symbseed+$namechck;
                   5101: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5102: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5103: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   5104: 	return "$num1,$num2";
                   5105:     }
                   5106: }
                   5107: 
                   5108: sub rndseed_64bit3 {
                   5109:     my ($symb,$courseid,$domain,$username)=@_;
                   5110:     {
                   5111: 	use integer;
                   5112: 	# strings need to be an even # of cahracters long, it it is odd the
                   5113:         # last characters gets thrown away
                   5114: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5115: 	my $symbseed=numval2($symb) << 10;
                   5116: 	my $namechck=unpack("%32S*",$username.' ');
                   5117: 	
                   5118: 	my $nameseed=numval2($username) << 21;
1.443     albertel 5119: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5120: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5121: 	
                   5122: 	my $num1=$symbchck+$symbseed+$namechck;
                   5123: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5124: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 5125: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5126: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5127: 	
1.503     albertel 5128: 	return "$num1:$num2";
1.443     albertel 5129:     }
                   5130: }
                   5131: 
1.575     albertel 5132: sub rndseed_64bit4 {
                   5133:     my ($symb,$courseid,$domain,$username)=@_;
                   5134:     {
                   5135: 	use integer;
                   5136: 	# strings need to be an even # of cahracters long, it it is odd the
                   5137:         # last characters gets thrown away
                   5138: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5139: 	my $symbseed=numval3($symb) << 10;
                   5140: 	my $namechck=unpack("%32S*",$username.' ');
                   5141: 	
                   5142: 	my $nameseed=numval3($username) << 21;
                   5143: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5144: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5145: 	
                   5146: 	my $num1=$symbchck+$symbseed+$namechck;
                   5147: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5148: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5149: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5150: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5151: 	
                   5152: 	return "$num1:$num2";
                   5153:     }
                   5154: }
                   5155: 
1.366     albertel 5156: sub rndseed_CODE_64bit {
                   5157:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 5158:     {
1.366     albertel 5159: 	use integer;
1.443     albertel 5160: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 5161: 	my $symbseed=numval2($symb);
1.491     albertel 5162: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5163: 	my $CODEseed=numval(&getCODE());
1.443     albertel 5164: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 5165: 	my $num1=$symbseed+$CODEchck;
                   5166: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5167: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 5168: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 5169: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5170: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 5171: 	return "$num1:$num2";
1.366     albertel 5172:     }
                   5173: }
                   5174: 
1.575     albertel 5175: sub rndseed_CODE_64bit4 {
                   5176:     my ($symb,$courseid,$domain,$username)=@_;
                   5177:     {
                   5178: 	use integer;
                   5179: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   5180: 	my $symbseed=numval3($symb);
                   5181: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5182: 	my $CODEseed=numval3(&getCODE());
                   5183: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5184: 	my $num1=$symbseed+$CODEchck;
                   5185: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5186: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   5187: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   5188: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5189: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   5190: 	return "$num1:$num2";
                   5191:     }
                   5192: }
                   5193: 
1.366     albertel 5194: sub setup_random_from_rndseed {
                   5195:     my ($rndseed)=@_;
1.503     albertel 5196:     if ($rndseed =~/([,:])/) {
                   5197: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 5198: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   5199:     } else {
                   5200: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 5201:     }
1.36      albertel 5202: }
                   5203: 
1.474     albertel 5204: sub latest_receipt_algorithm_id {
                   5205:     return 'receipt2';
                   5206: }
                   5207: 
1.480     www      5208: sub recunique {
                   5209:     my $fucourseid=shift;
                   5210:     my $unique;
                   5211:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5212: 	$unique=$ENV{"course.$fucourseid.internal.encseed"};
                   5213:     } else {
                   5214: 	$unique=$perlvar{'lonReceipt'};
                   5215:     }
                   5216:     return unpack("%32C*",$unique);
                   5217: }
                   5218: 
                   5219: sub recprefix {
                   5220:     my $fucourseid=shift;
                   5221:     my $prefix;
                   5222:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5223: 	$prefix=$ENV{"course.$fucourseid.internal.encpref"};
                   5224:     } else {
                   5225: 	$prefix=$perlvar{'lonHostID'};
                   5226:     }
                   5227:     return unpack("%32C*",$prefix);
                   5228: }
                   5229: 
1.76      www      5230: sub ireceipt {
1.474     albertel 5231:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      5232:     my $cuname=unpack("%32C*",$funame);
                   5233:     my $cudom=unpack("%32C*",$fudom);
                   5234:     my $cucourseid=unpack("%32C*",$fucourseid);
                   5235:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      5236:     my $cunique=&recunique($fucourseid);
1.474     albertel 5237:     my $cpart=unpack("%32S*",$part);
1.480     www      5238:     my $return =&recprefix($fucourseid).'-';
1.474     albertel 5239:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   5240: 	$ENV{'request.state'} eq 'construct') {
                   5241: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   5242: 			       " and ".($cpart%$cudom));
                   5243: 			       
                   5244: 	$return.= ($cunique%$cuname+
                   5245: 		   $cunique%$cudom+
                   5246: 		   $cusymb%$cuname+
                   5247: 		   $cusymb%$cudom+
                   5248: 		   $cucourseid%$cuname+
                   5249: 		   $cucourseid%$cudom+
                   5250: 		   $cpart%$cuname+
                   5251: 		   $cpart%$cudom);
                   5252:     } else {
                   5253: 	$return.= ($cunique%$cuname+
                   5254: 		   $cunique%$cudom+
                   5255: 		   $cusymb%$cuname+
                   5256: 		   $cusymb%$cudom+
                   5257: 		   $cucourseid%$cuname+
                   5258: 		   $cucourseid%$cudom);
                   5259:     }
                   5260:     return $return;
1.76      www      5261: }
                   5262: 
                   5263: sub receipt {
1.474     albertel 5264:     my ($part)=@_;
                   5265:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   5266:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      5267: }
1.260     ng       5268: 
1.36      albertel 5269: # ------------------------------------------------------------ Serves up a file
1.472     albertel 5270: # returns either the contents of the file or 
                   5271: # -1 if the file doesn't exist
1.481     raeburn  5272: #
                   5273: # if the target is a file that was uploaded via DOCS, 
                   5274: # a check will be made to see if a current copy exists on the local server,
                   5275: # if it does this will be served, otherwise a copy will be retrieved from
                   5276: # the home server for the course and stored in /home/httpd/html/userfiles on
                   5277: # the local server.   
1.472     albertel 5278: 
1.36      albertel 5279: sub getfile {
1.538     albertel 5280:     my ($file) = @_;
1.609     banghart 5281:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 5282:     &repcopy($file);
                   5283:     return &readfile($file);
                   5284: }
                   5285: 
                   5286: sub repcopy_userfile {
                   5287:     my ($file)=@_;
1.609     banghart 5288:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 5289:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 5290:     my ($cdom,$cnum,$filename) = 
                   5291: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   5292:     my ($info,$rtncode);
                   5293:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   5294:     if (-e "$file") {
                   5295: 	my @fileinfo = stat($file);
                   5296: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5297: 	if ($lwpresp ne 'ok') {
                   5298: 	    if ($rtncode eq '404') {
1.538     albertel 5299: 		unlink($file);
1.482     albertel 5300: 	    }
1.517     albertel 5301: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 5302: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5303: 	    #my $response=$ua->request($request);
                   5304: 	    #if ($response->is_success()) {
                   5305: 	#	return $response->content;
                   5306: 	#    } else {
                   5307: 	#	return -1;
                   5308: 	#    }
1.482     albertel 5309: 	    return -1;
                   5310: 	}
                   5311: 	if ($info < $fileinfo[9]) {
1.607     raeburn  5312: 	    return 'ok';
1.482     albertel 5313: 	}
                   5314: 	$info = '';
1.538     albertel 5315: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5316: 	if ($lwpresp ne 'ok') {
                   5317: 	    return -1;
                   5318: 	}
                   5319:     } else {
1.538     albertel 5320: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5321: 	if ($lwpresp ne 'ok') {
1.517     albertel 5322: 	    my $ua=new LWP::UserAgent;
1.538     albertel 5323: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5324: 	    my $response=$ua->request($request);
                   5325: 	    if ($response->is_success()) {
1.538     albertel 5326: 		$info=$response->content;
1.517     albertel 5327: 	    } else {
                   5328: 		return -1;
                   5329: 	    }
1.482     albertel 5330: 	}
                   5331: 	my @parts = ($cdom,$cnum); 
                   5332: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   5333: 	    push @parts, split(/\//,$1);
1.518     albertel 5334: 	}
1.538     albertel 5335: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 5336: 	foreach my $part (@parts) {
                   5337: 	    $path .= '/'.$part;
                   5338: 	    if (!-e $path) {
                   5339: 		mkdir($path,0770);
                   5340: 	    }
                   5341: 	}
                   5342:     }
1.538     albertel 5343:     open(FILE,">$file");
1.482     albertel 5344:     print FILE $info;
                   5345:     close(FILE);
1.607     raeburn  5346:     return 'ok';
1.481     raeburn  5347: }
                   5348: 
1.517     albertel 5349: sub tokenwrapper {
                   5350:     my $uri=shift;
1.552     albertel 5351:     $uri=~s|^http\://([^/]+)||;
                   5352:     $uri=~s|^/||;
1.517     albertel 5353:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
                   5354:     my $token=$1;
1.552     albertel 5355:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   5356:     if ($udom && $uname && $file) {
                   5357: 	$file=~s|(\?\.*)*$||;
                   5358:         &appenv("userfile.$udom/$uname/$file" => $ENV{'request.course.id'});
                   5359:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 5360:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   5361:                                '&tokenissued='.$perlvar{'lonHostID'};
                   5362:     } else {
                   5363:         return '/adm/notfound.html';
                   5364:     }
                   5365: }
                   5366: 
1.481     raeburn  5367: sub getuploaded {
                   5368:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   5369:     $uri=~s/^\///;
                   5370:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   5371:     my $ua=new LWP::UserAgent;
                   5372:     my $request=new HTTP::Request($reqtype,$uri);
                   5373:     my $response=$ua->request($request);
                   5374:     $$rtncode = $response->code;
1.482     albertel 5375:     if (! $response->is_success()) {
                   5376: 	return 'failed';
                   5377:     }      
                   5378:     if ($reqtype eq 'HEAD') {
1.486     www      5379: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 5380:     } elsif ($reqtype eq 'GET') {
                   5381: 	$$info = $response->content;
1.472     albertel 5382:     }
1.482     albertel 5383:     return 'ok';
1.36      albertel 5384: }
                   5385: 
1.481     raeburn  5386: sub readfile {
                   5387:     my $file = shift;
                   5388:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   5389:     my $fh;
                   5390:     open($fh,"<$file");
                   5391:     my $a='';
                   5392:     while (<$fh>) { $a .=$_; }
                   5393:     return $a;
                   5394: }
                   5395: 
1.36      albertel 5396: sub filelocation {
1.590     banghart 5397:     my ($dir,$file) = @_;
                   5398:     my $location;
                   5399:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
                   5400:     if ($file=~m:^/~:) { # is a contruction space reference
                   5401:         $location = $file;
                   5402:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.609     banghart 5403:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 5404:         my ($udom,$uname,$filename)=
1.609     banghart 5405:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 5406:         my $home=&homeserver($uname,$udom);
                   5407:         my $is_me=0;
                   5408:         my @ids=&current_machine_ids();
                   5409:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   5410:         if ($is_me) {
                   5411:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   5412:   	      '/userfiles/'.$filename;
                   5413:         } else {
                   5414:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   5415:   	      $udom.'/'.$uname.'/'.$filename;
                   5416:         }
                   5417:     } else {
                   5418:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   5419:         $file=~s:^/res/:/:;
                   5420:         if ( !( $file =~ m:^/:) ) {
                   5421:             $location = $dir. '/'.$file;
                   5422:         } else {
                   5423:             $location = '/home/httpd/html/res'.$file;
                   5424:         }
1.59      albertel 5425:     }
1.590     banghart 5426:     $location=~s://+:/:g; # remove duplicate /
                   5427:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   5428:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   5429:     return $location;
1.46      www      5430: }
1.36      albertel 5431: 
1.46      www      5432: sub hreflocation {
                   5433:     my ($dir,$file)=@_;
1.460     albertel 5434:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
                   5435: 	my $finalpath=filelocation($dir,$file);
                   5436: 	$finalpath=~s-^/home/httpd/html--;
1.462     albertel 5437: 	$finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5438: 	return $finalpath;
                   5439:     } elsif ($file=~m-^/home-) {
                   5440: 	$file=~s-^/home/httpd/html--;
1.462     albertel 5441: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5442: 	return $file;
1.46      www      5443:     }
1.462     albertel 5444:     return $file;
1.465     albertel 5445: }
                   5446: 
                   5447: sub current_machine_domains {
                   5448:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5449:     my @domains;
                   5450:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5451: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5452: 	if ($hostname eq $name) {
                   5453: 	    push(@domains,$hostdom{$id});
                   5454: 	}
                   5455:     }
                   5456:     return @domains;
                   5457: }
                   5458: 
                   5459: sub current_machine_ids {
                   5460:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5461:     my @ids;
                   5462:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5463: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5464: 	if ($hostname eq $name) {
                   5465: 	    push(@ids,$id);
                   5466: 	}
                   5467:     }
                   5468:     return @ids;
1.31      www      5469: }
                   5470: 
                   5471: # ------------------------------------------------------------- Declutters URLs
                   5472: 
                   5473: sub declutter {
                   5474:     my $thisfn=shift;
1.569     albertel 5475:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 5476:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      5477:     $thisfn=~s/^\///;
                   5478:     $thisfn=~s/^res\///;
1.235     www      5479:     $thisfn=~s/\?.+$//;
1.268     www      5480:     return $thisfn;
                   5481: }
                   5482: 
                   5483: # ------------------------------------------------------------- Clutter up URLs
                   5484: 
                   5485: sub clutter {
                   5486:     my $thisfn='/'.&declutter(shift);
1.609     banghart 5487:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      5488:        $thisfn='/res'.$thisfn; 
                   5489:     }
1.31      www      5490:     return $thisfn;
1.12      www      5491: }
                   5492: 
1.557     albertel 5493: sub freeze_escape {
                   5494:     my ($value)=@_;
                   5495:     if (ref($value)) {
                   5496: 	$value=&nfreeze($value);
                   5497: 	return '__FROZEN__'.&escape($value);
                   5498:     }
                   5499:     return &escape($value);
                   5500: }
                   5501: 
1.12      www      5502: # -------------------------------------------------------- Escape Special Chars
                   5503: 
                   5504: sub escape {
                   5505:     my $str=shift;
                   5506:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   5507:     return $str;
                   5508: }
                   5509: 
                   5510: # ----------------------------------------------------- Un-Escape Special Chars
                   5511: 
                   5512: sub unescape {
                   5513:     my $str=shift;
                   5514:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   5515:     return $str;
                   5516: }
1.11      www      5517: 
1.557     albertel 5518: sub thaw_unescape {
                   5519:     my ($value)=@_;
                   5520:     if ($value =~ /^__FROZEN__/) {
                   5521: 	substr($value,0,10,undef);
                   5522: 	$value=&unescape($value);
                   5523: 	return &thaw($value);
                   5524:     }
                   5525:     return &unescape($value);
                   5526: }
                   5527: 
1.415     albertel 5528: sub mod_perl_version {
1.580     albertel 5529:     return 1;
1.415     albertel 5530:     if (defined($perlvar{'MODPERL2'})) {
                   5531: 	return 2;
                   5532:     }
1.436     albertel 5533: }
                   5534: 
                   5535: sub correct_line_ends {
                   5536:     my ($result)=@_;
                   5537:     $$result =~s/\r\n/\n/mg;
                   5538:     $$result =~s/\r/\n/mg;
1.415     albertel 5539: }
1.1       albertel 5540: # ================================================================ Main Program
                   5541: 
1.184     www      5542: sub goodbye {
1.204     albertel 5543:    &logthis("Starting Shut down");
1.443     albertel 5544: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 5545:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 5546: #converted
1.599     albertel 5547: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   5548:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   5549: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   5550: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 5551: #1.1 only
1.599     albertel 5552: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   5553: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   5554: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   5555: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   5556:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   5557:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   5558:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      5559:    &flushcourselogs();
                   5560:    &logthis("Shutting down");
1.362     albertel 5561:    return DONE;
1.184     www      5562: }
                   5563: 
1.179     www      5564: BEGIN {
1.228     harris41 5565: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      5566:     unless ($readit) {
1.217     harris41 5567: {
1.581     matthew  5568:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 5569:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 5570: 
                   5571:     while (my $configline=<$config>) {
1.484     albertel 5572:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 5573: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      5574:            chomp($varvalue);
1.1       albertel 5575:            $perlvar{$varname}=$varvalue;
                   5576:         }
                   5577:     }
1.448     albertel 5578:     close($config);
1.1       albertel 5579: }
1.227     harris41 5580: {
1.448     albertel 5581:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 5582: 
                   5583:     while (my $configline=<$config>) {
                   5584:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   5585: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   5586:            chomp($varvalue);
                   5587:            $perlvar{$varname}=$varvalue;
                   5588:         }
                   5589:     }
1.448     albertel 5590:     close($config);
1.227     harris41 5591: }
1.1       albertel 5592: 
1.327     albertel 5593: # ------------------------------------------------------------ Read domain file
                   5594: {
                   5595:     %domaindescription = ();
                   5596:     %domain_auth_def = ();
                   5597:     %domain_auth_arg_def = ();
1.448     albertel 5598:     my $fh;
                   5599:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 5600:        while (<$fh>) {
1.390     matthew  5601:            next if (/^(\#|\s*$)/);
                   5602: #           next if /^\#/;
1.327     albertel 5603:            chomp;
1.403     www      5604:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   5605: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   5606: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 5607:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      5608: 	   $domaindescription{$domain}=$domain_description;
                   5609: 	   $domain_lang_def{$domain}=$def_lang;
                   5610: 	   $domain_city{$domain}=$city;
                   5611: 	   $domain_longi{$domain}=$longi;
                   5612: 	   $domain_lati{$domain}=$lati;
                   5613: 
1.448     albertel 5614:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 5615: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 5616: 	}
1.327     albertel 5617:     }
1.448     albertel 5618:     close ($fh);
1.327     albertel 5619: }
                   5620: 
                   5621: 
1.1       albertel 5622: # ------------------------------------------------------------- Read hosts file
                   5623: {
1.448     albertel 5624:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 5625: 
                   5626:     while (my $configline=<$config>) {
1.303     matthew  5627:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      5628:        chomp($configline);
1.595     albertel 5629:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 5630:        $name=~s/\s//g;
1.595     albertel 5631:        if ($id && $domain && $role && $name) {
1.252     albertel 5632: 	 $hostname{$id}=$name;
                   5633: 	 $hostdom{$id}=$domain;
                   5634: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      5635:        }
1.1       albertel 5636:     }
1.448     albertel 5637:     close($config);
1.1       albertel 5638: }
                   5639: 
1.598     albertel 5640: sub get_iphost {
                   5641:     if (%iphost) { return %iphost; }
                   5642:     foreach my $id (keys(%hostname)) {
                   5643: 	my $name=$hostname{$id};
                   5644: 	my $ip = gethostbyname($name);
                   5645: 	if (!$ip || length($ip) ne 4) {
                   5646: 	    &logthis("Skipping host $id name $name no IP found\n");
                   5647: 	    next;
                   5648: 	}
                   5649: 	$ip=inet_ntoa($ip);
                   5650: 	push(@{$iphost{$ip}},$id);
                   5651:     }
                   5652:     return %iphost;
                   5653: }
                   5654: 
1.1       albertel 5655: # ------------------------------------------------------ Read spare server file
                   5656: {
1.448     albertel 5657:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 5658: 
                   5659:     while (my $configline=<$config>) {
                   5660:        chomp($configline);
1.284     matthew  5661:        if ($configline) {
1.1       albertel 5662:           $spareid{$configline}=1;
                   5663:        }
                   5664:     }
1.448     albertel 5665:     close($config);
1.1       albertel 5666: }
1.11      www      5667: # ------------------------------------------------------------ Read permissions
                   5668: {
1.448     albertel 5669:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      5670: 
                   5671:     while (my $configline=<$config>) {
1.448     albertel 5672: 	chomp($configline);
                   5673: 	if ($configline) {
                   5674: 	    my ($role,$perm)=split(/ /,$configline);
                   5675: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   5676: 	}
1.11      www      5677:     }
1.448     albertel 5678:     close($config);
1.11      www      5679: }
                   5680: 
                   5681: # -------------------------------------------- Read plain texts for permissions
                   5682: {
1.448     albertel 5683:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      5684: 
                   5685:     while (my $configline=<$config>) {
1.448     albertel 5686: 	chomp($configline);
                   5687: 	if ($configline) {
                   5688: 	    my ($short,$plain)=split(/:/,$configline);
                   5689: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   5690: 	}
1.135     www      5691:     }
1.448     albertel 5692:     close($config);
1.135     www      5693: }
                   5694: 
                   5695: # ---------------------------------------------------------- Read package table
                   5696: {
1.448     albertel 5697:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      5698: 
                   5699:     while (my $configline=<$config>) {
1.483     albertel 5700: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 5701: 	chomp($configline);
                   5702: 	my ($short,$plain)=split(/:/,$configline);
                   5703: 	my ($pack,$name)=split(/\&/,$short);
                   5704: 	if ($plain ne '') {
                   5705: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   5706: 	    $packagetab{$short}=$plain; 
                   5707: 	}
1.11      www      5708:     }
1.448     albertel 5709:     close($config);
1.329     matthew  5710: }
                   5711: 
                   5712: # ------------- set up temporary directory
                   5713: {
                   5714:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   5715: 
1.11      www      5716: }
                   5717: 
1.599     albertel 5718: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      5719: 
1.281     www      5720: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      5721: $dumpcount=0;
1.22      www      5722: 
1.163     harris41 5723: &logtouch();
1.12      www      5724: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      5725: $readit=1;
1.564     albertel 5726:     {
                   5727: 	use integer;
                   5728: 	my $test=(2**32)+1;
1.568     albertel 5729: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 5730: 	&logthis(" Detected 64bit platform ($_64bit)");
                   5731:     }
1.195     www      5732: }
1.1       albertel 5733: }
1.179     www      5734: 
1.1       albertel 5735: 1;
1.191     harris41 5736: __END__
                   5737: 
1.243     albertel 5738: =pod
                   5739: 
1.191     harris41 5740: =head1 NAME
                   5741: 
1.243     albertel 5742: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 5743: 
                   5744: =head1 SYNOPSIS
                   5745: 
1.243     albertel 5746: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 5747: 
                   5748:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   5749: 
1.243     albertel 5750: Common parameters:
                   5751: 
                   5752: =over 4
                   5753: 
                   5754: =item *
                   5755: 
                   5756: $uname : an internal username (if $cname expecting a course Id specifically)
                   5757: 
                   5758: =item *
                   5759: 
                   5760: $udom : a domain (if $cdom expecting a course's domain specifically)
                   5761: 
                   5762: =item *
                   5763: 
                   5764: $symb : a resource instance identifier
                   5765: 
                   5766: =item *
                   5767: 
                   5768: $namespace : the name of a .db file that contains the data needed or
                   5769: being set.
                   5770: 
                   5771: =back
                   5772: 
1.394     bowersj2 5773: =head1 OVERVIEW
1.191     harris41 5774: 
1.394     bowersj2 5775: lonnet provides subroutines which interact with the
                   5776: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   5777: about classes, users, and resources.
1.243     albertel 5778: 
                   5779: For many of these objects you can also use this to store data about
                   5780: them or modify them in various ways.
1.191     harris41 5781: 
1.394     bowersj2 5782: =head2 Symbs
1.191     harris41 5783: 
1.394     bowersj2 5784: To identify a specific instance of a resource, LON-CAPA uses symbols
                   5785: or "symbs"X<symb>. These identifiers are built from the URL of the
                   5786: map, the resource number of the resource in the map, and the URL of
                   5787: the resource itself. The latter is somewhat redundant, but might help
                   5788: if maps change.
                   5789: 
                   5790: An example is
                   5791: 
                   5792:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   5793: 
                   5794: The respective map entry is
                   5795: 
                   5796:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   5797:   title="Problem 2">
                   5798:  </resource>
                   5799: 
                   5800: Symbs are used by the random number generator, as well as to store and
                   5801: restore data specific to a certain instance of for example a problem.
                   5802: 
                   5803: =head2 Storing And Retrieving Data
                   5804: 
                   5805: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   5806: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   5807: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   5808: is is the non-critical message twin of cstore. These functions are for
                   5809: handlers to store a perl hash to a user's permanent data space in an
                   5810: easy manner, and to retrieve it again on another call. It is expected
                   5811: that a handler would use this once at the beginning to retrieve data,
                   5812: and then again once at the end to send only the new data back.
                   5813: 
                   5814: The data is stored in the user's data directory on the user's
                   5815: homeserver under the ID of the course.
                   5816: 
                   5817: The hash that is returned by restore will have all of the previous
                   5818: value for all of the elements of the hash.
                   5819: 
                   5820: Example:
                   5821: 
                   5822:  #creating a hash
                   5823:  my %hash;
                   5824:  $hash{'foo'}='bar';
                   5825: 
                   5826:  #storing it
                   5827:  &Apache::lonnet::cstore(\%hash);
                   5828: 
                   5829:  #changing a value
                   5830:  $hash{'foo'}='notbar';
                   5831: 
                   5832:  #adding a new value
                   5833:  $hash{'bar'}='foo';
                   5834:  &Apache::lonnet::cstore(\%hash);
                   5835: 
                   5836:  #retrieving the hash
                   5837:  my %history=&Apache::lonnet::restore();
                   5838: 
                   5839:  #print the hash
                   5840:  foreach my $key (sort(keys(%history))) {
                   5841:    print("\%history{$key} = $history{$key}");
                   5842:  }
                   5843: 
                   5844: Will print out:
1.191     harris41 5845: 
1.394     bowersj2 5846:  %history{1:foo} = bar
                   5847:  %history{1:keys} = foo:timestamp
                   5848:  %history{1:timestamp} = 990455579
                   5849:  %history{2:bar} = foo
                   5850:  %history{2:foo} = notbar
                   5851:  %history{2:keys} = foo:bar:timestamp
                   5852:  %history{2:timestamp} = 990455580
                   5853:  %history{bar} = foo
                   5854:  %history{foo} = notbar
                   5855:  %history{timestamp} = 990455580
                   5856:  %history{version} = 2
                   5857: 
                   5858: Note that the special hash entries C<keys>, C<version> and
                   5859: C<timestamp> were added to the hash. C<version> will be equal to the
                   5860: total number of versions of the data that have been stored. The
                   5861: C<timestamp> attribute will be the UNIX time the hash was
                   5862: stored. C<keys> is available in every historical section to list which
                   5863: keys were added or changed at a specific historical revision of a
                   5864: hash.
                   5865: 
                   5866: B<Warning>: do not store the hash that restore returns directly. This
                   5867: will cause a mess since it will restore the historical keys as if the
                   5868: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 5869: 
1.394     bowersj2 5870: Calling convention:
1.191     harris41 5871: 
1.394     bowersj2 5872:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   5873:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 5874: 
1.394     bowersj2 5875: For more detailed information, see lonnet specific documentation.
1.191     harris41 5876: 
1.394     bowersj2 5877: =head1 RETURN MESSAGES
1.191     harris41 5878: 
1.394     bowersj2 5879: =over 4
1.191     harris41 5880: 
1.394     bowersj2 5881: =item * B<con_lost>: unable to contact remote host
1.191     harris41 5882: 
1.394     bowersj2 5883: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   5884: when the connection is brought back up
1.191     harris41 5885: 
1.394     bowersj2 5886: =item * B<con_failed>: unable to contact remote host and unable to save message
                   5887: for later delivery
1.191     harris41 5888: 
1.394     bowersj2 5889: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 5890: 
1.394     bowersj2 5891: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 5892: that was requested
1.191     harris41 5893: 
1.243     albertel 5894: =back
1.191     harris41 5895: 
1.243     albertel 5896: =head1 PUBLIC SUBROUTINES
1.191     harris41 5897: 
1.243     albertel 5898: =head2 Session Environment Functions
1.191     harris41 5899: 
1.243     albertel 5900: =over 4
1.191     harris41 5901: 
1.394     bowersj2 5902: =item * 
                   5903: X<appenv()>
                   5904: B<appenv(%hash)>: the value of %hash is written to
                   5905: the user envirnoment file, and will be restored for each access this
                   5906: user makes during this session, also modifies the %ENV for the current
                   5907: process
1.191     harris41 5908: 
                   5909: =item *
1.394     bowersj2 5910: X<delenv()>
                   5911: B<delenv($regexp)>: removes all items from the session
                   5912: environment file that matches the regular expression in $regexp. The
                   5913: values are also delted from the current processes %ENV.
1.191     harris41 5914: 
1.243     albertel 5915: =back
                   5916: 
                   5917: =head2 User Information
1.191     harris41 5918: 
1.243     albertel 5919: =over 4
1.191     harris41 5920: 
                   5921: =item *
1.394     bowersj2 5922: X<queryauthenticate()>
                   5923: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 5924: authentication scheme
                   5925: 
                   5926: =item *
1.394     bowersj2 5927: X<authenticate()>
                   5928: B<authenticate($uname,$upass,$udom)>: try to
                   5929: authenticate user from domain's lib servers (first use the current
                   5930: one). C<$upass> should be the users password.
1.191     harris41 5931: 
                   5932: =item *
1.394     bowersj2 5933: X<homeserver()>
                   5934: B<homeserver($uname,$udom)>: find the server which has
                   5935: the user's directory and files (there must be only one), this caches
                   5936: the answer, and also caches if there is a borken connection.
1.191     harris41 5937: 
                   5938: =item *
1.394     bowersj2 5939: X<idget()>
                   5940: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   5941: (IDs are a unique resource in a domain, there must be only 1 ID per
                   5942: username, and only 1 username per ID in a specific domain) (returns
                   5943: hash: id=>name,id=>name)
1.191     harris41 5944: 
                   5945: =item *
1.394     bowersj2 5946: X<idrget()>
                   5947: B<idrget($udom,@unames)>: find the IDs behind a list of
                   5948: usernames (returns hash: name=>id,name=>id)
1.191     harris41 5949: 
                   5950: =item *
1.394     bowersj2 5951: X<idput()>
                   5952: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 5953: 
                   5954: =item *
1.394     bowersj2 5955: X<rolesinit()>
                   5956: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 5957: 
                   5958: =item *
1.551     albertel 5959: X<getsection()>
                   5960: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 5961: course $cname, return section name/number or '' for "not in course"
                   5962: and '-1' for "no section"
                   5963: 
                   5964: =item *
1.394     bowersj2 5965: X<userenvironment()>
                   5966: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 5967: passed in @what from the requested user's environment, returns a hash
                   5968: 
                   5969: =back
                   5970: 
                   5971: =head2 User Roles
                   5972: 
                   5973: =over 4
                   5974: 
                   5975: =item *
                   5976: 
                   5977: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   5978: actions
                   5979:  F: full access
                   5980:  U,I,K: authentication modes (cxx only)
                   5981:  '': forbidden
                   5982:  1: user needs to choose course
                   5983:  2: browse allowed
                   5984: 
                   5985: =item *
                   5986: 
                   5987: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   5988: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   5989: and course level
                   5990: 
                   5991: =item *
                   5992: 
                   5993: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   5994: explanation of a user role term
                   5995: 
                   5996: =back
                   5997: 
                   5998: =head2 User Modification
                   5999: 
                   6000: =over 4
                   6001: 
                   6002: =item *
                   6003: 
                   6004: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6005: user for the level given by URL.  Optional start and end dates (leave empty
                   6006: string or zero for "no date")
1.191     harris41 6007: 
                   6008: =item *
                   6009: 
1.243     albertel 6010: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6011: change a users, password, possible return values are: ok,
                   6012: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6013: refused
1.191     harris41 6014: 
                   6015: =item *
                   6016: 
1.243     albertel 6017: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6018: 
                   6019: =item *
                   6020: 
1.243     albertel 6021: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6022: modify user
1.191     harris41 6023: 
                   6024: =item *
                   6025: 
1.286     matthew  6026: modifystudent
                   6027: 
                   6028: modify a students enrollment and identification information.
                   6029: The course id is resolved based on the current users environment.  
                   6030: This means the envoking user must be a course coordinator or otherwise
                   6031: associated with a course.
                   6032: 
1.297     matthew  6033: This call is essentially a wrapper for lonnet::modifyuser and
                   6034: lonnet::modify_student_enrollment
1.286     matthew  6035: 
                   6036: Inputs: 
                   6037: 
                   6038: =over 4
                   6039: 
                   6040: =item B<$udom> Students loncapa domain
                   6041: 
                   6042: =item B<$uname> Students loncapa login name
                   6043: 
                   6044: =item B<$uid> Students id/student number
                   6045: 
                   6046: =item B<$umode> Students authentication mode
                   6047: 
                   6048: =item B<$upass> Students password
                   6049: 
                   6050: =item B<$first> Students first name
                   6051: 
                   6052: =item B<$middle> Students middle name
                   6053: 
                   6054: =item B<$last> Students last name
                   6055: 
                   6056: =item B<$gene> Students generation
                   6057: 
                   6058: =item B<$usec> Students section in course
                   6059: 
                   6060: =item B<$end> Unix time of the roles expiration
                   6061: 
                   6062: =item B<$start> Unix time of the roles start date
                   6063: 
                   6064: =item B<$forceid> If defined, allow $uid to be changed
                   6065: 
                   6066: =item B<$desiredhome> server to use as home server for student
                   6067: 
                   6068: =back
1.297     matthew  6069: 
                   6070: =item *
                   6071: 
                   6072: modify_student_enrollment
                   6073: 
                   6074: Change a students enrollment status in a class.  The environment variable
                   6075: 'role.request.course' must be defined for this function to proceed.
                   6076: 
                   6077: Inputs:
                   6078: 
                   6079: =over 4
                   6080: 
                   6081: =item $udom, students domain
                   6082: 
                   6083: =item $uname, students name
                   6084: 
                   6085: =item $uid, students user id
                   6086: 
                   6087: =item $first, students first name
                   6088: 
                   6089: =item $middle
                   6090: 
                   6091: =item $last
                   6092: 
                   6093: =item $gene
                   6094: 
                   6095: =item $usec
                   6096: 
                   6097: =item $end
                   6098: 
                   6099: =item $start
                   6100: 
                   6101: =back
                   6102: 
1.191     harris41 6103: 
                   6104: =item *
                   6105: 
1.243     albertel 6106: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   6107: custom role; give a custom role to a user for the level given by URL.  Specify
                   6108: name and domain of role author, and role name
1.191     harris41 6109: 
                   6110: =item *
                   6111: 
1.243     albertel 6112: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 6113: 
                   6114: =item *
                   6115: 
1.243     albertel 6116: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   6117: 
                   6118: =back
                   6119: 
                   6120: =head2 Course Infomation
                   6121: 
                   6122: =over 4
1.191     harris41 6123: 
                   6124: =item *
                   6125: 
1.243     albertel 6126: coursedescription($courseid) : course description
1.191     harris41 6127: 
                   6128: =item *
                   6129: 
1.243     albertel 6130: courseresdata($coursenum,$coursedomain,@which) : request for current
                   6131: parameter setting for a specific course, @what should be a list of
                   6132: parameters to ask about. This routine caches answers for 5 minutes.
                   6133: 
                   6134: =back
                   6135: 
                   6136: =head2 Course Modification
                   6137: 
                   6138: =over 4
1.191     harris41 6139: 
                   6140: =item *
                   6141: 
1.243     albertel 6142: writecoursepref($courseid,%prefs) : write preferences (environment
                   6143: database) for a course
1.191     harris41 6144: 
                   6145: =item *
                   6146: 
1.243     albertel 6147: createcourse($udom,$description,$url) : make/modify course
                   6148: 
                   6149: =back
                   6150: 
                   6151: =head2 Resource Subroutines
                   6152: 
                   6153: =over 4
1.191     harris41 6154: 
                   6155: =item *
                   6156: 
1.243     albertel 6157: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 6158: 
                   6159: =item *
                   6160: 
1.243     albertel 6161: repcopy($filename) : subscribes to the requested file, and attempts to
                   6162: replicate from the owning library server, Might return
1.607     raeburn  6163: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   6164: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 6165: resource. Expects the local filesystem pathname
                   6166: (/home/httpd/html/res/....)
                   6167: 
                   6168: =back
                   6169: 
                   6170: =head2 Resource Information
                   6171: 
                   6172: =over 4
1.191     harris41 6173: 
                   6174: =item *
                   6175: 
1.243     albertel 6176: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   6177: a vairety of different possible values, $varname should be a request
                   6178: string, and the other parameters can be used to specify who and what
                   6179: one is asking about.
                   6180: 
                   6181: Possible values for $varname are environment.lastname (or other item
                   6182: from the envirnment hash), user.name (or someother aspect about the
                   6183: user), resource.0.maxtries (or some other part and parameter of a
                   6184: resource)
1.204     albertel 6185: 
                   6186: =item *
                   6187: 
1.243     albertel 6188: directcondval($number) : get current value of a condition; reads from a state
                   6189: string
1.204     albertel 6190: 
                   6191: =item *
                   6192: 
1.243     albertel 6193: condval($condidx) : value of condition index based on state
1.204     albertel 6194: 
                   6195: =item *
                   6196: 
1.243     albertel 6197: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   6198: resource's metadata, $what should be either a specific key, or either
                   6199: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   6200: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   6201: 
                   6202: this function automatically caches all requests
1.191     harris41 6203: 
                   6204: =item *
                   6205: 
1.243     albertel 6206: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   6207: network of library servers; returns file handle of where SQL and regex results
                   6208: will be stored for query
1.191     harris41 6209: 
                   6210: =item *
                   6211: 
1.243     albertel 6212: symbread($filename) : return symbolic list entry (filename argument optional);
                   6213: returns the data handle
1.191     harris41 6214: 
                   6215: =item *
                   6216: 
1.243     albertel 6217: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 6218: a possible symb for the URL in $thisfn, and if is an encryypted
                   6219: resource that the user accessed using /enc/ returns a 1 on success, 0
                   6220: on failure, user must be in a course, as it assumes the existance of
                   6221: the course initial hash, and uses $ENV('request.course.id'}
1.243     albertel 6222: 
1.191     harris41 6223: 
                   6224: =item *
                   6225: 
1.243     albertel 6226: symbclean($symb) : removes versions numbers from a symb, returns the
                   6227: cleaned symb
1.191     harris41 6228: 
                   6229: =item *
                   6230: 
1.243     albertel 6231: is_on_map($uri) : checks if the $uri is somewhere on the current
                   6232: course map, user must be in a course for it to work.
1.191     harris41 6233: 
                   6234: =item *
                   6235: 
1.243     albertel 6236: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 6237: 
                   6238: =item *
                   6239: 
1.243     albertel 6240: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   6241: a random seed, all arguments are optional, if they aren't sent it uses the
                   6242: environment to derive them. Note: if symb isn't sent and it can't get one
                   6243: from &symbread it will use the current time as its return value
1.191     harris41 6244: 
                   6245: =item *
                   6246: 
1.243     albertel 6247: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   6248: unfakeable, receipt
1.191     harris41 6249: 
                   6250: =item *
                   6251: 
1.243     albertel 6252: receipt() : API to ireceipt working off of ENV values; given out to users
1.191     harris41 6253: 
                   6254: =item *
                   6255: 
1.243     albertel 6256: countacc($url) : count the number of accesses to a given URL
1.191     harris41 6257: 
                   6258: =item *
                   6259: 
1.243     albertel 6260: 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 6261: 
                   6262: =item *
                   6263: 
1.243     albertel 6264: 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 6265: 
                   6266: =item *
                   6267: 
1.243     albertel 6268: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 6269: 
                   6270: =item *
                   6271: 
1.243     albertel 6272: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   6273: forcing spreadsheet to reevaluate the resource scores next time.
                   6274: 
                   6275: =back
                   6276: 
                   6277: =head2 Storing/Retreiving Data
                   6278: 
                   6279: =over 4
1.191     harris41 6280: 
                   6281: =item *
                   6282: 
1.243     albertel 6283: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   6284: for this url; hashref needs to be given and should be a \%hashname; the
                   6285: remaining args aren't required and if they aren't passed or are '' they will
                   6286: be derived from the ENV
1.191     harris41 6287: 
                   6288: =item *
                   6289: 
1.243     albertel 6290: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   6291: uses critical subroutine
1.191     harris41 6292: 
                   6293: =item *
                   6294: 
1.243     albertel 6295: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   6296: all args are optional
1.191     harris41 6297: 
                   6298: =item *
                   6299: 
1.243     albertel 6300: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   6301: works very similar to store/cstore, but all data is stored in a
                   6302: temporary location and can be reset using tmpreset, $storehash should
                   6303: be a hash reference, returns nothing on success
1.191     harris41 6304: 
                   6305: =item *
                   6306: 
1.243     albertel 6307: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   6308: similar to restore, but all data is stored in a temporary location and
                   6309: can be reset using tmpreset. Returns a hash of values on success,
                   6310: error string otherwise.
1.191     harris41 6311: 
                   6312: =item *
                   6313: 
1.243     albertel 6314: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   6315: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 6316: 
                   6317: =item *
                   6318: 
1.243     albertel 6319: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6320: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 6321: 
                   6322: =item *
                   6323: 
1.243     albertel 6324: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   6325: namesp ($udom and $uname are optional)
1.191     harris41 6326: 
                   6327: =item *
                   6328: 
1.243     albertel 6329: dump($namespace,$udom,$uname,$regexp) : 
                   6330: dumps the complete (or key matching regexp) namespace into a hash
                   6331: ($udom, $uname and $regexp are optional)
1.449     matthew  6332: 
                   6333: =item *
                   6334: 
                   6335: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   6336: $store can be a scalar, an array reference, or if the amount to be 
                   6337: incremented is > 1, a hash reference.
                   6338: 
                   6339: ($udom and $uname are optional)
1.191     harris41 6340: 
                   6341: =item *
                   6342: 
1.243     albertel 6343: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   6344: ($udom and $uname are optional)
1.191     harris41 6345: 
                   6346: =item *
                   6347: 
1.524     raeburn  6348: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   6349: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
                   6350: used in records written by &store and retrieved by &restore.  This function 
                   6351: was created for use in editing discussion posts, without incrementing the
                   6352: version number included in the key for a particular post. The colon 
                   6353: separated list of attribute names (e.g., the value associated with the key 
                   6354: 1:keys:$symb) is also generated and passed in the ampersand separated 
                   6355: items sent to lonnet::reply().  
                   6356: 
                   6357: =item *
                   6358: 
1.243     albertel 6359: cput($namespace,$storehash,$udom,$uname) : critical put
                   6360: ($udom and $uname are optional)
1.191     harris41 6361: 
                   6362: =item *
                   6363: 
1.243     albertel 6364: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6365: reference filled in from namesp (encrypts the return communication)
                   6366: ($udom and $uname are optional)
1.191     harris41 6367: 
                   6368: =item *
                   6369: 
1.243     albertel 6370: log($udom,$name,$home,$message) : write to permanent log for user; use
                   6371: critical subroutine
                   6372: 
                   6373: =back
                   6374: 
                   6375: =head2 Network Status Functions
                   6376: 
                   6377: =over 4
1.191     harris41 6378: 
                   6379: =item *
                   6380: 
                   6381: dirlist($uri) : return directory list based on URI
                   6382: 
                   6383: =item *
                   6384: 
1.243     albertel 6385: spareserver() : find server with least workload from spare.tab
                   6386: 
                   6387: =back
                   6388: 
                   6389: =head2 Apache Request
                   6390: 
                   6391: =over 4
1.191     harris41 6392: 
                   6393: =item *
                   6394: 
1.243     albertel 6395: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   6396: localhost, posts hash
                   6397: 
                   6398: =back
                   6399: 
                   6400: =head2 Data to String to Data
                   6401: 
                   6402: =over 4
1.191     harris41 6403: 
                   6404: =item *
                   6405: 
1.243     albertel 6406: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   6407: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 6408: 
                   6409: =item *
                   6410: 
1.243     albertel 6411: hashref2str($hashref) : convert a hashref into a string complete with
                   6412: escaping and '=' and '&' separators, supports elements that are
                   6413: arrayrefs and hashrefs
1.191     harris41 6414: 
                   6415: =item *
                   6416: 
1.243     albertel 6417: arrayref2str($arrayref) : convert an arrayref into a string complete
                   6418: with escaping and '&' separators, supports elements that are arrayrefs
                   6419: and hashrefs
1.191     harris41 6420: 
                   6421: =item *
                   6422: 
1.243     albertel 6423: str2hash($string) : convert string to hash using unescaping and
                   6424: splitting on '=' and '&', supports elements that are arrayrefs and
                   6425: hashrefs
1.191     harris41 6426: 
                   6427: =item *
                   6428: 
1.243     albertel 6429: str2array($string) : convert string to hash using unescaping and
                   6430: splitting on '&', supports elements that are arrayrefs and hashrefs
                   6431: 
                   6432: =back
                   6433: 
                   6434: =head2 Logging Routines
                   6435: 
                   6436: =over 4
                   6437: 
                   6438: These routines allow one to make log messages in the lonnet.log and
                   6439: lonnet.perm logfiles.
1.191     harris41 6440: 
                   6441: =item *
                   6442: 
1.243     albertel 6443: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 6444: 
                   6445: =item *
                   6446: 
1.243     albertel 6447: logthis() : append message to the normal lonnet.log file, it gets
                   6448: preiodically rolled over and deleted.
1.191     harris41 6449: 
                   6450: =item *
                   6451: 
1.243     albertel 6452: logperm() : append a permanent message to lonnet.perm.log, this log
                   6453: file never gets deleted by any automated portion of the system, only
                   6454: messages of critical importance should go in here.
                   6455: 
                   6456: =back
                   6457: 
                   6458: =head2 General File Helper Routines
                   6459: 
                   6460: =over 4
1.191     harris41 6461: 
                   6462: =item *
                   6463: 
1.481     raeburn  6464: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   6465: (a) files in /uploaded
                   6466:   (i) If a local copy of the file exists - 
                   6467:       compares modification date of local copy with last-modified date for 
                   6468:       definitive version stored on home server for course. If local copy is 
                   6469:       stale, requests a new version from the home server and stores it. 
                   6470:       If the original has been removed from the home server, then local copy 
                   6471:       is unlinked.
                   6472:   (ii) If local copy does not exist -
                   6473:       requests the file from the home server and stores it. 
                   6474:   
                   6475:   If $caller is 'uploadrep':  
                   6476:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   6477:     for request for files originally uploaded via DOCS. 
                   6478:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   6479:   
                   6480:   Otherwise:
                   6481:      This indicates a call from the content generation phase of the request.
                   6482:      -  returns the entire contents of the file or -1.
                   6483:      
                   6484: (b) files in /res
                   6485:    - returns the entire contents of a file or -1; 
                   6486:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 6487: 
                   6488: =item *
                   6489: 
1.243     albertel 6490: filelocation($dir,$file) : returns file system location of a file
                   6491: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   6492: directory that relative $file lookups are to looked in ($dir of /a/dir
                   6493: and a file of ../bob will become /a/bob)
1.191     harris41 6494: 
                   6495: =item *
                   6496: 
                   6497: hreflocation($dir,$file) : returns file system location or a URL; same as
                   6498: filelocation except for hrefs
                   6499: 
                   6500: =item *
                   6501: 
                   6502: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   6503: 
1.243     albertel 6504: =back
                   6505: 
1.608     albertel 6506: =head2 Usererfile file routines (/uploaded*)
                   6507: 
                   6508: =over 4
                   6509: 
                   6510: =item *
                   6511: 
                   6512: userfileupload(): main rotine for putting a file in a user or course's
                   6513:                   filespace, arguments are,
                   6514: 
                   6515:  formname - required - this is the name of the element in $ENV where the
                   6516:            filename, and the contents of the file to create/modifed exist
                   6517:            the filename is in $ENV{'form.'.$formname.'.filename'} and the
                   6518:            contents of the file is located in $ENV{'form.'.$formname}
                   6519:  coursedoc - if true, store the file in the course of the active role
                   6520:              of the current user
                   6521:  subdir - required - subdirectory to put the file in under ../userfiles/
                   6522:          if undefined, it will be placed in "unknown"
                   6523: 
                   6524:  (This routine calls clean_filename() to remove any dangerous
                   6525:  characters from the filename, and then calls finuserfileupload() to
                   6526:  complete the transaction)
                   6527: 
                   6528:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6529:  and /adm/notfound.html if unsuccessful
                   6530: 
                   6531: =item *
                   6532: 
                   6533: clean_filename(): routine for cleaing a filename up for storage in
                   6534:                  userfile space, argument is:
                   6535: 
                   6536:  filename - proposed filename
                   6537: 
                   6538: returns: the new clean filename
                   6539: 
                   6540: =item *
                   6541: 
                   6542: finishuserfileupload(): routine that creaes and sends the file to
                   6543: userspace, probably shouldn't be called directly
                   6544: 
                   6545:   docuname: username or courseid of destination for the file
                   6546:   docudom: domain of user/course of destination for the file
                   6547:   docuhome: loncapa id of the library server that is getting the file
                   6548:   formname: same as for userfileupload()
                   6549:   fname: filename (inculding subdirectories) for the file
                   6550: 
                   6551:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6552:  and /adm/notfound.html if unsuccessful
                   6553: 
                   6554: =item *
                   6555: 
                   6556: renameuserfile(): renames an existing userfile to a new name
                   6557: 
                   6558:   Args:
                   6559:    docuname: username or courseid of destination for the file
                   6560:    docudom: domain of user/course of destination for the file
                   6561:    old: current file name (including any subdirs under userfiles)
                   6562:    new: desired file name (including any subdirs under userfiles)
                   6563: 
                   6564: =item *
                   6565: 
                   6566: mkdiruserfile(): creates a directory is a userfiles dir
                   6567: 
                   6568:   Args:
                   6569:    docuname: username or courseid of destination for the file
                   6570:    docudom: domain of user/course of destination for the file
                   6571:    dir: dir to create (including any subdirs under userfiles)
                   6572: 
                   6573: =item *
                   6574: 
                   6575: removeuserfile(): removes a file that exists in userfiles
                   6576: 
                   6577:   Args:
                   6578:    docuname: username or courseid of destination for the file
                   6579:    docudom: domain of user/course of destination for the file
                   6580:    fname: filname to delete (including any subdirs under userfiles)
                   6581: 
                   6582: =item *
                   6583: 
                   6584: removeuploadedurl(): convience function for removeuserfile()
                   6585: 
                   6586:   Args:
                   6587:    url:  a full /uploaded/... url to delete
                   6588: 
                   6589: =back
                   6590: 
1.243     albertel 6591: =head2 HTTP Helper Routines
                   6592: 
                   6593: =over 4
                   6594: 
1.191     harris41 6595: =item *
                   6596: 
                   6597: escape() : unpack non-word characters into CGI-compatible hex codes
                   6598: 
                   6599: =item *
                   6600: 
                   6601: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   6602: 
1.243     albertel 6603: =back
                   6604: 
                   6605: =head1 PRIVATE SUBROUTINES
                   6606: 
                   6607: =head2 Underlying communication routines (Shouldn't call)
                   6608: 
                   6609: =over 4
                   6610: 
                   6611: =item *
                   6612: 
                   6613: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   6614: 
                   6615: =item *
                   6616: 
                   6617: reply() : uses subreply to send a message to remote machine, logs all failures
                   6618: 
                   6619: =item *
                   6620: 
                   6621: critical() : passes a critical message to another server; if cannot
                   6622: get through then place message in connection buffer directory and
                   6623: returns con_delayed, if incapable of saving message, returns
                   6624: con_failed
                   6625: 
                   6626: =item *
                   6627: 
                   6628: reconlonc() : tries to reconnect lonc client processes.
                   6629: 
                   6630: =back
                   6631: 
                   6632: =head2 Resource Access Logging
                   6633: 
                   6634: =over 4
                   6635: 
                   6636: =item *
                   6637: 
                   6638: flushcourselogs() : flush (save) buffer logs and access logs
                   6639: 
                   6640: =item *
                   6641: 
                   6642: courselog($what) : save message for course in hash
                   6643: 
                   6644: =item *
                   6645: 
                   6646: courseacclog($what) : save message for course using &courselog().  Perform
                   6647: special processing for specific resource types (problems, exams, quizzes, etc).
                   6648: 
1.191     harris41 6649: =item *
                   6650: 
                   6651: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   6652: as a PerlChildExitHandler
1.243     albertel 6653: 
                   6654: =back
                   6655: 
                   6656: =head2 Other
                   6657: 
                   6658: =over 4
                   6659: 
                   6660: =item *
                   6661: 
                   6662: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 6663: 
                   6664: =back
                   6665: 
                   6666: =cut

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