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

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

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