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

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

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