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

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

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