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

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

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