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

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

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