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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.952   ! raeburn     4: # $Id: lonnet.pm,v 1.951 2008/03/24 04:55:54 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.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
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
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
1.917     albertel  323: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    324: 	if (!$opened) {
1.915     albertel  325: 	    return 0;
                    326: 	}
1.783     albertel  327: 	flock($idf,LOCK_SH);
                    328: 	@profile=<$idf>;
                    329: 	close($idf);
                    330:     }
                    331:     my %temp_env;
                    332:     foreach my $line (@profile) {
1.786     albertel  333: 	if ($line !~ m/=/) {
                    334: 	    return 0;
                    335: 	}
1.783     albertel  336: 	chomp($line);
                    337: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    339:     }
                    340:     unlink("$lonidsdir/$handle.id");
                    341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    342: 	    0640)) {
                    343: 	%disk_env = %temp_env;
                    344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    345: 	untie(%disk_env);
                    346:     }
1.786     albertel  347:     return 1;
1.783     albertel  348: }
                    349: 
1.374     www       350: # ------------------------------------------- Transfer profile into environment
1.780     albertel  351: my $env_loaded;
                    352: sub transfer_profile_to_env {
1.788     albertel  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    354:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       355: 
1.720     albertel  356:     if (!defined($lonidsdir)) {
                    357: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    358:     }
                    359:     if (!defined($handle)) {
                    360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    361:     }
                    362: 
1.786     albertel  363:     my $convert;
                    364:     {
1.917     albertel  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    366: 	if (!$opened) {
1.915     albertel  367: 	    return;
                    368: 	}
1.786     albertel  369: 	flock($idf,LOCK_SH);
                    370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    371: 		&GDBM_READER(),0640)) {
                    372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    373: 	    untie(%disk_env);
                    374: 	} else {
                    375: 	    $convert = 1;
                    376: 	}
                    377:     }
                    378:     if ($convert) {
                    379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    380: 	    &logthis("Failed to load session, or convert session.");
                    381: 	}
1.374     www       382:     }
1.783     albertel  383: 
1.786     albertel  384:     my %remove;
1.783     albertel  385:     while ( my $envname = each(%env) ) {
1.433     matthew   386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    387:             if ($time < time-300) {
1.783     albertel  388:                 $remove{$key}++;
1.433     matthew   389:             }
                    390:         }
                    391:     }
1.783     albertel  392: 
1.619     albertel  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  394:     $env_loaded=1;
1.783     albertel  395:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   396:         &delenv($expired_key);
1.374     www       397:     }
1.1       albertel  398: }
                    399: 
1.916     albertel  400: # ---------------------------------------------------- Check for valid session 
                    401: sub check_for_valid_session {
                    402:     my ($r) = @_;
                    403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    404:     my $lonid=$cookies{'lonID'};
                    405:     return undef if (!$lonid);
                    406: 
                    407:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    408:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    409:     return undef if (!-e "$lonidsdir/$handle.id");
                    410: 
1.917     albertel  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    412:     return undef if (!$opened);
1.916     albertel  413: 
                    414:     flock($idf,LOCK_SH);
                    415:     my %disk_env;
                    416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    417: 	    &GDBM_READER(),0640)) {
                    418: 	return undef;	
                    419:     }
                    420: 
                    421:     if (!defined($disk_env{'user.name'})
                    422: 	|| !defined($disk_env{'user.domain'})) {
                    423: 	return undef;
                    424:     }
                    425:     return $handle;
                    426: }
                    427: 
1.830     albertel  428: sub timed_flock {
                    429:     my ($file,$lock_type) = @_;
                    430:     my $failed=0;
                    431:     eval {
                    432: 	local $SIG{__DIE__}='DEFAULT';
                    433: 	local $SIG{ALRM}=sub {
                    434: 	    $failed=1;
                    435: 	    die("failed lock");
                    436: 	};
                    437: 	alarm(13);
                    438: 	flock($file,$lock_type);
                    439: 	alarm(0);
                    440:     };
                    441:     if ($failed) {
                    442: 	return undef;
                    443:     } else {
                    444: 	return 1;
                    445:     }
                    446: }
                    447: 
1.5       www       448: # ---------------------------------------------------------- Append Environment
                    449: 
                    450: sub appenv {
1.949     raeburn   451:     my ($newenv,$roles) = @_;
                    452:     if (ref($newenv) eq 'HASH') {
                    453:         foreach my $key (keys(%{$newenv})) {
                    454:             my $refused = 0;
                    455: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    456:                 $refused = 1;
                    457:                 if (ref($roles) eq 'ARRAY') {
                    458:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    459:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    460:                         $refused = 0;
                    461:                     }
                    462:                 }
                    463:             }
                    464:             if ($refused) {
                    465:                 &logthis("<font color=\"blue\">WARNING: ".
                    466:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    467:                          .'</font>');
                    468: 	        delete($newenv->{$key});
                    469:             } else {
                    470:                 $env{$key}=$newenv->{$key};
                    471:             }
                    472:         }
                    473:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    474:         if ($opened
                    475: 	    && &timed_flock($env_file,LOCK_EX)
                    476: 	    &&
                    477: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    478: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    479: 	    while (my ($key,$value) = each(%{$newenv})) {
                    480: 	        $disk_env{$key} = $value;
                    481: 	    }
                    482: 	    untie(%disk_env);
1.35      www       483:         }
1.191     harris41  484:     }
1.56      www       485:     return 'ok';
                    486: }
                    487: # ----------------------------------------------------- Delete from Environment
                    488: 
                    489: sub delenv {
                    490:     my $delthis=shift;
                    491:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  492:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       493:                 "Attempt to delete from environment ".$delthis);
                    494:         return 'error';
                    495:     }
1.917     albertel  496:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    497:     if ($opened
1.915     albertel  498: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  499: 	&&
                    500: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    501: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  502: 	foreach my $key (keys(%disk_env)) {
                    503: 	    if ($key=~/^$delthis/) { 
1.915     albertel  504: 		delete($env{$key});
                    505: 		delete($disk_env{$key});
                    506: 	    }
1.448     albertel  507: 	}
1.783     albertel  508: 	untie(%disk_env);
1.5       www       509:     }
                    510:     return 'ok';
1.369     albertel  511: }
                    512: 
1.790     albertel  513: sub get_env_multiple {
                    514:     my ($name) = @_;
                    515:     my @values;
                    516:     if (defined($env{$name})) {
                    517:         # exists is it an array
                    518:         if (ref($env{$name})) {
                    519:             @values=@{ $env{$name} };
                    520:         } else {
                    521:             $values[0]=$env{$name};
                    522:         }
                    523:     }
                    524:     return(@values);
                    525: }
                    526: 
1.369     albertel  527: # ------------------------------------------ Find out current server userload
                    528: sub userload {
                    529:     my $numusers=0;
                    530:     {
                    531: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    532: 	my $filename;
                    533: 	my $curtime=time;
                    534: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  535: 	    next if ($filename eq '.' || $filename eq '..');
                    536: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  537: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  538: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  539: 	}
                    540: 	closedir(LONIDS);
                    541:     }
                    542:     my $userloadpercent=0;
                    543:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    544:     if ($maxuserload) {
1.371     albertel  545: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  546:     }
1.372     albertel  547:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  548:     return $userloadpercent;
1.283     www       549: }
                    550: 
                    551: # ------------------------------------------ Fight off request when overloaded
                    552: 
                    553: sub overloaderror {
                    554:     my ($r,$checkserver)=@_;
                    555:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    556:     my $loadavg;
                    557:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  558:        open(my $loadfile,'/proc/loadavg');
1.283     www       559:        $loadavg=<$loadfile>;
                    560:        $loadavg =~ s/\s.*//g;
1.285     matthew   561:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  562:        close($loadfile);
1.283     www       563:     } else {
                    564:        $loadavg=&reply('load',$checkserver);
                    565:     }
1.285     matthew   566:     my $overload=$loadavg-100;
1.283     www       567:     if ($overload>0) {
1.285     matthew   568: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       569:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       570:         return 413;
1.283     www       571:     }    
                    572:     return '';
1.5       www       573: }
1.1       albertel  574: 
                    575: # ------------------------------ Find server with least workload from spare.tab
1.11      www       576: 
1.1       albertel  577: sub spareserver {
1.670     albertel  578:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  579:     my $spare_server;
1.370     albertel  580:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  581:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    582:                                                      :  $userloadpercent;
                    583:     
                    584:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    585: 	($spare_server, $lowest_load) =
                    586: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    587:     }
                    588: 
                    589:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    590: 
                    591:     if (!$found_server) {
                    592: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    593: 	    ($spare_server, $lowest_load) =
                    594: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    595: 	}
                    596:     }
                    597: 
                    598:     if (!$want_server_name) {
1.838     albertel  599: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  600:     }
                    601:     return $spare_server;
                    602: }
                    603: 
                    604: sub compare_server_load {
                    605:     my ($try_server, $spare_server, $lowest_load) = @_;
                    606: 
                    607:     my $loadans     = &reply('load',    $try_server);
                    608:     my $userloadans = &reply('userload',$try_server);
                    609: 
                    610:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    611: 	next; #didn't get a number from the server
                    612:     }
                    613: 
                    614:     my $load;
                    615:     if ($loadans =~ /\d/) {
                    616: 	if ($userloadans =~ /\d/) {
                    617: 	    #both are numbers, pick the bigger one
                    618: 	    $load = ($loadans > $userloadans) ? $loadans 
                    619: 		                              : $userloadans;
1.411     albertel  620: 	} else {
1.784     albertel  621: 	    $load = $loadans;
1.411     albertel  622: 	}
1.784     albertel  623:     } else {
                    624: 	$load = $userloadans;
                    625:     }
                    626: 
                    627:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    628: 	$spare_server = $try_server;
                    629: 	$lowest_load  = $load;
1.370     albertel  630:     }
1.784     albertel  631:     return ($spare_server,$lowest_load);
1.202     matthew   632: }
1.914     albertel  633: 
                    634: # --------------------------- ask offload servers if user already has a session
                    635: sub find_existing_session {
                    636:     my ($udom,$uname) = @_;
                    637:     foreach my $try_server (@{ $spareid{'primary'} },
                    638: 			    @{ $spareid{'default'} }) {
                    639: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    640:     }
                    641:     return;
                    642: }
                    643: 
                    644: # -------------------------------- ask if server already has a session for user
                    645: sub has_user_session {
                    646:     my ($lonid,$udom,$uname) = @_;
                    647:     my $result = &reply(join(':','userhassession',
                    648: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    649:     return 1 if ($result eq 'ok');
                    650: 
                    651:     return 0;
                    652: }
                    653: 
1.202     matthew   654: # --------------------------------------------- Try to change a user's password
                    655: 
                    656: sub changepass {
1.799     raeburn   657:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   658:     $currentpass = &escape($currentpass);
                    659:     $newpass     = &escape($newpass);
1.799     raeburn   660:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   661: 		       $server);
                    662:     if (! $answer) {
                    663: 	&logthis("No reply on password change request to $server ".
                    664: 		 "by $uname in domain $udom.");
                    665:     } elsif ($answer =~ "^ok") {
                    666:         &logthis("$uname in $udom successfully changed their password ".
                    667: 		 "on $server.");
                    668:     } elsif ($answer =~ "^pwchange_failure") {
                    669: 	&logthis("$uname in $udom was unable to change their password ".
                    670: 		 "on $server.  The action was blocked by either lcpasswd ".
                    671: 		 "or pwchange");
                    672:     } elsif ($answer =~ "^non_authorized") {
                    673:         &logthis("$uname in $udom did not get their password correct when ".
                    674: 		 "attempting to change it on $server.");
                    675:     } elsif ($answer =~ "^auth_mode_error") {
                    676:         &logthis("$uname in $udom attempted to change their password despite ".
                    677: 		 "not being locally or internally authenticated on $server.");
                    678:     } elsif ($answer =~ "^unknown_user") {
                    679:         &logthis("$uname in $udom attempted to change their password ".
                    680: 		 "on $server but were unable to because $server is not ".
                    681: 		 "their home server.");
                    682:     } elsif ($answer =~ "^refused") {
                    683: 	&logthis("$server refused to change $uname in $udom password because ".
                    684: 		 "it was sent an unencrypted request to change the password.");
                    685:     }
                    686:     return $answer;
1.1       albertel  687: }
                    688: 
1.169     harris41  689: # ----------------------- Try to determine user's current authentication scheme
                    690: 
                    691: sub queryauthenticate {
                    692:     my ($uname,$udom)=@_;
1.456     albertel  693:     my $uhome=&homeserver($uname,$udom);
                    694:     if (!$uhome) {
                    695: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    696: 	return 'no_host';
                    697:     }
                    698:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    699:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    700: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  701:     }
1.456     albertel  702:     return $answer;
1.169     harris41  703: }
                    704: 
1.1       albertel  705: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       706: 
1.1       albertel  707: sub authenticate {
1.952   ! raeburn   708:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  709:     $upass=&escape($upass);
                    710:     $uname= &LONCAPA::clean_username($uname);
1.836     www       711:     my $uhome=&homeserver($uname,$udom,1);
1.952   ! raeburn   712:     my $newhome;
1.836     www       713:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    714: # Maybe the machine was offline and only re-appeared again recently?
                    715:         &reconlonc();
                    716: # One more
1.952   ! raeburn   717: 	$uhome=&homeserver($uname,$udom,1);
        !           718:         if (($uhome eq 'no_host') && $checkdefauth) {
        !           719:             if (defined(&domain($udom,'primary'))) {
        !           720:                 $newhome=&domain($udom,'primary');
        !           721:             }
        !           722:             if ($newhome ne '') {
        !           723:                 $uhome = $newhome;
        !           724:             }
        !           725:         }
1.836     www       726: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    727: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952   ! raeburn   728: 	    return 'no_host';
        !           729:         }
1.1       albertel  730:     }
1.952   ! raeburn   731:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  732:     if ($answer eq 'authorized') {
1.952   ! raeburn   733:         if ($newhome) {
        !           734:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
        !           735:             return 'no_account_on_host'; 
        !           736:         } else {
        !           737:             &logthis("User $uname at $udom authorized by $uhome");
        !           738:             return $uhome;
        !           739:         }
1.471     albertel  740:     }
                    741:     if ($answer eq 'non_authorized') {
                    742: 	&logthis("User $uname at $udom rejected by $uhome");
                    743: 	return 'no_host'; 
1.9       www       744:     }
1.471     albertel  745:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  746:     return 'no_host';
                    747: }
                    748: 
                    749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       750: 
1.599     albertel  751: my %homecache;
1.1       albertel  752: sub homeserver {
1.230     stredwic  753:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  754:     my $index="$uname:$udom";
1.426     albertel  755: 
1.599     albertel  756:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  757: 
                    758:     my %servers = &get_servers($udom,'library');
                    759:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  760:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  761: 		 exists($badServerCache{$tryserver}));
1.841     albertel  762: 
                    763: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    764: 	if ($answer eq 'found') {
                    765: 	    delete($badServerCache{$tryserver}); 
                    766: 	    return $homecache{$index}=$tryserver;
                    767: 	} elsif ($answer eq 'no_host') {
                    768: 	    $badServerCache{$tryserver}=1;
                    769: 	}
1.1       albertel  770:     }    
                    771:     return 'no_host';
1.70      www       772: }
                    773: 
                    774: # ------------------------------------- Find the usernames behind a list of IDs
                    775: 
                    776: sub idget {
                    777:     my ($udom,@ids)=@_;
                    778:     my %returnhash=();
                    779:     
1.841     albertel  780:     my %servers = &get_servers($udom,'library');
                    781:     foreach my $tryserver (keys(%servers)) {
                    782: 	my $idlist=join('&',@ids);
                    783: 	$idlist=~tr/A-Z/a-z/; 
                    784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    785: 	my @answer=();
                    786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    787: 	    @answer=split(/\&/,$reply);
                    788: 	}                    ;
                    789: 	my $i;
                    790: 	for ($i=0;$i<=$#ids;$i++) {
                    791: 	    if ($answer[$i]) {
                    792: 		$returnhash{$ids[$i]}=$answer[$i];
                    793: 	    } 
                    794: 	}
                    795:     } 
1.70      www       796:     return %returnhash;
                    797: }
                    798: 
                    799: # ------------------------------------- Find the IDs behind a list of usernames
                    800: 
                    801: sub idrget {
                    802:     my ($udom,@unames)=@_;
                    803:     my %returnhash=();
1.800     albertel  804:     foreach my $uname (@unames) {
                    805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  806:     }
1.70      www       807:     return %returnhash;
                    808: }
                    809: 
                    810: # ------------------------------- Store away a list of names and associated IDs
                    811: 
                    812: sub idput {
                    813:     my ($udom,%ids)=@_;
                    814:     my %servers=();
1.800     albertel  815:     foreach my $uname (keys(%ids)) {
                    816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    817:         my $uhom=&homeserver($uname,$udom);
1.70      www       818:         if ($uhom ne 'no_host') {
1.800     albertel  819:             my $id=&escape($ids{$uname});
1.70      www       820:             $id=~tr/A-Z/a-z/;
1.800     albertel  821:             my $esc_unam=&escape($uname);
1.70      www       822: 	    if ($servers{$uhom}) {
1.800     albertel  823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       824:             } else {
1.800     albertel  825:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       826:             }
                    827:         }
1.191     harris41  828:     }
1.800     albertel  829:     foreach my $server (keys(%servers)) {
                    830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  831:     }
1.344     www       832: }
                    833: 
1.806     raeburn   834: # ------------------------------------------- get items from domain db files   
                    835: 
                    836: sub get_dom {
1.860     raeburn   837:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   838:     my $items='';
                    839:     foreach my $item (@$storearr) {
                    840:         $items.=&escape($item).'&';
                    841:     }
                    842:     $items=~s/\&$//;
1.860     raeburn   843:     if (!$udom) {
                    844:         $udom=$env{'user.domain'};
                    845:         if (defined(&domain($udom,'primary'))) {
                    846:             $uhome=&domain($udom,'primary');
                    847:         } else {
1.874     albertel  848:             undef($uhome);
1.860     raeburn   849:         }
                    850:     } else {
                    851:         if (!$uhome) {
                    852:             if (defined(&domain($udom,'primary'))) {
                    853:                 $uhome=&domain($udom,'primary');
                    854:             }
                    855:         }
                    856:     }
                    857:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   858:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   859:         my %returnhash;
1.875     albertel  860:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   861:             return %returnhash;
                    862:         }
1.806     raeburn   863:         my @pairs=split(/\&/,$rep);
                    864:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    865:             return @pairs;
                    866:         }
                    867:         my $i=0;
                    868:         foreach my $item (@$storearr) {
                    869:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    870:             $i++;
                    871:         }
                    872:         return %returnhash;
                    873:     } else {
1.880     banghart  874:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   875:     }
                    876: }
                    877: 
                    878: # -------------------------------------------- put items in domain db files 
                    879: 
                    880: sub put_dom {
1.860     raeburn   881:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    882:     if (!$udom) {
                    883:         $udom=$env{'user.domain'};
                    884:         if (defined(&domain($udom,'primary'))) {
                    885:             $uhome=&domain($udom,'primary');
                    886:         } else {
1.874     albertel  887:             undef($uhome);
1.860     raeburn   888:         }
                    889:     } else {
                    890:         if (!$uhome) {
                    891:             if (defined(&domain($udom,'primary'))) {
                    892:                 $uhome=&domain($udom,'primary');
                    893:             }
                    894:         }
                    895:     } 
                    896:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   897:         my $items='';
                    898:         foreach my $item (keys(%$storehash)) {
                    899:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    900:         }
                    901:         $items=~s/\&$//;
                    902:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    903:     } else {
1.860     raeburn   904:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   905:     }
                    906: }
                    907: 
1.837     raeburn   908: sub retrieve_inst_usertypes {
                    909:     my ($udom) = @_;
                    910:     my (%returnhash,@order);
1.846     albertel  911:     if (defined(&domain($udom,'primary'))) {
                    912:         my $uhome=&domain($udom,'primary');
1.837     raeburn   913:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    914:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    915:         my @pairs=split(/\&/,$hashitems);
                    916:         foreach my $item (@pairs) {
                    917:             my ($key,$value)=split(/=/,$item,2);
                    918:             $key = &unescape($key);
                    919:             next if ($key =~ /^error: 2 /);
                    920:             $returnhash{$key}=&thaw_unescape($value);
                    921:         }
                    922:         my @esc_order = split(/\&/,$orderitems);
                    923:         foreach my $item (@esc_order) {
                    924:             push(@order,&unescape($item));
                    925:         }
                    926:     } else {
                    927:         &logthis("get_dom failed - no primary domain server for $udom");
                    928:     }
                    929:     return (\%returnhash,\@order);
                    930: }
                    931: 
1.868     raeburn   932: sub is_domainimage {
                    933:     my ($url) = @_;
                    934:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    935:         if (&domain($1) ne '') {
                    936:             return '1';
                    937:         }
                    938:     }
                    939:     return;
                    940: }
                    941: 
1.899     raeburn   942: sub inst_directory_query {
                    943:     my ($srch) = @_;
                    944:     my $udom = $srch->{'srchdomain'};
                    945:     my %results;
                    946:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   947:     my $outcome;
1.899     raeburn   948:     if ($homeserver ne '') {
1.904     albertel  949: 	my $queryid=&reply("querysend:instdirsearch:".
                    950: 			   &escape($srch->{'srchby'}).':'.
                    951: 			   &escape($srch->{'srchterm'}).':'.
                    952: 			   &escape($srch->{'srchtype'}),$homeserver);
                    953: 	my $host=&hostname($homeserver);
                    954: 	if ($queryid !~/^\Q$host\E\_/) {
                    955: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    956: 	    return;
                    957: 	}
                    958: 	my $response = &get_query_reply($queryid);
                    959: 	my $maxtries = 5;
                    960: 	my $tries = 1;
                    961: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    962: 	    $response = &get_query_reply($queryid);
                    963: 	    $tries ++;
                    964: 	}
                    965: 
                    966:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   967:             if ($response eq 'unavailable') {
                    968:                 $outcome = $response;
                    969:             } else {
                    970:                 $outcome = 'ok';
                    971:                 my @matches = split(/\n/,$response);
                    972:                 foreach my $match (@matches) {
                    973:                     my ($key,$value) = split(/=/,$match);
                    974:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    975:                 }
1.899     raeburn   976:             }
                    977:         }
                    978:     }
1.909     raeburn   979:     return ($outcome,%results);
1.899     raeburn   980: }
                    981: 
                    982: sub usersearch {
                    983:     my ($srch) = @_;
                    984:     my $dom = $srch->{'srchdomain'};
                    985:     my %results;
                    986:     my %libserv = &all_library();
                    987:     my $query = 'usersearch';
                    988:     foreach my $tryserver (keys(%libserv)) {
                    989:         if (&host_domain($tryserver) eq $dom) {
                    990:             my $host=&hostname($tryserver);
                    991:             my $queryid=
1.911     raeburn   992:                 &reply("querysend:".&escape($query).':'.
                    993:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   994:                        &escape($srch->{'srchtype'}).':'.
                    995:                        &escape($srch->{'srchterm'}),$tryserver);
                    996:             if ($queryid !~/^\Q$host\E\_/) {
                    997:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   998:                 next;
1.899     raeburn   999:             }
                   1000:             my $reply = &get_query_reply($queryid);
                   1001:             my $maxtries = 1;
                   1002:             my $tries = 1;
                   1003:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1004:                 $reply = &get_query_reply($queryid);
                   1005:                 $tries ++;
                   1006:             }
                   1007:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1008:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1009:             } else {
1.911     raeburn  1010:                 my @matches;
                   1011:                 if ($reply =~ /\n/) {
                   1012:                     @matches = split(/\n/,$reply);
                   1013:                 } else {
                   1014:                     @matches = split(/\&/,$reply);
                   1015:                 }
1.899     raeburn  1016:                 foreach my $match (@matches) {
                   1017:                     my ($uname,$udom,%userhash);
1.911     raeburn  1018:                     foreach my $entry (split(/:/,$match)) {
                   1019:                         my ($key,$value) =
                   1020:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1021:                         $userhash{$key} = $value;
                   1022:                         if ($key eq 'username') {
                   1023:                             $uname = $value;
                   1024:                         } elsif ($key eq 'domain') {
                   1025:                             $udom = $value;
1.911     raeburn  1026:                         }
1.899     raeburn  1027:                     }
                   1028:                     $results{$uname.':'.$udom} = \%userhash;
                   1029:                 }
                   1030:             }
                   1031:         }
                   1032:     }
                   1033:     return %results;
                   1034: }
                   1035: 
1.912     raeburn  1036: sub get_instuser {
                   1037:     my ($udom,$uname,$id) = @_;
                   1038:     my $homeserver = &domain($udom,'primary');
                   1039:     my ($outcome,%results);
                   1040:     if ($homeserver ne '') {
                   1041:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1042:                            &escape($id).':'.&escape($udom),$homeserver);
                   1043:         my $host=&hostname($homeserver);
                   1044:         if ($queryid !~/^\Q$host\E\_/) {
                   1045:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1046:             return;
                   1047:         }
                   1048:         my $response = &get_query_reply($queryid);
                   1049:         my $maxtries = 5;
                   1050:         my $tries = 1;
                   1051:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1052:             $response = &get_query_reply($queryid);
                   1053:             $tries ++;
                   1054:         }
                   1055:         if (!&error($response) && $response ne 'refused') {
                   1056:             if ($response eq 'unavailable') {
                   1057:                 $outcome = $response;
                   1058:             } else {
                   1059:                 $outcome = 'ok';
                   1060:                 my @matches = split(/\n/,$response);
                   1061:                 foreach my $match (@matches) {
                   1062:                     my ($key,$value) = split(/=/,$match);
                   1063:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1064:                 }
                   1065:             }
                   1066:         }
                   1067:     }
                   1068:     my %userinfo;
                   1069:     if (ref($results{$uname}) eq 'HASH') {
                   1070:         %userinfo = %{$results{$uname}};
                   1071:     } 
                   1072:     return ($outcome,%userinfo);
                   1073: }
                   1074: 
                   1075: sub inst_rulecheck {
1.923     raeburn  1076:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1077:     my %returnhash;
                   1078:     if ($udom ne '') {
                   1079:         if (ref($rules) eq 'ARRAY') {
                   1080:             @{$rules} = map {&escape($_);} (@{$rules});
                   1081:             my $rulestr = join(':',@{$rules});
                   1082:             my $homeserver=&domain($udom,'primary');
                   1083:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1084:                 my $response;
                   1085:                 if ($item eq 'username') {                
                   1086:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1087:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1088:                                               $homeserver));
1.923     raeburn  1089:                 } elsif ($item eq 'id') {
                   1090:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1091:                                               ':'.&escape($id).':'.$rulestr,
                   1092:                                               $homeserver));
1.945     raeburn  1093:                 } elsif ($item eq 'selfcreate') {
                   1094:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1095:                                                &escape($udom).':'.&escape($uname).
                   1096:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1097:                 }
1.912     raeburn  1098:                 if ($response ne 'refused') {
                   1099:                     my @pairs=split(/\&/,$response);
                   1100:                     foreach my $item (@pairs) {
                   1101:                         my ($key,$value)=split(/=/,$item,2);
                   1102:                         $key = &unescape($key);
                   1103:                         next if ($key =~ /^error: 2 /);
                   1104:                         $returnhash{$key}=&thaw_unescape($value);
                   1105:                     }
                   1106:                 }
                   1107:             }
                   1108:         }
                   1109:     }
                   1110:     return %returnhash;
                   1111: }
                   1112: 
                   1113: sub inst_userrules {
1.923     raeburn  1114:     my ($udom,$check) = @_;
1.912     raeburn  1115:     my (%ruleshash,@ruleorder);
                   1116:     if ($udom ne '') {
                   1117:         my $homeserver=&domain($udom,'primary');
                   1118:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1119:             my $response;
                   1120:             if ($check eq 'id') {
                   1121:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1122:                                  $homeserver);
1.943     raeburn  1123:             } elsif ($check eq 'email') {
                   1124:                 $response=&reply('instemailrules:'.&escape($udom),
                   1125:                                  $homeserver);
1.923     raeburn  1126:             } else {
                   1127:                 $response=&reply('instuserrules:'.&escape($udom),
                   1128:                                  $homeserver);
                   1129:             }
1.912     raeburn  1130:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1131:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1132:                 ($response ne 'no_such_host')) {
                   1133:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1134:                 my @pairs=split(/\&/,$hashitems);
                   1135:                 foreach my $item (@pairs) {
                   1136:                     my ($key,$value)=split(/=/,$item,2);
                   1137:                     $key = &unescape($key);
                   1138:                     next if ($key =~ /^error: 2 /);
                   1139:                     $ruleshash{$key}=&thaw_unescape($value);
                   1140:                 }
                   1141:                 my @esc_order = split(/\&/,$orderitems);
                   1142:                 foreach my $item (@esc_order) {
                   1143:                     push(@ruleorder,&unescape($item));
                   1144:                 }
                   1145:             }
                   1146:         }
                   1147:     }
                   1148:     return (\%ruleshash,\@ruleorder);
                   1149: }
                   1150: 
1.943     raeburn  1151: # ------------------------- Get Authentication and Language Defaults for Domain
                   1152: 
                   1153: sub get_domain_defaults {
                   1154:     my ($domain) = @_;
                   1155:     my $cachetime = 60*60*24;
                   1156:     my ($defauthtype,$defautharg,$deflang);
                   1157:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1158:     if (defined($cached)) {
                   1159:         if (ref($result) eq 'HASH') {
                   1160:             return %{$result};
                   1161:         }
                   1162:     }
                   1163:     my %domdefaults;
                   1164:     my %domconfig =
                   1165:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1166:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1167:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1168:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1169:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1170:     } else {
                   1171:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1172:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1173:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1174:     }
                   1175:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1176:                                   $cachetime);
                   1177:     return %domdefaults;
                   1178: }
                   1179: 
1.344     www      1180: # --------------------------------------------------- Assign a key to a student
                   1181: 
                   1182: sub assign_access_key {
1.364     www      1183: #
                   1184: # a valid key looks like uname:udom#comments
                   1185: # comments are being appended
                   1186: #
1.498     www      1187:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1188:     $kdom=
1.620     albertel 1189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1190:     $knum=
1.620     albertel 1191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1192:     $cdom=
1.620     albertel 1193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1194:     $cnum=
1.620     albertel 1195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1196:     $udom=$env{'user.name'} unless (defined($udom));
                   1197:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1198:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1199:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1200:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1201:                                                   # assigned to this person
                   1202:                                                   # - this should not happen,
1.345     www      1203:                                                   # unless something went wrong
                   1204:                                                   # the first time around
                   1205: # ready to assign
1.364     www      1206:         $logentry=$1.'; '.$logentry;
1.496     www      1207:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1208:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1209: # key now belongs to user
1.346     www      1210: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1211:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1212:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1213:                 return 'ok';
                   1214:             } else {
                   1215:                 return 
                   1216:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1217: 	    }
                   1218:         } else {
                   1219:             return 'error: Could not assign key, try again later.';
                   1220:         }
1.364     www      1221:     } elsif (!$existing{$ckey}) {
1.345     www      1222: # the key does not exist
                   1223: 	return 'error: The key does not exist';
                   1224:     } else {
                   1225: # the key is somebody else's
                   1226: 	return 'error: The key is already in use';
                   1227:     }
1.344     www      1228: }
                   1229: 
1.364     www      1230: # ------------------------------------------ put an additional comment on a key
                   1231: 
                   1232: sub comment_access_key {
                   1233: #
                   1234: # a valid key looks like uname:udom#comments
                   1235: # comments are being appended
                   1236: #
                   1237:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1238:     $cdom=
1.620     albertel 1239:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1240:     $cnum=
1.620     albertel 1241:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1242:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1243:     if ($existing{$ckey}) {
                   1244:         $existing{$ckey}.='; '.$logentry;
                   1245: # ready to assign
1.367     www      1246:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1247:                                                  $cdom,$cnum) eq 'ok') {
                   1248: 	    return 'ok';
                   1249:         } else {
                   1250: 	    return 'error: Count not store comment.';
                   1251:         }
                   1252:     } else {
                   1253: # the key does not exist
                   1254: 	return 'error: The key does not exist';
                   1255:     }
                   1256: }
                   1257: 
1.344     www      1258: # ------------------------------------------------------ Generate a set of keys
                   1259: 
                   1260: sub generate_access_keys {
1.364     www      1261:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1262:     $cdom=
1.620     albertel 1263:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1264:     $cnum=
1.620     albertel 1265:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1266:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1267:     unless (($cdom) && ($cnum)) { return 0; }
                   1268:     if ($number>10000) { return 0; }
                   1269:     sleep(2); # make sure don't get same seed twice
                   1270:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1271:     my $total=0;
                   1272:     for (my $i=1;$i<=$number;$i++) {
                   1273:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1274:                   sprintf("%lx",int(100000*rand)).'-'.
                   1275:                   sprintf("%lx",int(100000*rand));
                   1276:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1277:        $newkey=~s/0/h/g; # and also 0 and O
                   1278:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1279:        if ($existing{$newkey}) {
                   1280:            $i--;
                   1281:        } else {
1.364     www      1282: 	  if (&put('accesskeys',
                   1283:               { $newkey => '# generated '.localtime().
1.620     albertel 1284:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1285:                            '; '.$logentry },
                   1286: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1287:               $total++;
                   1288: 	  }
                   1289:        }
                   1290:     }
1.620     albertel 1291:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1292:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1293:     return $total;
                   1294: }
                   1295: 
                   1296: # ------------------------------------------------------- Validate an accesskey
                   1297: 
                   1298: sub validate_access_key {
                   1299:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1300:     $cdom=
1.620     albertel 1301:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1302:     $cnum=
1.620     albertel 1303:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1304:     $udom=$env{'user.domain'} unless (defined($udom));
                   1305:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1306:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1307:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1308: }
                   1309: 
                   1310: # ------------------------------------- Find the section of student in a course
1.652     albertel 1311: sub devalidate_getsection_cache {
                   1312:     my ($udom,$unam,$courseid)=@_;
                   1313:     my $hashid="$udom:$unam:$courseid";
                   1314:     &devalidate_cache_new('getsection',$hashid);
                   1315: }
1.298     matthew  1316: 
1.815     albertel 1317: sub courseid_to_courseurl {
                   1318:     my ($courseid) = @_;
                   1319:     #already url style courseid
                   1320:     return $courseid if ($courseid =~ m{^/});
                   1321: 
                   1322:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1323: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1324: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1325: 	return "/$cdom/$cnum";
                   1326:     }
                   1327: 
                   1328:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1329:     if (exists($courseinfo{'num'})) {
                   1330: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1331:     }
                   1332: 
                   1333:     return undef;
                   1334: }
                   1335: 
1.298     matthew  1336: sub getsection {
                   1337:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1338:     my $cachetime=1800;
1.551     albertel 1339: 
                   1340:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1341:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1342:     if (defined($cached)) { return $result; }
                   1343: 
1.298     matthew  1344:     my %Pending; 
                   1345:     my %Expired;
                   1346:     #
                   1347:     # Each role can either have not started yet (pending), be active, 
                   1348:     #    or have expired.
                   1349:     #
                   1350:     # If there is an active role, we are done.
                   1351:     #
                   1352:     # If there is more than one role which has not started yet, 
                   1353:     #     choose the one which will start sooner
                   1354:     # If there is one role which has not started yet, return it.
                   1355:     #
                   1356:     # If there is more than one expired role, choose the one which ended last.
                   1357:     # If there is a role which has expired, return it.
                   1358:     #
1.815     albertel 1359:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1360:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1361:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1362:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1363:         my $section=$1;
                   1364:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1365:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1366:         my $now=time;
1.548     albertel 1367:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1368:             $Expired{$end}=$section;
                   1369:             next;
                   1370:         }
1.548     albertel 1371:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1372:             $Pending{$start}=$section;
                   1373:             next;
                   1374:         }
1.599     albertel 1375:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1376:     }
                   1377:     #
                   1378:     # Presumedly there will be few matching roles from the above
                   1379:     # loop and the sorting time will be negligible.
                   1380:     if (scalar(keys(%Pending))) {
                   1381:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1382:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1383:     } 
                   1384:     if (scalar(keys(%Expired))) {
                   1385:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1386:         my $time = pop(@sorted);
1.599     albertel 1387:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1388:     }
1.599     albertel 1389:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1390: }
1.70      www      1391: 
1.599     albertel 1392: sub save_cache {
                   1393:     &purge_remembered();
1.722     albertel 1394:     #&Apache::loncommon::validate_page();
1.620     albertel 1395:     undef(%env);
1.780     albertel 1396:     undef($env_loaded);
1.599     albertel 1397: }
1.452     albertel 1398: 
1.599     albertel 1399: my $to_remember=-1;
                   1400: my %remembered;
                   1401: my %accessed;
                   1402: my $kicks=0;
                   1403: my $hits=0;
1.849     albertel 1404: sub make_key {
                   1405:     my ($name,$id) = @_;
1.872     albertel 1406:     if (length($id) > 65 
                   1407: 	&& length(&escape($id)) > 200) {
                   1408: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1409:     }
1.849     albertel 1410:     return &escape($name.':'.$id);
                   1411: }
                   1412: 
1.599     albertel 1413: sub devalidate_cache_new {
                   1414:     my ($name,$id,$debug) = @_;
                   1415:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1416:     $id=&make_key($name,$id);
1.599     albertel 1417:     $memcache->delete($id);
                   1418:     delete($remembered{$id});
                   1419:     delete($accessed{$id});
                   1420: }
                   1421: 
                   1422: sub is_cached_new {
                   1423:     my ($name,$id,$debug) = @_;
1.849     albertel 1424:     $id=&make_key($name,$id);
1.599     albertel 1425:     if (exists($remembered{$id})) {
                   1426: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1427: 	$accessed{$id}=[&gettimeofday()];
                   1428: 	$hits++;
                   1429: 	return ($remembered{$id},1);
                   1430:     }
                   1431:     my $value = $memcache->get($id);
                   1432:     if (!(defined($value))) {
                   1433: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1434: 	return (undef,undef);
1.416     albertel 1435:     }
1.599     albertel 1436:     if ($value eq '__undef__') {
                   1437: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1438: 	$value=undef;
                   1439:     }
                   1440:     &make_room($id,$value,$debug);
                   1441:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1442:     return ($value,1);
                   1443: }
                   1444: 
                   1445: sub do_cache_new {
                   1446:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1447:     $id=&make_key($name,$id);
1.599     albertel 1448:     my $setvalue=$value;
                   1449:     if (!defined($setvalue)) {
                   1450: 	$setvalue='__undef__';
                   1451:     }
1.623     albertel 1452:     if (!defined($time) ) {
                   1453: 	$time=600;
                   1454:     }
1.599     albertel 1455:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1456:     my $result = $memcache->set($id,$setvalue,$time);
                   1457:     if (! $result) {
1.872     albertel 1458: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1459: 	$memcache->disconnect_all();
1.872     albertel 1460:     }
1.600     albertel 1461:     # need to make a copy of $value
1.919     albertel 1462:     &make_room($id,$value,$debug);
1.599     albertel 1463:     return $value;
                   1464: }
                   1465: 
                   1466: sub make_room {
                   1467:     my ($id,$value,$debug)=@_;
1.919     albertel 1468: 
                   1469:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1470:                                     : $value;
1.599     albertel 1471:     if ($to_remember<0) { return; }
                   1472:     $accessed{$id}=[&gettimeofday()];
                   1473:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1474:     my $to_kick;
                   1475:     my $max_time=0;
                   1476:     foreach my $other (keys(%accessed)) {
                   1477: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1478: 	    $to_kick=$other;
                   1479: 	    $max_time=&tv_interval($accessed{$other});
                   1480: 	}
                   1481:     }
                   1482:     delete($remembered{$to_kick});
                   1483:     delete($accessed{$to_kick});
                   1484:     $kicks++;
                   1485:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1486:     return;
                   1487: }
                   1488: 
1.599     albertel 1489: sub purge_remembered {
1.604     albertel 1490:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1491:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1492:     undef(%remembered);
                   1493:     undef(%accessed);
1.428     albertel 1494: }
1.70      www      1495: # ------------------------------------- Read an entry from a user's environment
                   1496: 
                   1497: sub userenvironment {
                   1498:     my ($udom,$unam,@what)=@_;
                   1499:     my %returnhash=();
                   1500:     my @answer=split(/\&/,
                   1501:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1502:                       &homeserver($unam,$udom)));
                   1503:     my $i;
                   1504:     for ($i=0;$i<=$#what;$i++) {
                   1505: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1506:     }
                   1507:     return %returnhash;
1.1       albertel 1508: }
                   1509: 
1.617     albertel 1510: # ---------------------------------------------------------- Get a studentphoto
                   1511: sub studentphoto {
                   1512:     my ($udom,$unam,$ext) = @_;
                   1513:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1514:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1515:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1516:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1517:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1518:             } else {
                   1519:                 my ($result,$perm_reqd)=
1.707     albertel 1520: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1521:                 if ($result eq 'ok') {
                   1522:                     if (!($perm_reqd eq 'yes')) {
                   1523:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1524:                     }
                   1525:                 }
                   1526:             }
                   1527:         }
                   1528:     } else {
                   1529:         my ($result,$perm_reqd) = 
1.707     albertel 1530: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1531:         if ($result eq 'ok') {
                   1532:             if (!($perm_reqd eq 'yes')) {
                   1533:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1534:             }
                   1535:         }
                   1536:     }
                   1537:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1538: }
                   1539: 
                   1540: sub retrievestudentphoto {
                   1541:     my ($udom,$unam,$ext,$type) = @_;
                   1542:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1543:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1544:     if ($ret eq 'ok') {
                   1545:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1546:         if ($type eq 'thumbnail') {
                   1547:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1548:         }
                   1549:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1550:         return $tokenurl;
                   1551:     } else {
                   1552:         if ($type eq 'thumbnail') {
                   1553:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1554:         } else { 
                   1555:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1556:         }
1.617     albertel 1557:     }
                   1558: }
                   1559: 
1.263     www      1560: # -------------------------------------------------------------------- New chat
                   1561: 
                   1562: sub chatsend {
1.724     raeburn  1563:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1564:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1565:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1566:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1567:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1568: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1569: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1570: }
                   1571: 
                   1572: # ------------------------------------------ Find current version of a resource
                   1573: 
                   1574: sub getversion {
                   1575:     my $fname=&clutter(shift);
                   1576:     unless ($fname=~/^\/res\//) { return -1; }
                   1577:     return &currentversion(&filelocation('',$fname));
                   1578: }
                   1579: 
                   1580: sub currentversion {
                   1581:     my $fname=shift;
1.599     albertel 1582:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1583:     if (defined($cached)) { return $result; }
1.292     www      1584:     my $author=$fname;
                   1585:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1586:     my ($udom,$uname)=split(/\//,$author);
                   1587:     my $home=homeserver($uname,$udom);
                   1588:     if ($home eq 'no_host') { 
                   1589:         return -1; 
                   1590:     }
                   1591:     my $answer=reply("currentversion:$fname",$home);
                   1592:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1593: 	return -1;
                   1594:     }
1.599     albertel 1595:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1596: }
                   1597: 
1.1       albertel 1598: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1599: 
1.1       albertel 1600: sub subscribe {
                   1601:     my $fname=shift;
1.761     raeburn  1602:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1603:     $fname=~s/[\n\r]//g;
1.1       albertel 1604:     my $author=$fname;
                   1605:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1606:     my ($udom,$uname)=split(/\//,$author);
                   1607:     my $home=homeserver($uname,$udom);
1.335     albertel 1608:     if ($home eq 'no_host') {
                   1609:         return 'not_found';
1.1       albertel 1610:     }
                   1611:     my $answer=reply("sub:$fname",$home);
1.64      www      1612:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1613: 	$answer.=' by '.$home;
                   1614:     }
1.1       albertel 1615:     return $answer;
                   1616: }
                   1617:     
1.8       www      1618: # -------------------------------------------------------------- Replicate file
                   1619: 
                   1620: sub repcopy {
                   1621:     my $filename=shift;
1.23      www      1622:     $filename=~s/\/+/\//g;
1.607     raeburn  1623:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1624:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1625:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1626: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1627: 	return &repcopy_userfile($filename);
                   1628:     }
1.532     albertel 1629:     $filename=~s/[\n\r]//g;
1.8       www      1630:     my $transname="$filename.in.transfer";
1.828     www      1631: # FIXME: this should flock
1.607     raeburn  1632:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1633:     my $remoteurl=subscribe($filename);
1.64      www      1634:     if ($remoteurl =~ /^con_lost by/) {
                   1635: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1636:            return 'unavailable';
1.8       www      1637:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1638: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1639: 	   return 'not_found';
1.64      www      1640:     } elsif ($remoteurl =~ /^rejected by/) {
                   1641: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1642:            return 'forbidden';
1.20      www      1643:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1644:            return 'ok';
1.8       www      1645:     } else {
1.290     www      1646:         my $author=$filename;
                   1647:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1648:         my ($udom,$uname)=split(/\//,$author);
                   1649:         my $home=homeserver($uname,$udom);
                   1650:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1651:            my @parts=split(/\//,$filename);
                   1652:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1653:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1654:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1655: 	       return 'bad_request';
1.8       www      1656:            }
                   1657:            my $count;
                   1658:            for ($count=5;$count<$#parts;$count++) {
                   1659:                $path.="/$parts[$count]";
                   1660:                if ((-e $path)!=1) {
                   1661: 		   mkdir($path,0777);
                   1662:                }
                   1663:            }
                   1664:            my $ua=new LWP::UserAgent;
                   1665:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1666:            my $response=$ua->request($request,$transname);
                   1667:            if ($response->is_error()) {
                   1668: 	       unlink($transname);
                   1669:                my $message=$response->status_line;
1.672     albertel 1670:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1671:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1672:                return 'unavailable';
1.8       www      1673:            } else {
1.16      www      1674: 	       if ($remoteurl!~/\.meta$/) {
                   1675:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1676:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1677:                   if ($mresponse->is_error()) {
                   1678: 		      unlink($filename.'.meta');
                   1679:                       &logthis(
1.672     albertel 1680:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1681:                   }
                   1682: 	       }
1.8       www      1683:                rename($transname,$filename);
1.607     raeburn  1684:                return 'ok';
1.8       www      1685:            }
1.290     www      1686:        }
1.8       www      1687:     }
1.330     www      1688: }
                   1689: 
                   1690: # ------------------------------------------------ Get server side include body
                   1691: sub ssi_body {
1.381     albertel 1692:     my ($filelink,%form)=@_;
1.606     matthew  1693:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1694:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1695:     }
1.330     www      1696:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1697:                                      &ssi($filelink,%form));
1.778     albertel 1698:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1699:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1700:     $output=~s/\<\/body\s*\>.*?$//si;
1.330     www      1701:     return $output;
1.8       www      1702: }
                   1703: 
1.15      www      1704: # --------------------------------------------------------- Server Side Include
                   1705: 
1.782     albertel 1706: sub absolute_url {
                   1707:     my ($host_name) = @_;
                   1708:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1709:     if ($host_name eq '') {
                   1710: 	$host_name = $ENV{'SERVER_NAME'};
                   1711:     }
                   1712:     return $protocol.$host_name;
                   1713: }
                   1714: 
1.942     foxr     1715: #
                   1716: #   Server side include.
                   1717: # Parameters:
                   1718: #  fn     Possibly encrypted resource name/id.
                   1719: #  form   Hash that describes how the rendering should be done
                   1720: #         and other things.
1.944     foxr     1721: # Returns:
1.950     raeburn  1722: #   Scalar context: The content of the response.
                   1723: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1724: #     
1.15      www      1725: sub ssi {
                   1726: 
1.944     foxr     1727:     my ($fn,%form)=@_;
1.15      www      1728:     my $ua=new LWP::UserAgent;
1.23      www      1729:     my $request;
1.711     albertel 1730: 
                   1731:     $form{'no_update_last_known'}=1;
1.895     albertel 1732:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1733:     if (%form) {
1.782     albertel 1734:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1735:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1736:     } else {
1.782     albertel 1737:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1738:     }
                   1739: 
1.15      www      1740:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1741:     my $response=$ua->request($request);
                   1742: 
1.944     foxr     1743:     if (wantarray) {
                   1744: 	return ($response->content, $response);
                   1745:     } else {
                   1746: 	return $response->content;
1.942     foxr     1747:     }
1.324     www      1748: }
                   1749: 
                   1750: sub externalssi {
                   1751:     my ($url)=@_;
                   1752:     my $ua=new LWP::UserAgent;
                   1753:     my $request=new HTTP::Request('GET',$url);
                   1754:     my $response=$ua->request($request);
1.15      www      1755:     return $response->content;
                   1756: }
1.254     www      1757: 
1.492     albertel 1758: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1759: 
                   1760: sub allowuploaded {
                   1761:     my ($srcurl,$url)=@_;
                   1762:     $url=&clutter(&declutter($url));
                   1763:     my $dir=$url;
                   1764:     $dir=~s/\/[^\/]+$//;
                   1765:     my %httpref=();
                   1766:     my $httpurl=&hreflocation('',$url);
                   1767:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1768:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1769: }
1.477     raeburn  1770: 
1.478     albertel 1771: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1772: # input: action, courseID, current domain, intended
1.637     raeburn  1773: #        path to file, source of file, instruction to parse file for objects,
                   1774: #        ref to hash for embedded objects,
                   1775: #        ref to hash for codebase of java objects.
                   1776: #
1.485     raeburn  1777: # output: url to file (if action was uploaddoc), 
                   1778: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1779: #
1.478     albertel 1780: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1781: # course.
1.477     raeburn  1782: #
1.478     albertel 1783: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1784: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1785: #          course's home server.
1.477     raeburn  1786: #
1.478     albertel 1787: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1788: #          be copied from $source (current location) to 
                   1789: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1790: #         and will then be copied to
                   1791: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1792: #         course's home server.
1.485     raeburn  1793: #
1.481     raeburn  1794: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1795: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1796: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1797: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1798: #         in course's home server.
1.637     raeburn  1799: #
1.477     raeburn  1800: 
                   1801: sub process_coursefile {
1.638     albertel 1802:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1803:     my $fetchresult;
1.638     albertel 1804:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1805:     if ($action eq 'propagate') {
1.638     albertel 1806:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1807: 			     $home);
1.481     raeburn  1808:     } else {
1.477     raeburn  1809:         my $fpath = '';
                   1810:         my $fname = $file;
1.478     albertel 1811:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1812:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1813:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1814:         if ($action eq 'copy') {
                   1815:             if ($source eq '') {
                   1816:                 $fetchresult = 'no source file';
                   1817:                 return $fetchresult;
                   1818:             } else {
                   1819:                 my $destination = $filepath.'/'.$fname;
                   1820:                 rename($source,$destination);
                   1821:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1822:                                  $home);
1.481     raeburn  1823:             }
                   1824:         } elsif ($action eq 'uploaddoc') {
                   1825:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1826:             print $fh $env{'form.'.$source};
1.481     raeburn  1827:             close($fh);
1.637     raeburn  1828:             if ($parser eq 'parse') {
                   1829:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1830:                 unless ($parse_result eq 'ok') {
                   1831:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1832:                 }
                   1833:             }
1.477     raeburn  1834:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1835:                                  $home);
1.481     raeburn  1836:             if ($fetchresult eq 'ok') {
                   1837:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1838:             } else {
                   1839:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1840:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1841:                 return '/adm/notfound.html';
                   1842:             }
1.477     raeburn  1843:         }
                   1844:     }
1.485     raeburn  1845:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1846:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1847:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1848:     }
                   1849:     return $fetchresult;
                   1850: }
                   1851: 
1.637     raeburn  1852: sub build_filepath {
                   1853:     my ($fpath) = @_;
                   1854:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1855:     unless ($fpath eq '') {
                   1856:         my @parts=split('/',$fpath);
                   1857:         foreach my $part (@parts) {
                   1858:             $filepath.= '/'.$part;
                   1859:             if ((-e $filepath)!=1) {
                   1860:                 mkdir($filepath,0777);
                   1861:             }
                   1862:         }
                   1863:     }
                   1864:     return $filepath;
                   1865: }
                   1866: 
                   1867: sub store_edited_file {
1.638     albertel 1868:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1869:     my $file = $primary_url;
                   1870:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1871:     my $fpath = '';
                   1872:     my $fname = $file;
                   1873:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1874:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1875:     my $filepath = &build_filepath($fpath);
                   1876:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1877:     print $fh $content;
                   1878:     close($fh);
1.638     albertel 1879:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1880:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1881: 			  $home);
1.637     raeburn  1882:     if ($$fetchresult eq 'ok') {
                   1883:         return '/uploaded/'.$fpath.'/'.$fname;
                   1884:     } else {
1.638     albertel 1885:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1886: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1887:         return '/adm/notfound.html';
                   1888:     }
                   1889: }
                   1890: 
1.531     albertel 1891: sub clean_filename {
1.831     albertel 1892:     my ($fname,$args)=@_;
1.315     www      1893: # Replace Windows backslashes by forward slashes
1.257     www      1894:     $fname=~s/\\/\//g;
1.831     albertel 1895:     if (!$args->{'keep_path'}) {
                   1896:         # Get rid of everything but the actual filename
                   1897: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1898:     }
1.315     www      1899: # Replace spaces by underscores
                   1900:     $fname=~s/\s+/\_/g;
                   1901: # Replace all other weird characters by nothing
1.831     albertel 1902:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1903: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1904: # numbers
                   1905:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1906:     return $fname;
                   1907: }
                   1908: 
1.608     albertel 1909: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1910: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1911: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1912: #        $coursedoc - if true up to the current course
                   1913: #                     if false
                   1914: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1915: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1916: #        $allfiles - reference to hash for embedded objects
                   1917: #        $codebase - reference to hash for codebase of java objects
                   1918: #        $desuname - username for permanent storage of uploaded file
                   1919: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1920: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1921: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1922: # 
1.686     albertel 1923: # output: url of file in userspace, or error: <message> 
                   1924: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1925: 
                   1926: 
1.531     albertel 1927: sub userfileupload {
1.860     raeburn  1928:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1929:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1930:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1931:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1932:     $fname=&clean_filename($fname);
1.315     www      1933: # See if there is anything left
1.257     www      1934:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1935:     chop($env{'form.'.$formname});
1.523     raeburn  1936:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1937:         my $now = time;
                   1938:         my $filepath = 'tmp/helprequests/'.$now;
                   1939:         my @parts=split(/\//,$filepath);
                   1940:         my $fullpath = $perlvar{'lonDaemons'};
                   1941:         for (my $i=0;$i<@parts;$i++) {
                   1942:             $fullpath .= '/'.$parts[$i];
                   1943:             if ((-e $fullpath)!=1) {
                   1944:                 mkdir($fullpath,0777);
                   1945:             }
                   1946:         }
                   1947:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1948:         print $fh $env{'form.'.$formname};
1.523     raeburn  1949:         close($fh);
1.741     raeburn  1950:         return $fullpath.'/'.$fname;
                   1951:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1952:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1953:                        '_'.$env{'user.domain'}.'/pending';
                   1954:         my @parts=split(/\//,$filepath);
                   1955:         my $fullpath = $perlvar{'lonDaemons'};
                   1956:         for (my $i=0;$i<@parts;$i++) {
                   1957:             $fullpath .= '/'.$parts[$i];
                   1958:             if ((-e $fullpath)!=1) {
                   1959:                 mkdir($fullpath,0777);
                   1960:             }
                   1961:         }
                   1962:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1963:         print $fh $env{'form.'.$formname};
                   1964:         close($fh);
                   1965:         return $fullpath.'/'.$fname;
1.523     raeburn  1966:     }
1.719     banghart 1967:     
1.258     www      1968: # Create the directory if not present
1.493     albertel 1969:     $fname="$subdir/$fname";
1.259     www      1970:     if ($coursedoc) {
1.638     albertel 1971: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1972: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1973:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1974:             return &finishuserfileupload($docuname,$docudom,
                   1975: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1976: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1977:         } else {
1.620     albertel 1978:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1979:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1980: 				       $fname,$formname,$parser,
                   1981: 				       $allfiles,$codebase);
1.481     raeburn  1982:         }
1.719     banghart 1983:     } elsif (defined($destuname)) {
                   1984:         my $docuname=$destuname;
                   1985:         my $docudom=$destudom;
1.860     raeburn  1986: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1987: 				     $parser,$allfiles,$codebase,
                   1988:                                      $thumbwidth,$thumbheight);
1.719     banghart 1989:         
1.259     www      1990:     } else {
1.638     albertel 1991:         my $docuname=$env{'user.name'};
                   1992:         my $docudom=$env{'user.domain'};
1.714     raeburn  1993:         if (exists($env{'form.group'})) {
                   1994:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1995:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1996:         }
1.860     raeburn  1997: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1998: 				     $parser,$allfiles,$codebase,
                   1999:                                      $thumbwidth,$thumbheight);
1.259     www      2000:     }
1.271     www      2001: }
                   2002: 
                   2003: sub finishuserfileupload {
1.860     raeburn  2004:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2005:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2006:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2007:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2008:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2009:     $file=$fname;
                   2010:     if ($fname=~m|/|) {
                   2011:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2012: 	$path.=$fnamepath.'/';
                   2013:     }
1.259     www      2014:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2015:     my $count;
                   2016:     for ($count=4;$count<=$#parts;$count++) {
                   2017:         $filepath.="/$parts[$count]";
                   2018:         if ((-e $filepath)!=1) {
                   2019: 	    mkdir($filepath,0777);
                   2020:         }
                   2021:     }
                   2022: # Save the file
                   2023:     {
1.701     albertel 2024: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2025: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2026: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2027: 	    return '/adm/notfound.html';
                   2028: 	}
                   2029: 	if (!print FH ($env{'form.'.$formname})) {
                   2030: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2031: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2032: 	    return '/adm/notfound.html';
                   2033: 	}
1.570     albertel 2034: 	close(FH);
1.258     www      2035:     }
1.637     raeburn  2036:     if ($parser eq 'parse') {
1.638     albertel 2037:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2038: 						   $codebase);
1.637     raeburn  2039:         unless ($parse_result eq 'ok') {
1.638     albertel 2040:             &logthis('Failed to parse '.$filepath.$file.
                   2041: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2042:         }
                   2043:     }
1.860     raeburn  2044:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2045:         my $input = $filepath.'/'.$file;
                   2046:         my $output = $filepath.'/'.'tn-'.$file;
                   2047:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2048:         system("convert -sample $thumbsize $input $output");
                   2049:         if (-e $filepath.'/'.'tn-'.$file) {
                   2050:             $fetchthumb  = 1; 
                   2051:         }
                   2052:     }
1.858     raeburn  2053:  
1.259     www      2054: # Notify homeserver to grep it
                   2055: #
1.638     albertel 2056:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2057:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2058:     if ($fetchresult eq 'ok') {
1.860     raeburn  2059:         if ($fetchthumb) {
                   2060:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2061:             if ($thumbresult ne 'ok') {
                   2062:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2063:                          $docuhome.': '.$thumbresult);
                   2064:             }
                   2065:         }
1.259     www      2066: #
1.258     www      2067: # Return the URL to it
1.494     albertel 2068:         return '/uploaded/'.$path.$file;
1.263     www      2069:     } else {
1.494     albertel 2070:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2071: 		 ': '.$fetchresult);
1.263     www      2072:         return '/adm/notfound.html';
1.858     raeburn  2073:     }
1.493     albertel 2074: }
                   2075: 
1.637     raeburn  2076: sub extract_embedded_items {
1.648     raeburn  2077:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2078:     my @state = ();
                   2079:     my %javafiles = (
                   2080:                       codebase => '',
                   2081:                       code => '',
                   2082:                       archive => ''
                   2083:                     );
                   2084:     my %mediafiles = (
                   2085:                       src => '',
                   2086:                       movie => '',
                   2087:                      );
1.648     raeburn  2088:     my $p;
                   2089:     if ($content) {
                   2090:         $p = HTML::LCParser->new($content);
                   2091:     } else {
                   2092:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2093:     }
1.641     albertel 2094:     while (my $t=$p->get_token()) {
1.640     albertel 2095: 	if ($t->[0] eq 'S') {
                   2096: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2097: 	    push(@state, $tagname);
1.648     raeburn  2098:             if (lc($tagname) eq 'allow') {
                   2099:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2100:             }
1.640     albertel 2101: 	    if (lc($tagname) eq 'img') {
                   2102: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2103: 	    }
1.886     albertel 2104: 	    if (lc($tagname) eq 'a') {
                   2105: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2106: 	    }
1.645     raeburn  2107:             if (lc($tagname) eq 'script') {
                   2108:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2109:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2110:                 } else {
                   2111:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2112:                 }
                   2113:             }
                   2114:             if (lc($tagname) eq 'link') {
                   2115:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2116:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2117:                 }
                   2118:             }
1.640     albertel 2119: 	    if (lc($tagname) eq 'object' ||
                   2120: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2121: 		foreach my $item (keys(%javafiles)) {
                   2122: 		    $javafiles{$item} = '';
                   2123: 		}
                   2124: 	    }
                   2125: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2126: 		my $name = lc($attr->{'name'});
                   2127: 		foreach my $item (keys(%javafiles)) {
                   2128: 		    if ($name eq $item) {
                   2129: 			$javafiles{$item} = $attr->{'value'};
                   2130: 			last;
                   2131: 		    }
                   2132: 		}
                   2133: 		foreach my $item (keys(%mediafiles)) {
                   2134: 		    if ($name eq $item) {
                   2135: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2136: 			last;
                   2137: 		    }
                   2138: 		}
                   2139: 	    }
                   2140: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2141: 		foreach my $item (keys(%javafiles)) {
                   2142: 		    if ($attr->{$item}) {
                   2143: 			$javafiles{$item} = $attr->{$item};
                   2144: 			last;
                   2145: 		    }
                   2146: 		}
                   2147: 		foreach my $item (keys(%mediafiles)) {
                   2148: 		    if ($attr->{$item}) {
                   2149: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2150: 			last;
                   2151: 		    }
                   2152: 		}
                   2153: 	    }
                   2154: 	} elsif ($t->[0] eq 'E') {
                   2155: 	    my ($tagname) = ($t->[1]);
                   2156: 	    if ($javafiles{'codebase'} ne '') {
                   2157: 		$javafiles{'codebase'} .= '/';
                   2158: 	    }  
                   2159: 	    if (lc($tagname) eq 'applet' ||
                   2160: 		lc($tagname) eq 'object' ||
                   2161: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2162: 		) {
                   2163: 		foreach my $item (keys(%javafiles)) {
                   2164: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2165: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2166: 			&add_filetype($allfiles,$file,$item);
                   2167: 		    }
                   2168: 		}
                   2169: 	    } 
                   2170: 	    pop @state;
                   2171: 	}
                   2172:     }
1.637     raeburn  2173:     return 'ok';
                   2174: }
                   2175: 
1.639     albertel 2176: sub add_filetype {
                   2177:     my ($allfiles,$file,$type)=@_;
                   2178:     if (exists($allfiles->{$file})) {
                   2179: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2180: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2181: 	}
                   2182:     } else {
                   2183: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2184:     }
                   2185: }
                   2186: 
1.493     albertel 2187: sub removeuploadedurl {
                   2188:     my ($url)=@_;
                   2189:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2190:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2191: }
                   2192: 
                   2193: sub removeuserfile {
                   2194:     my ($docuname,$docudom,$fname)=@_;
                   2195:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2196:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2197:     if ($result eq 'ok') {
                   2198:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2199:             my $metafile = $fname.'.meta';
                   2200:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2201: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2202:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2203:             my $sqlresult = 
1.823     albertel 2204:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2205:                                         'portfolio_metadata',$group,
                   2206:                                         'delete');
1.798     raeburn  2207:         }
                   2208:     }
                   2209:     return $result;
1.257     www      2210: }
1.15      www      2211: 
1.530     albertel 2212: sub mkdiruserfile {
                   2213:     my ($docuname,$docudom,$dir)=@_;
                   2214:     my $home=&homeserver($docuname,$docudom);
                   2215:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2216: }
                   2217: 
1.531     albertel 2218: sub renameuserfile {
                   2219:     my ($docuname,$docudom,$old,$new)=@_;
                   2220:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2221:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2222:                         &escape("$old").':'.&escape("$new"),$home);
                   2223:     if ($result eq 'ok') {
                   2224:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2225:             my $oldmeta = $old.'.meta';
                   2226:             my $newmeta = $new.'.meta';
                   2227:             my $metaresult = 
                   2228:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2229: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2230:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2231:             my $sqlresult = 
1.823     albertel 2232:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2233:                                         'portfolio_metadata',$group,
                   2234:                                         'delete');
1.798     raeburn  2235:         }
                   2236:     }
                   2237:     return $result;
1.531     albertel 2238: }
                   2239: 
1.14      www      2240: # ------------------------------------------------------------------------- Log
                   2241: 
                   2242: sub log {
                   2243:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2244:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2245: }
                   2246: 
                   2247: # ------------------------------------------------------------------ Course Log
1.352     www      2248: #
                   2249: # This routine flushes several buffers of non-mission-critical nature
                   2250: #
1.157     www      2251: 
                   2252: sub flushcourselogs {
1.352     www      2253:     &logthis('Flushing log buffers');
                   2254: #
                   2255: # course logs
                   2256: # This is a log of all transactions in a course, which can be used
                   2257: # for data mining purposes
                   2258: #
                   2259: # It also collects the courseid database, which lists last transaction
                   2260: # times and course titles for all courseids
                   2261: #
                   2262:     my %courseidbuffer=();
1.921     raeburn  2263:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2264:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2265: 		          &escape($courselogs{$crsid}),
                   2266: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2267: 	    delete $courselogs{$crsid};
                   2268:         } else {
                   2269:             &logthis('Failed to flush log buffer for '.$crsid);
                   2270:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2271:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2272:                         " exceeded maximum size, deleting.</font>");
                   2273:                delete $courselogs{$crsid};
                   2274:             }
1.352     www      2275:         }
1.920     raeburn  2276:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2277:             'description' => $coursedescrbuf{$crsid},
                   2278:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2279:             'type'        => $coursetypebuf{$crsid},
                   2280:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2281:         };
1.191     harris41 2282:     }
1.352     www      2283: #
                   2284: # Write course id database (reverse lookup) to homeserver of courses 
                   2285: # Is used in pickcourse
                   2286: #
1.840     albertel 2287:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2288:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2289:                                     $courseidbuffer{$crs_home},
                   2290:                                     $crs_home,'timeonly');
1.352     www      2291:     }
                   2292: #
                   2293: # File accesses
                   2294: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2295: #
1.449     matthew  2296:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2297:         if ($entry =~ /___count$/) {
                   2298:             my ($dom,$name);
1.807     albertel 2299:             ($dom,$name,undef)=
1.811     albertel 2300: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2301:             if (! defined($dom) || $dom eq '' || 
                   2302:                 ! defined($name) || $name eq '') {
1.620     albertel 2303:                 my $cid = $env{'request.course.id'};
                   2304:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2305:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2306:             }
1.450     matthew  2307:             my $value = $accesshash{$entry};
                   2308:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2309:             my %temphash=($url => $value);
1.449     matthew  2310:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2311:             if ($result eq 'ok') {
                   2312:                 delete $accesshash{$entry};
                   2313:             } elsif ($result eq 'unknown_cmd') {
                   2314:                 # Target server has old code running on it.
1.450     matthew  2315:                 my %temphash=($entry => $value);
1.449     matthew  2316:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2317:                     delete $accesshash{$entry};
                   2318:                 }
                   2319:             }
                   2320:         } else {
1.811     albertel 2321:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2322:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2323:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2324:                 delete $accesshash{$entry};
                   2325:             }
1.185     www      2326:         }
1.191     harris41 2327:     }
1.352     www      2328: #
                   2329: # Roles
                   2330: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2331: #
1.800     albertel 2332:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2333:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2334: 	    split(/\:/,$entry);
                   2335:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2336:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2337:                 $rudom,$runame) eq 'ok') {
                   2338: 	    delete $userrolehash{$entry};
                   2339:         }
                   2340:     }
1.662     raeburn  2341: #
                   2342: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2343: #
                   2344:     my %domrolebuffer = ();
                   2345:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2346:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2347:         if ($domrolebuffer{$rudom}) {
                   2348:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2349:                       '='.&escape($domainrolehash{$entry});
                   2350:         } else {
                   2351:             $domrolebuffer{$rudom}.=&escape($entry).
                   2352:                       '='.&escape($domainrolehash{$entry});
                   2353:         }
                   2354:         delete $domainrolehash{$entry};
                   2355:     }
                   2356:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2357: 	my %servers = &get_servers($dom,'library');
                   2358: 	foreach my $tryserver (keys(%servers)) {
                   2359: 	    unless (&reply('domroleput:'.$dom.':'.
                   2360: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2361: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2362: 	    }
1.662     raeburn  2363:         }
                   2364:     }
1.186     www      2365:     $dumpcount++;
1.157     www      2366: }
                   2367: 
                   2368: sub courselog {
                   2369:     my $what=shift;
1.158     www      2370:     $what=time.':'.$what;
1.620     albertel 2371:     unless ($env{'request.course.id'}) { return ''; }
                   2372:     $coursedombuf{$env{'request.course.id'}}=
                   2373:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2374:     $coursenumbuf{$env{'request.course.id'}}=
                   2375:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2376:     $coursehombuf{$env{'request.course.id'}}=
                   2377:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2378:     $coursedescrbuf{$env{'request.course.id'}}=
                   2379:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2380:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2381:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2382:     $courseownerbuf{$env{'request.course.id'}}=
                   2383:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2384:     $coursetypebuf{$env{'request.course.id'}}=
                   2385:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2386:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2387: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2388:     } else {
1.620     albertel 2389: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2390:     }
1.620     albertel 2391:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2392: 	&flushcourselogs();
                   2393:     }
1.158     www      2394: }
                   2395: 
                   2396: sub courseacclog {
                   2397:     my $fnsymb=shift;
1.620     albertel 2398:     unless ($env{'request.course.id'}) { return ''; }
                   2399:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2400:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2401:         $what.=':POST';
1.583     matthew  2402:         # FIXME: Probably ought to escape things....
1.800     albertel 2403: 	foreach my $key (keys(%env)) {
                   2404:             if ($key=~/^form\.(.*)/) {
                   2405: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2406:             }
1.191     harris41 2407:         }
1.583     matthew  2408:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2409:         # FIXME: We should not be depending on a form parameter that someone
                   2410:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2411:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2412:             $what.= ':POST';
                   2413:             # FIXME: Probably ought to escape things....
                   2414:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2415:                                  'crsdiscuss') {
1.620     albertel 2416:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2417:             }
                   2418:         }
1.158     www      2419:     }
                   2420:     &courselog($what);
1.149     www      2421: }
                   2422: 
1.185     www      2423: sub countacc {
                   2424:     my $url=&declutter(shift);
1.458     matthew  2425:     return if (! defined($url) || $url eq '');
1.620     albertel 2426:     unless ($env{'request.course.id'}) { return ''; }
                   2427:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2428:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2429:     $accesshash{$key}++;
1.185     www      2430: }
1.349     www      2431: 
1.361     www      2432: sub linklog {
                   2433:     my ($from,$to)=@_;
                   2434:     $from=&declutter($from);
                   2435:     $to=&declutter($to);
                   2436:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2437:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2438: }
                   2439:   
1.349     www      2440: sub userrolelog {
                   2441:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2442:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2443:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2444:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2445:         ($trole=~/^ta/)) {
1.350     www      2446:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2447:        $userrolehash
                   2448:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2449:                     =$tend.':'.$tstart;
1.662     raeburn  2450:     }
1.898     albertel 2451:     if (($env{'request.role'} =~ /dc\./) &&
                   2452: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2453: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2454: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2455:        $userrolehash
                   2456:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2457:                     =$tend.':'.$tstart;
                   2458:     }
1.662     raeburn  2459:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2460:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2461:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2462:         ($trole=~/^sc/)) {
                   2463:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2464:        $domainrolehash
                   2465:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2466:                     = $tend.':'.$tstart;
                   2467:     }
1.351     www      2468: }
                   2469: 
                   2470: sub get_course_adv_roles {
1.948     raeburn  2471:     my ($cid,$codes) = @_;
1.620     albertel 2472:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2473:     my %coursehash=&coursedescription($cid);
1.470     www      2474:     my %nothide=();
1.800     albertel 2475:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2476:         if ($user !~ /:/) {
                   2477: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2478:         } else {
                   2479:             $nothide{$user}=1;
                   2480:         }
1.470     www      2481:     }
1.351     www      2482:     my %returnhash=();
                   2483:     my %dumphash=
                   2484:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2485:     my $now=time;
1.800     albertel 2486:     foreach my $entry (keys %dumphash) {
                   2487: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2488:         if (($tstart) && ($tstart<0)) { next; }
                   2489:         if (($tend) && ($tend<$now)) { next; }
                   2490:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2491:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2492: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2493: 	if ((&privileged($username,$domain)) && 
                   2494: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2495: 	if ($role eq 'cr') { next; }
1.948     raeburn  2496:         if ($codes) {
                   2497:             if ($section) { $role .= ':'.$section; }
                   2498:             if ($returnhash{$role}) {
                   2499:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2500:             } else {
                   2501:                 $returnhash{$role}=$username.':'.$domain;
                   2502:             }
1.351     www      2503:         } else {
1.948     raeburn  2504:             my $key=&plaintext($role);
                   2505:             if ($section) { $key.=' (Section '.$section.')'; }
                   2506:             if ($returnhash{$key}) {
                   2507: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2508:             } else {
                   2509:                 $returnhash{$key}=$username.':'.$domain;
                   2510:             }
1.351     www      2511:         }
1.948     raeburn  2512:     }
1.400     www      2513:     return %returnhash;
                   2514: }
                   2515: 
                   2516: sub get_my_roles {
1.937     raeburn  2517:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2518:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2519:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2520:     my (%dumphash,%nothide);
1.858     raeburn  2521:     if ($context eq 'userroles') { 
                   2522:         %dumphash = &dump('roles',$udom,$uname);
                   2523:     } else {
                   2524:         %dumphash=
1.400     www      2525:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2526:         if ($hidepriv) {
                   2527:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2528:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2529:                 if ($user !~ /:/) {
                   2530:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2531:                 } else {
                   2532:                     $nothide{$user} = 1;
                   2533:                 }
                   2534:             }
                   2535:         }
1.858     raeburn  2536:     }
1.400     www      2537:     my %returnhash=();
                   2538:     my $now=time;
1.800     albertel 2539:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2540:         my ($role,$tend,$tstart);
                   2541:         if ($context eq 'userroles') {
                   2542: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2543:         } else {
                   2544:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2545:         }
1.400     www      2546:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2547:         my $status = 'active';
1.939     raeburn  2548:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2549:             $status = 'previous';
                   2550:         } 
                   2551:         if (($tstart) && ($now<$tstart)) {
                   2552:             $status = 'future';
                   2553:         }
                   2554:         if (ref($types) eq 'ARRAY') {
                   2555:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2556:                 next;
                   2557:             } 
                   2558:         } else {
                   2559:             if ($status ne 'active') {
                   2560:                 next;
                   2561:             }
                   2562:         }
1.867     raeburn  2563:         my ($rolecode,$username,$domain,$section,$area);
                   2564:         if ($context eq 'userroles') {
                   2565:             ($area,$rolecode) = split(/_/,$entry);
                   2566:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2567:         } else {
                   2568:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2569:         }
1.832     raeburn  2570:         if (ref($roledoms) eq 'ARRAY') {
                   2571:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2572:                 next;
                   2573:             }
                   2574:         }
                   2575:         if (ref($roles) eq 'ARRAY') {
                   2576:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2577:                 if ($role =~ /^cr\//) {
                   2578:                     if (!grep(/^cr$/,@{$roles})) {
                   2579:                         next;
                   2580:                     }
                   2581:                 } else {
                   2582:                     next;
                   2583:                 }
1.832     raeburn  2584:             }
1.867     raeburn  2585:         }
1.937     raeburn  2586:         if ($hidepriv) {
                   2587:             if ((&privileged($username,$domain)) &&
                   2588:                 (!$nothide{$username.':'.$domain})) { 
                   2589:                 next;
                   2590:             }
                   2591:         }
1.933     raeburn  2592:         if ($withsec) {
                   2593:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2594:                 $tstart.':'.$tend;
                   2595:         } else {
                   2596:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2597:         }
1.832     raeburn  2598:     }
1.373     www      2599:     return %returnhash;
1.399     www      2600: }
                   2601: 
                   2602: # ----------------------------------------------------- Frontpage Announcements
                   2603: #
                   2604: #
                   2605: 
                   2606: sub postannounce {
                   2607:     my ($server,$text)=@_;
1.844     albertel 2608:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2609:     unless ($text=~/\w/) { $text=''; }
                   2610:     return &reply('setannounce:'.&escape($text),$server);
                   2611: }
                   2612: 
                   2613: sub getannounce {
1.448     albertel 2614: 
                   2615:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2616: 	my $announcement='';
1.800     albertel 2617: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2618: 	close($fh);
1.399     www      2619: 	if ($announcement=~/\w/) { 
                   2620: 	    return 
                   2621:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2622:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2623: 	} else {
                   2624: 	    return '';
                   2625: 	}
                   2626:     } else {
                   2627: 	return '';
                   2628:     }
1.351     www      2629: }
1.353     www      2630: 
                   2631: # ---------------------------------------------------------- Course ID routines
                   2632: # Deal with domain's nohist_courseid.db files
                   2633: #
                   2634: 
                   2635: sub courseidput {
1.921     raeburn  2636:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2637:     my $outcome;
                   2638:     if ($caller eq 'timeonly') {
                   2639:         my $cids = '';
                   2640:         foreach my $item (keys(%$storehash)) {
                   2641:             $cids.=&escape($item).'&';
                   2642:         }
                   2643:         $cids=~s/\&$//;
                   2644:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2645:                           $coursehome);       
                   2646:     } else {
                   2647:         my $items = '';
                   2648:         foreach my $item (keys(%$storehash)) {
                   2649:             $items.= &escape($item).'='.
                   2650:                      &freeze_escape($$storehash{$item}).'&';
                   2651:         }
                   2652:         $items=~s/\&$//;
                   2653:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2654:                           $coursehome);
1.918     raeburn  2655:     }
                   2656:     if ($outcome eq 'unknown_cmd') {
                   2657:         my $what;
                   2658:         foreach my $cid (keys(%$storehash)) {
                   2659:             $what .= &escape($cid).'=';
1.921     raeburn  2660:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2661:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2662:             }
                   2663:             $what =~ s/\:$/&/;
                   2664:         }
                   2665:         $what =~ s/\&$//;  
                   2666:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2667:     } else {
                   2668:         return $outcome;
                   2669:     }
1.353     www      2670: }
                   2671: 
                   2672: sub courseiddump {
1.921     raeburn  2673:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2674:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
                   2675:         $selfenrollonly)=@_;
1.918     raeburn  2676:     my $as_hash = 1;
                   2677:     my %returnhash;
                   2678:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2679:     my %libserv = &all_library();
                   2680:     foreach my $tryserver (keys(%libserv)) {
                   2681:         if ( (  $hostidflag == 1 
                   2682: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2683: 	     || (!defined($hostidflag)) ) {
                   2684: 
1.918     raeburn  2685: 	    if (($domfilter eq '') ||
                   2686: 		(&host_domain($tryserver) eq $domfilter)) {
                   2687:                 my $rep = 
                   2688:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2689:                          $sincefilter.':'.&escape($descfilter).':'.
                   2690:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2691:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2692:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   2693:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2694:                 my @pairs=split(/\&/,$rep);
                   2695:                 foreach my $item (@pairs) {
                   2696:                     my ($key,$value)=split(/\=/,$item,2);
                   2697:                     $key = &unescape($key);
                   2698:                     next if ($key =~ /^error: 2 /);
                   2699:                     my $result = &thaw_unescape($value);
                   2700:                     if (ref($result) eq 'HASH') {
                   2701:                         $returnhash{$key}=$result;
                   2702:                     } else {
1.921     raeburn  2703:                         my @responses = split(/:/,$value);
                   2704:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2705:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2706:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2707:                         }
                   2708:                     } 
1.353     www      2709:                 }
                   2710:             }
                   2711:         }
                   2712:     }
                   2713:     return %returnhash;
                   2714: }
                   2715: 
1.658     raeburn  2716: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2717: 
                   2718: sub dcmailput {
1.685     raeburn  2719:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2720:     my $status = &Apache::lonnet::critical(
1.740     www      2721:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2722:        &escape($message),$server);
1.662     raeburn  2723:     return $status;
                   2724: }
                   2725: 
1.658     raeburn  2726: sub dcmaildump {
                   2727:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2728:     my %returnhash=();
1.846     albertel 2729: 
                   2730:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2731:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2732:                                                          &escape($enddate).':';
                   2733: 	my @esc_senders=map { &escape($_)} @$senders;
                   2734: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2735: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2736:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2737:             if (($key) && ($value)) {
                   2738:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2739:             }
                   2740:         }
                   2741:     }
                   2742:     return %returnhash;
                   2743: }
1.662     raeburn  2744: # ---------------------------------------------------------- Domain roles
                   2745: 
                   2746: sub get_domain_roles {
                   2747:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2748:     if (undef($startdate) || $startdate eq '') {
                   2749:         $startdate = '.';
                   2750:     }
                   2751:     if (undef($enddate) || $enddate eq '') {
                   2752:         $enddate = '.';
                   2753:     }
1.922     raeburn  2754:     my $rolelist;
                   2755:     if (ref($roles) eq 'ARRAY') {
                   2756:         $rolelist = join(':',@{$roles});
                   2757:     }
1.662     raeburn  2758:     my %personnel = ();
1.841     albertel 2759: 
                   2760:     my %servers = &get_servers($dom,'library');
                   2761:     foreach my $tryserver (keys(%servers)) {
                   2762: 	%{$personnel{$tryserver}}=();
                   2763: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2764: 					    &escape($startdate).':'.
                   2765: 					    &escape($enddate).':'.
                   2766: 					    &escape($rolelist), $tryserver))) {
                   2767: 	    my ($key,$value) = split(/\=/,$line,2);
                   2768: 	    if (($key) && ($value)) {
                   2769: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2770: 	    }
                   2771: 	}
1.662     raeburn  2772:     }
                   2773:     return %personnel;
                   2774: }
1.658     raeburn  2775: 
1.149     www      2776: # ----------------------------------------------------------- Check out an item
                   2777: 
1.504     albertel 2778: sub get_first_access {
                   2779:     my ($type,$argsymb)=@_;
1.790     albertel 2780:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2781:     if ($argsymb) { $symb=$argsymb; }
                   2782:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2783:     if ($type eq 'course') {
                   2784: 	$res='course';
                   2785:     } elsif ($type eq 'map') {
1.588     albertel 2786: 	$res=&symbread($map);
                   2787:     } else {
                   2788: 	$res=$symb;
                   2789:     }
                   2790:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2791:     return $times{"$courseid\0$res"};
1.504     albertel 2792: }
                   2793: 
                   2794: sub set_first_access {
                   2795:     my ($type)=@_;
1.790     albertel 2796:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2797:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2798:     if ($type eq 'course') {
                   2799: 	$res='course';
                   2800:     } elsif ($type eq 'map') {
1.588     albertel 2801: 	$res=&symbread($map);
                   2802:     } else {
                   2803: 	$res=$symb;
                   2804:     }
                   2805:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2806:     if (!$firstaccess) {
1.588     albertel 2807: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2808:     }
                   2809:     return 'already_set';
1.504     albertel 2810: }
                   2811: 
1.149     www      2812: sub checkout {
                   2813:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2814:     my $now=time;
                   2815:     my $lonhost=$perlvar{'lonHostID'};
                   2816:     my $infostr=&escape(
1.234     www      2817:                  'CHECKOUTTOKEN&'.
1.149     www      2818:                  $tuname.'&'.
                   2819:                  $tudom.'&'.
                   2820:                  $tcrsid.'&'.
                   2821:                  $symb.'&'.
                   2822: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2823:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2824:     if ($token=~/^error\:/) { 
1.672     albertel 2825:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2826:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2827:                  "</font>");
                   2828:         return ''; 
                   2829:     }
                   2830: 
1.149     www      2831:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2832:     $token=~tr/a-z/A-Z/;
                   2833: 
1.153     www      2834:     my %infohash=('resource.0.outtoken' => $token,
                   2835:                   'resource.0.checkouttime' => $now,
                   2836:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2837: 
                   2838:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2839:        return '';
1.151     www      2840:     } else {
1.672     albertel 2841:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2842:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2843:                  "</font>");
1.149     www      2844:     }    
                   2845: 
                   2846:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2847:                          &escape('Checkout '.$infostr.' - '.
                   2848:                                                  $token)) ne 'ok') {
                   2849: 	return '';
1.151     www      2850:     } else {
1.672     albertel 2851:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2852:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2853:                  "</font>");
1.149     www      2854:     }
1.151     www      2855:     return $token;
1.149     www      2856: }
                   2857: 
                   2858: # ------------------------------------------------------------ Check in an item
                   2859: 
                   2860: sub checkin {
                   2861:     my $token=shift;
1.150     www      2862:     my $now=time;
                   2863:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2864:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2865:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2866:     $dtoken=~s/\W/\_/g;
1.234     www      2867:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2868:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2869: 
1.154     www      2870:     unless (($tuname) && ($tudom)) {
                   2871:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2872:         return '';
                   2873:     }
                   2874:     
                   2875:     unless (&allowed('mgr',$tcrsid)) {
                   2876:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2877:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2878:         return '';
                   2879:     }
                   2880: 
1.153     www      2881:     my %infohash=('resource.0.intoken' => $token,
                   2882:                   'resource.0.checkintime' => $now,
                   2883:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2884: 
                   2885:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2886:        return '';
                   2887:     }    
                   2888: 
                   2889:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2890:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2891: 	return '';
                   2892:     }
                   2893: 
                   2894:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2895: }
                   2896: 
                   2897: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2898: 
                   2899: sub expirespread {
                   2900:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2901:     my $cid=$env{'request.course.id'}; 
1.110     www      2902:     if ($cid) {
                   2903:        my $now=time;
                   2904:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2905:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2906:                             $env{'course.'.$cid.'.num'}.
1.110     www      2907: 	        	    ':nohist_expirationdates:'.
                   2908:                             &escape($key).'='.$now,
1.620     albertel 2909:                             $env{'course.'.$cid.'.home'})
1.110     www      2910:     }
                   2911:     return 'ok';
1.14      www      2912: }
                   2913: 
1.109     www      2914: # ----------------------------------------------------- Devalidate Spreadsheets
                   2915: 
                   2916: sub devalidate {
1.325     www      2917:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2918:     my $cid=$env{'request.course.id'}; 
1.109     www      2919:     if ($cid) {
1.391     matthew  2920:         # delete the stored spreadsheets for
                   2921:         # - the student level sheet of this user in course's homespace
                   2922:         # - the assessment level sheet for this resource 
                   2923:         #   for this user in user's homespace
1.553     albertel 2924: 	# - current conditional state info
1.325     www      2925: 	my $key=$uname.':'.$udom.':';
1.109     www      2926:         my $status=
1.299     matthew  2927: 	    &del('nohist_calculatedsheets',
1.391     matthew  2928: 		 [$key.'studentcalc:'],
1.620     albertel 2929: 		 $env{'course.'.$cid.'.domain'},
                   2930: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2931: 		.' '.
                   2932: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2933: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2934:         unless ($status eq 'ok ok') {
                   2935:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2936:                     $uname.' at '.$udom.' for '.
1.109     www      2937: 		    $symb.': '.$status);
1.133     albertel 2938:         }
1.553     albertel 2939: 	&delenv('user.state.'.$cid);
1.109     www      2940:     }
                   2941: }
                   2942: 
1.265     albertel 2943: sub get_scalar {
                   2944:     my ($string,$end) = @_;
                   2945:     my $value;
                   2946:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2947: 	$value = $1;
                   2948:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2949: 	$value = $1;
                   2950:     }
                   2951:     return &unescape($value);
                   2952: }
                   2953: 
                   2954: sub array2str {
                   2955:   my (@array) = @_;
                   2956:   my $result=&arrayref2str(\@array);
                   2957:   $result=~s/^__ARRAY_REF__//;
                   2958:   $result=~s/__END_ARRAY_REF__$//;
                   2959:   return $result;
                   2960: }
                   2961: 
1.204     albertel 2962: sub arrayref2str {
                   2963:   my ($arrayref) = @_;
1.265     albertel 2964:   my $result='__ARRAY_REF__';
1.204     albertel 2965:   foreach my $elem (@$arrayref) {
1.265     albertel 2966:     if(ref($elem) eq 'ARRAY') {
                   2967:       $result.=&arrayref2str($elem).'&';
                   2968:     } elsif(ref($elem) eq 'HASH') {
                   2969:       $result.=&hashref2str($elem).'&';
                   2970:     } elsif(ref($elem)) {
                   2971:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2972:     } else {
                   2973:       $result.=&escape($elem).'&';
                   2974:     }
                   2975:   }
                   2976:   $result=~s/\&$//;
1.265     albertel 2977:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2978:   return $result;
                   2979: }
                   2980: 
1.168     albertel 2981: sub hash2str {
1.204     albertel 2982:   my (%hash) = @_;
                   2983:   my $result=&hashref2str(\%hash);
1.265     albertel 2984:   $result=~s/^__HASH_REF__//;
                   2985:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2986:   return $result;
                   2987: }
                   2988: 
                   2989: sub hashref2str {
                   2990:   my ($hashref)=@_;
1.265     albertel 2991:   my $result='__HASH_REF__';
1.800     albertel 2992:   foreach my $key (sort(keys(%$hashref))) {
                   2993:     if (ref($key) eq 'ARRAY') {
                   2994:       $result.=&arrayref2str($key).'=';
                   2995:     } elsif (ref($key) eq 'HASH') {
                   2996:       $result.=&hashref2str($key).'=';
                   2997:     } elsif (ref($key)) {
1.265     albertel 2998:       $result.='=';
1.800     albertel 2999:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3000:     } else {
1.800     albertel 3001: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3002:     }
                   3003: 
1.800     albertel 3004:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3005:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3006:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3007:       $result.=&hashref2str($hashref->{$key}).'&';
                   3008:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3009:        $result.='&';
1.800     albertel 3010:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3011:     } else {
1.800     albertel 3012:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3013:     }
                   3014:   }
1.168     albertel 3015:   $result=~s/\&$//;
1.265     albertel 3016:   $result .= '__END_HASH_REF__';
1.168     albertel 3017:   return $result;
                   3018: }
                   3019: 
                   3020: sub str2hash {
1.265     albertel 3021:     my ($string)=@_;
                   3022:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3023:     return %$hash;
                   3024: }
                   3025: 
                   3026: sub str2hashref {
1.168     albertel 3027:   my ($string) = @_;
1.265     albertel 3028: 
                   3029:   my %hash;
                   3030: 
                   3031:   if($string !~ /^__HASH_REF__/) {
                   3032:       if (! ($string eq '' || !defined($string))) {
                   3033: 	  $hash{'error'}='Not hash reference';
                   3034:       }
                   3035:       return (\%hash, $string);
                   3036:   }
                   3037: 
                   3038:   $string =~ s/^__HASH_REF__//;
                   3039: 
                   3040:   while($string !~ /^__END_HASH_REF__/) {
                   3041:       #key
                   3042:       my $key='';
                   3043:       if($string =~ /^__HASH_REF__/) {
                   3044:           ($key, $string)=&str2hashref($string);
                   3045:           if(defined($key->{'error'})) {
                   3046:               $hash{'error'}='Bad data';
                   3047:               return (\%hash, $string);
                   3048:           }
                   3049:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3050:           ($key, $string)=&str2arrayref($string);
                   3051:           if($key->[0] eq 'Array reference error') {
                   3052:               $hash{'error'}='Bad data';
                   3053:               return (\%hash, $string);
                   3054:           }
                   3055:       } else {
                   3056:           $string =~ s/^(.*?)=//;
1.267     albertel 3057: 	  $key=&unescape($1);
1.265     albertel 3058:       }
                   3059:       $string =~ s/^=//;
                   3060: 
                   3061:       #value
                   3062:       my $value='';
                   3063:       if($string =~ /^__HASH_REF__/) {
                   3064:           ($value, $string)=&str2hashref($string);
                   3065:           if(defined($value->{'error'})) {
                   3066:               $hash{'error'}='Bad data';
                   3067:               return (\%hash, $string);
                   3068:           }
                   3069:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3070:           ($value, $string)=&str2arrayref($string);
                   3071:           if($value->[0] eq 'Array reference error') {
                   3072:               $hash{'error'}='Bad data';
                   3073:               return (\%hash, $string);
                   3074:           }
                   3075:       } else {
                   3076: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3077:       }
                   3078:       $string =~ s/^&//;
                   3079: 
                   3080:       $hash{$key}=$value;
1.204     albertel 3081:   }
1.265     albertel 3082: 
                   3083:   $string =~ s/^__END_HASH_REF__//;
                   3084: 
                   3085:   return (\%hash, $string);
1.204     albertel 3086: }
                   3087: 
                   3088: sub str2array {
1.265     albertel 3089:     my ($string)=@_;
                   3090:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3091:     return @$array;
                   3092: }
                   3093: 
                   3094: sub str2arrayref {
1.204     albertel 3095:   my ($string) = @_;
1.265     albertel 3096:   my @array;
                   3097: 
                   3098:   if($string !~ /^__ARRAY_REF__/) {
                   3099:       if (! ($string eq '' || !defined($string))) {
                   3100: 	  $array[0]='Array reference error';
                   3101:       }
                   3102:       return (\@array, $string);
                   3103:   }
                   3104: 
                   3105:   $string =~ s/^__ARRAY_REF__//;
                   3106: 
                   3107:   while($string !~ /^__END_ARRAY_REF__/) {
                   3108:       my $value='';
                   3109:       if($string =~ /^__HASH_REF__/) {
                   3110:           ($value, $string)=&str2hashref($string);
                   3111:           if(defined($value->{'error'})) {
                   3112:               $array[0] ='Array reference error';
                   3113:               return (\@array, $string);
                   3114:           }
                   3115:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3116:           ($value, $string)=&str2arrayref($string);
                   3117:           if($value->[0] eq 'Array reference error') {
                   3118:               $array[0] ='Array reference error';
                   3119:               return (\@array, $string);
                   3120:           }
                   3121:       } else {
                   3122: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3123:       }
                   3124:       $string =~ s/^&//;
                   3125: 
                   3126:       push(@array, $value);
1.191     harris41 3127:   }
1.265     albertel 3128: 
                   3129:   $string =~ s/^__END_ARRAY_REF__//;
                   3130: 
                   3131:   return (\@array, $string);
1.168     albertel 3132: }
                   3133: 
1.167     albertel 3134: # -------------------------------------------------------------------Temp Store
                   3135: 
1.168     albertel 3136: sub tmpreset {
                   3137:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3138:   if (!$symb) {
                   3139:     $symb=&symbread();
1.620     albertel 3140:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3141:   }
                   3142:   $symb=escape($symb);
                   3143: 
1.620     albertel 3144:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3145:   $namespace=~s/\//\_/g;
                   3146:   $namespace=~s/\W//g;
                   3147: 
1.620     albertel 3148:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3149:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3150:   if ($domain eq 'public' && $stuname eq 'public') {
                   3151:       $stuname=$ENV{'REMOTE_ADDR'};
                   3152:   }
1.168     albertel 3153:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3154:   my %hash;
                   3155:   if (tie(%hash,'GDBM_File',
                   3156: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3157: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3158:     foreach my $key (keys %hash) {
1.180     albertel 3159:       if ($key=~ /:$symb/) {
1.168     albertel 3160: 	delete($hash{$key});
                   3161:       }
                   3162:     }
                   3163:   }
                   3164: }
                   3165: 
1.167     albertel 3166: sub tmpstore {
1.168     albertel 3167:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3168: 
                   3169:   if (!$symb) {
                   3170:     $symb=&symbread();
1.620     albertel 3171:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3172:   }
                   3173:   $symb=escape($symb);
                   3174: 
                   3175:   if (!$namespace) {
                   3176:     # I don't think we would ever want to store this for a course.
                   3177:     # it seems this will only be used if we don't have a course.
1.620     albertel 3178:     #$namespace=$env{'request.course.id'};
1.168     albertel 3179:     #if (!$namespace) {
1.620     albertel 3180:       $namespace=$env{'request.state'};
1.168     albertel 3181:     #}
                   3182:   }
                   3183:   $namespace=~s/\//\_/g;
                   3184:   $namespace=~s/\W//g;
1.620     albertel 3185:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3186:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3187:   if ($domain eq 'public' && $stuname eq 'public') {
                   3188:       $stuname=$ENV{'REMOTE_ADDR'};
                   3189:   }
1.168     albertel 3190:   my $now=time;
                   3191:   my %hash;
                   3192:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3193:   if (tie(%hash,'GDBM_File',
                   3194: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3195: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3196:     $hash{"version:$symb"}++;
                   3197:     my $version=$hash{"version:$symb"};
                   3198:     my $allkeys=''; 
                   3199:     foreach my $key (keys(%$storehash)) {
                   3200:       $allkeys.=$key.':';
1.591     albertel 3201:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3202:     }
                   3203:     $hash{"$version:$symb:timestamp"}=$now;
                   3204:     $allkeys.='timestamp';
                   3205:     $hash{"$version:keys:$symb"}=$allkeys;
                   3206:     if (untie(%hash)) {
                   3207:       return 'ok';
                   3208:     } else {
                   3209:       return "error:$!";
                   3210:     }
                   3211:   } else {
                   3212:     return "error:$!";
                   3213:   }
                   3214: }
1.167     albertel 3215: 
1.168     albertel 3216: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3217: 
1.168     albertel 3218: sub tmprestore {
                   3219:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3220: 
1.168     albertel 3221:   if (!$symb) {
                   3222:     $symb=&symbread();
1.620     albertel 3223:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3224:   }
                   3225:   $symb=escape($symb);
                   3226: 
1.620     albertel 3227:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3228: 
1.620     albertel 3229:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3230:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3231:   if ($domain eq 'public' && $stuname eq 'public') {
                   3232:       $stuname=$ENV{'REMOTE_ADDR'};
                   3233:   }
1.168     albertel 3234:   my %returnhash;
                   3235:   $namespace=~s/\//\_/g;
                   3236:   $namespace=~s/\W//g;
                   3237:   my %hash;
                   3238:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3239:   if (tie(%hash,'GDBM_File',
                   3240: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3241: 	  &GDBM_READER(),0640)) {
1.168     albertel 3242:     my $version=$hash{"version:$symb"};
                   3243:     $returnhash{'version'}=$version;
                   3244:     my $scope;
                   3245:     for ($scope=1;$scope<=$version;$scope++) {
                   3246:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3247:       my @keys=split(/:/,$vkeys);
                   3248:       my $key;
                   3249:       $returnhash{"$scope:keys"}=$vkeys;
                   3250:       foreach $key (@keys) {
1.591     albertel 3251: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3252: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3253:       }
                   3254:     }
1.168     albertel 3255:     if (!(untie(%hash))) {
                   3256:       return "error:$!";
                   3257:     }
                   3258:   } else {
                   3259:     return "error:$!";
                   3260:   }
                   3261:   return %returnhash;
1.167     albertel 3262: }
                   3263: 
1.9       www      3264: # ----------------------------------------------------------------------- Store
                   3265: 
                   3266: sub store {
1.124     www      3267:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3268:     my $home='';
                   3269: 
1.168     albertel 3270:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3271: 
1.213     www      3272:     $symb=&symbclean($symb);
1.122     albertel 3273:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3274: 
1.620     albertel 3275:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3276:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3277: 
                   3278:     &devalidate($symb,$stuname,$domain);
1.109     www      3279: 
                   3280:     $symb=escape($symb);
1.187     www      3281:     if (!$namespace) { 
1.620     albertel 3282:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3283:           return ''; 
                   3284:        } 
                   3285:     }
1.620     albertel 3286:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3287: 
                   3288:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3289:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3290: 
1.12      www      3291:     my $namevalue='';
1.800     albertel 3292:     foreach my $key (keys(%$storehash)) {
                   3293:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3294:     }
1.12      www      3295:     $namevalue=~s/\&$//;
1.187     www      3296:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3297:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3298: }
                   3299: 
1.47      www      3300: # -------------------------------------------------------------- Critical Store
                   3301: 
                   3302: sub cstore {
1.124     www      3303:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3304:     my $home='';
                   3305: 
1.168     albertel 3306:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3307: 
1.213     www      3308:     $symb=&symbclean($symb);
1.122     albertel 3309:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3310: 
1.620     albertel 3311:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3312:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3313: 
                   3314:     &devalidate($symb,$stuname,$domain);
1.109     www      3315: 
                   3316:     $symb=escape($symb);
1.187     www      3317:     if (!$namespace) { 
1.620     albertel 3318:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3319:           return ''; 
                   3320:        } 
                   3321:     }
1.620     albertel 3322:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3323: 
                   3324:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3325:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3326: 
1.47      www      3327:     my $namevalue='';
1.800     albertel 3328:     foreach my $key (keys(%$storehash)) {
                   3329:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3330:     }
1.47      www      3331:     $namevalue=~s/\&$//;
1.187     www      3332:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3333:     return critical
                   3334:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3335: }
                   3336: 
1.9       www      3337: # --------------------------------------------------------------------- Restore
                   3338: 
                   3339: sub restore {
1.124     www      3340:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3341:     my $home='';
                   3342: 
1.168     albertel 3343:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3344: 
1.122     albertel 3345:     if (!$symb) {
                   3346:       unless ($symb=escape(&symbread())) { return ''; }
                   3347:     } else {
1.213     www      3348:       $symb=&escape(&symbclean($symb));
1.122     albertel 3349:     }
1.188     www      3350:     if (!$namespace) { 
1.620     albertel 3351:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3352:           return ''; 
                   3353:        } 
                   3354:     }
1.620     albertel 3355:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3356:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3357:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3358:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3359: 
1.12      www      3360:     my %returnhash=();
1.800     albertel 3361:     foreach my $line (split(/\&/,$answer)) {
                   3362: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3363:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3364:     }
1.75      www      3365:     my $version;
                   3366:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3367:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3368:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3369:        }
1.75      www      3370:     }
1.13      www      3371:     return %returnhash;
1.34      www      3372: }
                   3373: 
                   3374: # ---------------------------------------------------------- Course Description
                   3375: 
                   3376: sub coursedescription {
1.731     albertel 3377:     my ($courseid,$args)=@_;
1.34      www      3378:     $courseid=~s/^\///;
1.49      www      3379:     $courseid=~s/\_/\//g;
1.34      www      3380:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3381:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3382:     my $normalid=$cdomain.'_'.$cnum;
                   3383:     # need to always cache even if we get errors otherwise we keep 
                   3384:     # trying and trying and trying to get the course description.
                   3385:     my %envhash=();
                   3386:     my %returnhash=();
1.731     albertel 3387:     
                   3388:     my $expiretime=600;
                   3389:     if ($env{'request.course.id'} eq $normalid) {
                   3390: 	$expiretime=120;
                   3391:     }
                   3392: 
                   3393:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3394:     if (!$args->{'freshen_cache'}
                   3395: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3396: 	foreach my $key (keys(%env)) {
                   3397: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3398: 	    my ($setting) = $1;
                   3399: 	    $returnhash{$setting} = $env{$key};
                   3400: 	}
                   3401: 	return %returnhash;
                   3402:     }
                   3403: 
                   3404:     # get the data agin
                   3405:     if (!$args->{'one_time'}) {
                   3406: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3407:     }
1.811     albertel 3408: 
1.34      www      3409:     if ($chome ne 'no_host') {
1.302     albertel 3410:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3411:        if (!exists($returnhash{'con_lost'})) {
                   3412:            $returnhash{'home'}= $chome;
                   3413: 	   $returnhash{'domain'} = $cdomain;
                   3414: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3415:            if (!defined($returnhash{'type'})) {
                   3416:                $returnhash{'type'} = 'Course';
                   3417:            }
1.130     albertel 3418:            while (my ($name,$value) = each %returnhash) {
1.53      www      3419:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3420:            }
1.270     www      3421:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3422:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3423: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3424:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3425:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3426:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3427:        }
                   3428:     }
1.731     albertel 3429:     if (!$args->{'one_time'}) {
1.949     raeburn  3430: 	&appenv(\%envhash);
1.731     albertel 3431:     }
1.302     albertel 3432:     return %returnhash;
1.461     www      3433: }
                   3434: 
                   3435: # -------------------------------------------------See if a user is privileged
                   3436: 
                   3437: sub privileged {
                   3438:     my ($username,$domain)=@_;
                   3439:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3440: 			&homeserver($username,$domain));
                   3441:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3442:     my $now=time;
                   3443:     if ($rolesdump ne '') {
1.800     albertel 3444:         foreach my $entry (split(/&/,$rolesdump)) {
                   3445: 	    if ($entry!~/^rolesdef_/) {
                   3446: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3447: 		$area=~s/\_\w\w$//;
                   3448: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3449: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3450: 		    my $active=1;
                   3451: 		    if ($tend) {
                   3452: 			if ($tend<$now) { $active=0; }
                   3453: 		    }
                   3454: 		    if ($tstart) {
                   3455: 			if ($tstart>$now) { $active=0; }
                   3456: 		    }
                   3457: 		    if ($active) { return 1; }
                   3458: 		}
                   3459: 	    }
                   3460: 	}
                   3461:     }
                   3462:     return 0;
1.9       www      3463: }
1.1       albertel 3464: 
1.103     harris41 3465: # -------------------------------------------------------- Get user privileges
1.11      www      3466: 
                   3467: sub rolesinit {
                   3468:     my ($domain,$username,$authhost)=@_;
                   3469:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3470:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3471:     my %allroles=();
1.678     raeburn  3472:     my %allgroups=();   
1.11      www      3473:     my $now=time;
1.743     albertel 3474:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3475:     my $group_privs;
1.11      www      3476: 
                   3477:     if ($rolesdump ne '') {
1.800     albertel 3478:         foreach my $entry (split(/&/,$rolesdump)) {
                   3479: 	  if ($entry!~/^rolesdef_/) {
                   3480:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3481: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3482:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3483: 	    if ($role=~/^cr/) { 
1.807     albertel 3484: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3485: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3486: 		    ($tend,$tstart)=split('_',$trest);
                   3487: 		} else {
                   3488: 		    $trole=$role;
                   3489: 		}
1.678     raeburn  3490:             } elsif ($role =~ m|^gr/|) {
                   3491:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3492:                 ($trole,$group_privs) = split(/\//,$trole);
                   3493:                 $group_privs = &unescape($group_privs);
1.587     albertel 3494: 	    } else {
                   3495: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3496: 	    }
1.743     albertel 3497: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3498: 					 $username);
                   3499: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3500:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3501:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3502:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3503: 		my $spec=$trole.'.'.$area;
                   3504: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3505: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3506:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3507:                 } elsif ($trole eq 'gr') {
                   3508:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3509: 		} else {
1.567     raeburn  3510:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3511: 		}
1.12      www      3512:             }
1.662     raeburn  3513:           }
1.191     harris41 3514:         }
1.743     albertel 3515:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3516:         $userroles{'user.adv'}    = $adv;
                   3517: 	$userroles{'user.author'} = $author;
1.620     albertel 3518:         $env{'user.adv'}=$adv;
1.11      www      3519:     }
1.743     albertel 3520:     return \%userroles;  
1.11      www      3521: }
                   3522: 
1.567     raeburn  3523: sub set_arearole {
                   3524:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3525: # log the associated role with the area
                   3526:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3527:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3528: }
                   3529: 
                   3530: sub custom_roleprivs {
                   3531:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3532:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3533:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3534:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3535:         my ($rdummy,$roledef)=
                   3536:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3537:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3538:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3539:             if (defined($syspriv)) {
                   3540:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3541:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3542:             }
                   3543:             if ($tdomain ne '') {
                   3544:                 if (defined($dompriv)) {
                   3545:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3546:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3547:                 }
                   3548:                 if (($trest ne '') && (defined($coursepriv))) {
                   3549:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3550:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3551:                 }
                   3552:             }
                   3553:         }
                   3554:     }
                   3555: }
                   3556: 
1.678     raeburn  3557: sub group_roleprivs {
                   3558:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3559:     my $access = 1;
                   3560:     my $now = time;
                   3561:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3562:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3563:     if ($access) {
1.811     albertel 3564:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3565:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3566:     }
                   3567: }
1.567     raeburn  3568: 
                   3569: sub standard_roleprivs {
                   3570:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3571:     if (defined($pr{$trole.':s'})) {
                   3572:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3573:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3574:     }
                   3575:     if ($tdomain ne '') {
                   3576:         if (defined($pr{$trole.':d'})) {
                   3577:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3578:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3579:         }
                   3580:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3581:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3582:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3583:         }
                   3584:     }
                   3585: }
                   3586: 
                   3587: sub set_userprivs {
1.678     raeburn  3588:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3589:     my $author=0;
                   3590:     my $adv=0;
1.678     raeburn  3591:     my %grouproles = ();
                   3592:     if (keys(%{$allgroups}) > 0) {
                   3593:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3594:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3595:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3596:                 $trole = $1;
                   3597:                 $area = $2;
1.681     raeburn  3598:                 $sec = $3;
                   3599:                 $extendedarea = $area.$sec;
                   3600:                 if (exists($$allgroups{$area})) {
                   3601:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3602:                         my $spec = $trole.'.'.$extendedarea;
                   3603:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3604:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3605:                     }
                   3606:                 }
                   3607:             }
                   3608:         }
                   3609:     }
1.800     albertel 3610:     foreach my $group (keys(%grouproles)) {
                   3611:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3612:     }
1.800     albertel 3613:     foreach my $role (keys(%{$allroles})) {
                   3614:         my %thesepriv;
1.941     raeburn  3615:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3616:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3617:             if ($item ne '') {
                   3618:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3619:                 if ($restrictions eq '') {
                   3620:                     $thesepriv{$privilege}='F';
                   3621:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3622:                     $thesepriv{$privilege}.=$restrictions;
                   3623:                 }
                   3624:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3625:             }
                   3626:         }
                   3627:         my $thesestr='';
1.800     albertel 3628:         foreach my $priv (keys(%thesepriv)) {
                   3629: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3630: 	}
                   3631:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3632:     }
                   3633:     return ($author,$adv);
                   3634: }
                   3635: 
1.12      www      3636: # --------------------------------------------------------------- get interface
                   3637: 
                   3638: sub get {
1.131     albertel 3639:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3640:    my $items='';
1.800     albertel 3641:    foreach my $item (@$storearr) {
                   3642:        $items.=&escape($item).'&';
1.191     harris41 3643:    }
1.12      www      3644:    $items=~s/\&$//;
1.620     albertel 3645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3646:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3647:    my $uhome=&homeserver($uname,$udomain);
                   3648: 
1.133     albertel 3649:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3650:    my @pairs=split(/\&/,$rep);
1.273     albertel 3651:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3652:      return @pairs;
                   3653:    }
1.15      www      3654:    my %returnhash=();
1.42      www      3655:    my $i=0;
1.800     albertel 3656:    foreach my $item (@$storearr) {
                   3657:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3658:       $i++;
1.191     harris41 3659:    }
1.15      www      3660:    return %returnhash;
1.27      www      3661: }
                   3662: 
                   3663: # --------------------------------------------------------------- del interface
                   3664: 
                   3665: sub del {
1.133     albertel 3666:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3667:    my $items='';
1.800     albertel 3668:    foreach my $item (@$storearr) {
                   3669:        $items.=&escape($item).'&';
1.191     harris41 3670:    }
1.27      www      3671:    $items=~s/\&$//;
1.620     albertel 3672:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3673:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3674:    my $uhome=&homeserver($uname,$udomain);
                   3675: 
                   3676:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3677: }
                   3678: 
                   3679: # -------------------------------------------------------------- dump interface
                   3680: 
                   3681: sub dump {
1.755     albertel 3682:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3683:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3684:     if (!$uname) { $uname=$env{'user.name'}; }
                   3685:     my $uhome=&homeserver($uname,$udomain);
                   3686:     if ($regexp) {
                   3687: 	$regexp=&escape($regexp);
                   3688:     } else {
                   3689: 	$regexp='.';
                   3690:     }
                   3691:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3692:     my @pairs=split(/\&/,$rep);
                   3693:     my %returnhash=();
                   3694:     foreach my $item (@pairs) {
                   3695: 	my ($key,$value)=split(/=/,$item,2);
                   3696: 	$key = &unescape($key);
                   3697: 	next if ($key =~ /^error: 2 /);
                   3698: 	$returnhash{$key}=&thaw_unescape($value);
                   3699:     }
                   3700:     return %returnhash;
1.407     www      3701: }
                   3702: 
1.717     albertel 3703: # --------------------------------------------------------- dumpstore interface
                   3704: 
                   3705: sub dumpstore {
                   3706:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3707:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3708:    if (!$uname) { $uname=$env{'user.name'}; }
                   3709:    my $uhome=&homeserver($uname,$udomain);
                   3710:    if ($regexp) {
                   3711:        $regexp=&escape($regexp);
                   3712:    } else {
                   3713:        $regexp='.';
                   3714:    }
                   3715:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3716:    my @pairs=split(/\&/,$rep);
                   3717:    my %returnhash=();
                   3718:    foreach my $item (@pairs) {
                   3719:        my ($key,$value)=split(/=/,$item,2);
                   3720:        next if ($key =~ /^error: 2 /);
                   3721:        $returnhash{$key}=&thaw_unescape($value);
                   3722:    }
                   3723:    return %returnhash;
1.717     albertel 3724: }
                   3725: 
1.407     www      3726: # -------------------------------------------------------------- keys interface
                   3727: 
                   3728: sub getkeys {
                   3729:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3730:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3731:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3732:    my $uhome=&homeserver($uname,$udomain);
                   3733:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3734:    my @keyarray=();
1.800     albertel 3735:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3736:       next if ($key =~ /^error: 2 /);
1.800     albertel 3737:       push(@keyarray,&unescape($key));
1.407     www      3738:    }
                   3739:    return @keyarray;
1.318     matthew  3740: }
                   3741: 
1.319     matthew  3742: # --------------------------------------------------------------- currentdump
                   3743: sub currentdump {
1.328     matthew  3744:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3745:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3746:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3747:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3748:    my $uhome = &homeserver($sname,$sdom);
                   3749:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3750:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3751:    #
1.318     matthew  3752:    my %returnhash=();
1.319     matthew  3753:    #
                   3754:    if ($rep eq "unknown_cmd") { 
                   3755:        # an old lond will not know currentdump
                   3756:        # Do a dump and make it look like a currentdump
1.822     albertel 3757:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3758:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3759:        my %hash = @tmp;
                   3760:        @tmp=();
1.424     matthew  3761:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3762:    } else {
                   3763:        my @pairs=split(/\&/,$rep);
1.800     albertel 3764:        foreach my $pair (@pairs) {
                   3765:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3766:            my ($symb,$param) = split(/:/,$key);
                   3767:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3768:                                                         &thaw_unescape($value);
1.319     matthew  3769:        }
1.191     harris41 3770:    }
1.12      www      3771:    return %returnhash;
1.424     matthew  3772: }
                   3773: 
                   3774: sub convert_dump_to_currentdump{
                   3775:     my %hash = %{shift()};
                   3776:     my %returnhash;
                   3777:     # Code ripped from lond, essentially.  The only difference
                   3778:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3779:     # we might run in to problems with parameter names =~ /^v\./
                   3780:     while (my ($key,$value) = each(%hash)) {
                   3781:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3782: 	$symb  = &unescape($symb);
                   3783: 	$param = &unescape($param);
1.424     matthew  3784:         next if ($v eq 'version' || $symb eq 'keys');
                   3785:         next if (exists($returnhash{$symb}) &&
                   3786:                  exists($returnhash{$symb}->{$param}) &&
                   3787:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3788:         $returnhash{$symb}->{$param}=$value;
                   3789:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3790:     }
                   3791:     #
                   3792:     # Remove all of the keys in the hashes which keep track of
                   3793:     # the version of the parameter.
                   3794:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3795:         # use a foreach because we are going to delete from the hash.
                   3796:         foreach my $key (keys(%$param_hash)) {
                   3797:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3798:         }
                   3799:     }
                   3800:     return \%returnhash;
1.12      www      3801: }
                   3802: 
1.627     albertel 3803: # ------------------------------------------------------ critical inc interface
                   3804: 
                   3805: sub cinc {
                   3806:     return &inc(@_,'critical');
                   3807: }
                   3808: 
1.449     matthew  3809: # --------------------------------------------------------------- inc interface
                   3810: 
                   3811: sub inc {
1.627     albertel 3812:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3813:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3814:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3815:     my $uhome=&homeserver($uname,$udomain);
                   3816:     my $items='';
                   3817:     if (! ref($store)) {
                   3818:         # got a single value, so use that instead
                   3819:         $items = &escape($store).'=&';
                   3820:     } elsif (ref($store) eq 'SCALAR') {
                   3821:         $items = &escape($$store).'=&';        
                   3822:     } elsif (ref($store) eq 'ARRAY') {
                   3823:         $items = join('=&',map {&escape($_);} @{$store});
                   3824:     } elsif (ref($store) eq 'HASH') {
                   3825:         while (my($key,$value) = each(%{$store})) {
                   3826:             $items.= &escape($key).'='.&escape($value).'&';
                   3827:         }
                   3828:     }
                   3829:     $items=~s/\&$//;
1.627     albertel 3830:     if ($critical) {
                   3831: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3832:     } else {
                   3833: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3834:     }
1.449     matthew  3835: }
                   3836: 
1.12      www      3837: # --------------------------------------------------------------- put interface
                   3838: 
                   3839: sub put {
1.134     albertel 3840:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3842:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3843:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3844:    my $items='';
1.800     albertel 3845:    foreach my $item (keys(%$storehash)) {
                   3846:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3847:    }
1.12      www      3848:    $items=~s/\&$//;
1.134     albertel 3849:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3850: }
                   3851: 
1.631     albertel 3852: # ------------------------------------------------------------ newput interface
                   3853: 
                   3854: sub newput {
                   3855:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3856:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3857:    if (!$uname) { $uname=$env{'user.name'}; }
                   3858:    my $uhome=&homeserver($uname,$udomain);
                   3859:    my $items='';
                   3860:    foreach my $key (keys(%$storehash)) {
                   3861:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3862:    }
                   3863:    $items=~s/\&$//;
                   3864:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3865: }
                   3866: 
                   3867: # ---------------------------------------------------------  putstore interface
                   3868: 
1.524     raeburn  3869: sub putstore {
1.715     albertel 3870:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3871:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3872:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3873:    my $uhome=&homeserver($uname,$udomain);
                   3874:    my $items='';
1.715     albertel 3875:    foreach my $key (keys(%$storehash)) {
                   3876:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3877:    }
1.715     albertel 3878:    $items=~s/\&$//;
1.716     albertel 3879:    my $esc_symb=&escape($symb);
                   3880:    my $esc_v=&escape($version);
1.715     albertel 3881:    my $reply =
1.716     albertel 3882:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3883: 	      $uhome);
                   3884:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3885:        # gfall back to way things use to be done
1.715     albertel 3886:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3887: 			    $uname);
1.524     raeburn  3888:    }
1.715     albertel 3889:    return $reply;
                   3890: }
                   3891: 
                   3892: sub old_putstore {
1.716     albertel 3893:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3894:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3895:     if (!$uname) { $uname=$env{'user.name'}; }
                   3896:     my $uhome=&homeserver($uname,$udomain);
                   3897:     my %newstorehash;
1.800     albertel 3898:     foreach my $item (keys(%$storehash)) {
                   3899: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3900: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3901:     }
                   3902:     my $items='';
                   3903:     my %allitems = ();
1.800     albertel 3904:     foreach my $item (keys(%newstorehash)) {
                   3905: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3906: 	    my $key = $1.':keys:'.$2;
                   3907: 	    $allitems{$key} .= $3.':';
                   3908: 	}
1.800     albertel 3909: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3910:     }
1.800     albertel 3911:     foreach my $item (keys(%allitems)) {
                   3912: 	$allitems{$item} =~ s/\:$//;
                   3913: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3914:     }
                   3915:     $items=~s/\&$//;
                   3916:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3917: }
                   3918: 
1.47      www      3919: # ------------------------------------------------------ critical put interface
                   3920: 
                   3921: sub cput {
1.134     albertel 3922:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3923:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3924:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3925:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3926:    my $items='';
1.800     albertel 3927:    foreach my $item (keys(%$storehash)) {
                   3928:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3929:    }
1.47      www      3930:    $items=~s/\&$//;
1.134     albertel 3931:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3932: }
                   3933: 
                   3934: # -------------------------------------------------------------- eget interface
                   3935: 
                   3936: sub eget {
1.133     albertel 3937:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3938:    my $items='';
1.800     albertel 3939:    foreach my $item (@$storearr) {
                   3940:        $items.=&escape($item).'&';
1.191     harris41 3941:    }
1.12      www      3942:    $items=~s/\&$//;
1.620     albertel 3943:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3944:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3945:    my $uhome=&homeserver($uname,$udomain);
                   3946:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3947:    my @pairs=split(/\&/,$rep);
                   3948:    my %returnhash=();
1.42      www      3949:    my $i=0;
1.800     albertel 3950:    foreach my $item (@$storearr) {
                   3951:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3952:       $i++;
1.191     harris41 3953:    }
1.12      www      3954:    return %returnhash;
                   3955: }
                   3956: 
1.667     albertel 3957: # ------------------------------------------------------------ tmpput interface
                   3958: sub tmpput {
1.802     raeburn  3959:     my ($storehash,$server,$context)=@_;
1.667     albertel 3960:     my $items='';
1.800     albertel 3961:     foreach my $item (keys(%$storehash)) {
                   3962: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3963:     }
                   3964:     $items=~s/\&$//;
1.802     raeburn  3965:     if (defined($context)) {
                   3966:         $items .= ':'.&escape($context);
                   3967:     }
1.667     albertel 3968:     return &reply("tmpput:$items",$server);
                   3969: }
                   3970: 
                   3971: # ------------------------------------------------------------ tmpget interface
                   3972: sub tmpget {
1.688     albertel 3973:     my ($token,$server)=@_;
                   3974:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3975:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3976:     my %returnhash;
                   3977:     foreach my $item (split(/\&/,$rep)) {
                   3978: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  3979:         next if ($key =~ /^error: 2 /);
1.667     albertel 3980: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3981:     }
                   3982:     return %returnhash;
                   3983: }
                   3984: 
1.688     albertel 3985: # ------------------------------------------------------------ tmpget interface
                   3986: sub tmpdel {
                   3987:     my ($token,$server)=@_;
                   3988:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3989:     return &reply("tmpdel:$token",$server);
                   3990: }
                   3991: 
1.765     albertel 3992: # -------------------------------------------------- portfolio access checking
                   3993: 
                   3994: sub portfolio_access {
1.766     albertel 3995:     my ($requrl) = @_;
1.765     albertel 3996:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3997:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3998:     if ($result) {
                   3999:         my %setters;
                   4000:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4001:             my ($startblock,$endblock) =
                   4002:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4003:             if ($startblock && $endblock) {
                   4004:                 return 'B';
                   4005:             }
                   4006:         } else {
                   4007:             my ($startblock,$endblock) =
                   4008:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4009:             if ($startblock && $endblock) {
                   4010:                 return 'B';
                   4011:             }
                   4012:         }
                   4013:     }
1.765     albertel 4014:     if ($result eq 'ok') {
1.766     albertel 4015:        return 'F';
1.765     albertel 4016:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4017:        return 'A';
1.765     albertel 4018:     }
1.766     albertel 4019:     return '';
1.765     albertel 4020: }
                   4021: 
                   4022: sub get_portfolio_access {
1.767     albertel 4023:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4024: 
                   4025:     if (!ref($access_hash)) {
                   4026: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4027: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4028: 						   $file_name);
                   4029: 	$access_hash = $access_controls{$file_name};
                   4030:     }
                   4031: 
1.765     albertel 4032:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4033:     my $now = time;
                   4034:     if (ref($access_hash) eq 'HASH') {
                   4035:         foreach my $key (keys(%{$access_hash})) {
                   4036:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4037:             if ($start > $now) {
                   4038:                 next;
                   4039:             }
                   4040:             if ($end && $end<$now) {
                   4041:                 next;
                   4042:             }
                   4043:             if ($scope eq 'public') {
                   4044:                 $public = $key;
                   4045:                 last;
                   4046:             } elsif ($scope eq 'guest') {
                   4047:                 $guest = $key;
                   4048:             } elsif ($scope eq 'domains') {
                   4049:                 push(@domains,$key);
                   4050:             } elsif ($scope eq 'users') {
                   4051:                 push(@users,$key);
                   4052:             } elsif ($scope eq 'course') {
                   4053:                 push(@courses,$key);
                   4054:             } elsif ($scope eq 'group') {
                   4055:                 push(@groups,$key);
                   4056:             }
                   4057:         }
                   4058:         if ($public) {
                   4059:             return 'ok';
                   4060:         }
                   4061:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4062:             if ($guest) {
                   4063:                 return $guest;
                   4064:             }
                   4065:         } else {
                   4066:             if (@domains > 0) {
                   4067:                 foreach my $domkey (@domains) {
                   4068:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4069:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4070:                             return 'ok';
                   4071:                         }
                   4072:                     }
                   4073:                 }
                   4074:             }
                   4075:             if (@users > 0) {
                   4076:                 foreach my $userkey (@users) {
1.865     raeburn  4077:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4078:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4079:                             if (ref($item) eq 'HASH') {
                   4080:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4081:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4082:                                     return 'ok';
                   4083:                                 }
                   4084:                             }
                   4085:                         }
                   4086:                     } 
1.765     albertel 4087:                 }
                   4088:             }
                   4089:             my %roleshash;
                   4090:             my @courses_and_groups = @courses;
                   4091:             push(@courses_and_groups,@groups); 
                   4092:             if (@courses_and_groups > 0) {
                   4093:                 my (%allgroups,%allroles); 
                   4094:                 my ($start,$end,$role,$sec,$group);
                   4095:                 foreach my $envkey (%env) {
1.811     albertel 4096:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4097:                         my $cid = $2.'_'.$3; 
                   4098:                         if ($1 eq 'gr') {
                   4099:                             $group = $4;
                   4100:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4101:                         } else {
                   4102:                             if ($4 eq '') {
                   4103:                                 $sec = 'none';
                   4104:                             } else {
                   4105:                                 $sec = $4;
                   4106:                             }
                   4107:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4108:                         }
1.811     albertel 4109:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4110:                         my $cid = $2.'_'.$3;
                   4111:                         if ($4 eq '') {
                   4112:                             $sec = 'none';
                   4113:                         } else {
                   4114:                             $sec = $4;
                   4115:                         }
                   4116:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4117:                     }
                   4118:                 }
                   4119:                 if (keys(%allroles) == 0) {
                   4120:                     return;
                   4121:                 }
                   4122:                 foreach my $key (@courses_and_groups) {
                   4123:                     my %content = %{$$access_hash{$key}};
                   4124:                     my $cnum = $content{'number'};
                   4125:                     my $cdom = $content{'domain'};
                   4126:                     my $cid = $cdom.'_'.$cnum;
                   4127:                     if (!exists($allroles{$cid})) {
                   4128:                         next;
                   4129:                     }    
                   4130:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4131:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4132:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4133:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4134:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4135:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4136:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4137:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4138:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4139:                                         if (grep/^all$/,@sections) {
                   4140:                                             return 'ok';
                   4141:                                         } else {
                   4142:                                             if (grep/^$sec$/,@sections) {
                   4143:                                                 return 'ok';
                   4144:                                             }
                   4145:                                         }
                   4146:                                     }
                   4147:                                 }
                   4148:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4149:                                     if (grep/^none$/,@groups) {
                   4150:                                         return 'ok';
                   4151:                                     }
                   4152:                                 } else {
                   4153:                                     if (grep/^all$/,@groups) {
                   4154:                                         return 'ok';
                   4155:                                     } 
                   4156:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4157:                                         if (grep/^$group$/,@groups) {
                   4158:                                             return 'ok';
                   4159:                                         }
                   4160:                                     }
                   4161:                                 } 
                   4162:                             }
                   4163:                         }
                   4164:                     }
                   4165:                 }
                   4166:             }
                   4167:             if ($guest) {
                   4168:                 return $guest;
                   4169:             }
                   4170:         }
                   4171:     }
                   4172:     return;
                   4173: }
                   4174: 
                   4175: sub course_group_datechecker {
                   4176:     my ($dates,$now,$status) = @_;
                   4177:     my ($start,$end) = split(/\./,$dates);
                   4178:     if (!$start && !$end) {
                   4179:         return 'ok';
                   4180:     }
                   4181:     if (grep/^active$/,@{$status}) {
                   4182:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4183:             return 'ok';
                   4184:         }
                   4185:     }
                   4186:     if (grep/^previous$/,@{$status}) {
                   4187:         if ($end > $now ) {
                   4188:             return 'ok';
                   4189:         }
                   4190:     }
                   4191:     if (grep/^future$/,@{$status}) {
                   4192:         if ($start > $now) {
                   4193:             return 'ok';
                   4194:         }
                   4195:     }
                   4196:     return; 
                   4197: }
                   4198: 
                   4199: sub parse_portfolio_url {
                   4200:     my ($url) = @_;
                   4201: 
                   4202:     my ($type,$udom,$unum,$group,$file_name);
                   4203:     
1.823     albertel 4204:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4205: 	$type = 1;
                   4206:         $udom = $1;
                   4207:         $unum = $2;
                   4208:         $file_name = $3;
1.823     albertel 4209:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4210: 	$type = 2;
                   4211:         $udom = $1;
                   4212:         $unum = $2;
                   4213:         $group = $3;
                   4214:         $file_name = $3.'/'.$4;
                   4215:     }
                   4216:     if (wantarray) {
                   4217: 	return ($type,$udom,$unum,$file_name,$group);
                   4218:     }
                   4219:     return $type;
                   4220: }
                   4221: 
                   4222: sub is_portfolio_url {
                   4223:     my ($url) = @_;
                   4224:     return scalar(&parse_portfolio_url($url));
                   4225: }
                   4226: 
1.798     raeburn  4227: sub is_portfolio_file {
                   4228:     my ($file) = @_;
1.820     raeburn  4229:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4230:         return 1;
                   4231:     }
                   4232:     return;
                   4233: }
                   4234: 
                   4235: 
1.341     www      4236: # ---------------------------------------------- Custom access rule evaluation
                   4237: 
                   4238: sub customaccess {
                   4239:     my ($priv,$uri)=@_;
1.807     albertel 4240:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4241:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4242:     $udom = &LONCAPA::clean_domain($udom);
                   4243:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4244:     my $access=0;
1.800     albertel 4245:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4246: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4247: 	if ($type eq 'user') {
                   4248: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4249: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4250: 		if ($tdom) {
                   4251: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4252: 		}
1.896     albertel 4253: 		if ($tuname) {
                   4254: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4255: 		}
                   4256: 		$access=($effect eq 'allow');
                   4257: 		last;
                   4258: 	    }
                   4259: 	} else {
                   4260: 	    if ($role) {
                   4261: 		if ($role ne $urole) { next; }
                   4262: 	    }
                   4263: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4264: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4265: 		if ($tdom) {
                   4266: 		    if ($tdom ne $udom) { next; }
                   4267: 		}
                   4268: 		if ($tcrs) {
                   4269: 		    if ($tcrs ne $ucrs) { next; }
                   4270: 		}
                   4271: 		if ($tsec) {
                   4272: 		    if ($tsec ne $usec) { next; }
                   4273: 		}
                   4274: 		$access=($effect eq 'allow');
                   4275: 		last;
                   4276: 	    }
                   4277: 	    if ($realm eq '' && $role eq '') {
                   4278: 		$access=($effect eq 'allow');
                   4279: 	    }
1.402     bowersj2 4280: 	}
1.341     www      4281:     }
                   4282:     return $access;
                   4283: }
                   4284: 
1.103     harris41 4285: # ------------------------------------------------- Check for a user privilege
1.12      www      4286: 
                   4287: sub allowed {
1.810     raeburn  4288:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4289:     my $ver_orguri=$uri;
1.439     www      4290:     $uri=&deversion($uri);
1.152     www      4291:     my $orguri=$uri;
1.52      www      4292:     $uri=&declutter($uri);
1.809     raeburn  4293: 
1.810     raeburn  4294:     if ($priv eq 'evb') {
                   4295: # Evade communication block restrictions for specified role in a course
                   4296:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4297:             return $1;
                   4298:         } else {
                   4299:             return;
                   4300:         }
                   4301:     }
                   4302: 
1.620     albertel 4303:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4304: # Free bre access to adm and meta resources
1.775     albertel 4305:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4306: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4307: 	&& ($priv eq 'bre')) {
1.14      www      4308: 	return 'F';
1.159     www      4309:     }
                   4310: 
1.545     banghart 4311: # Free bre access to user's own portfolio contents
1.714     raeburn  4312:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4313:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4314: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4315:         my %setters;
                   4316:         my ($startblock,$endblock) = 
                   4317:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4318:         if ($startblock && $endblock) {
                   4319:             return 'B';
                   4320:         } else {
                   4321:             return 'F';
                   4322:         }
1.545     banghart 4323:     }
                   4324: 
1.762     raeburn  4325: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4326:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4327:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4328:         if (exists($env{'request.course.id'})) {
                   4329:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4330:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4331:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4332:                 my $courseprivid=$env{'request.course.id'};
                   4333:                 $courseprivid=~s/\_/\//;
                   4334:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4335:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4336:                     return $1; 
1.762     raeburn  4337:                 } else {
                   4338:                     if ($env{'request.course.sec'}) {
                   4339:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4340:                     }
                   4341:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4342:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4343:                         return $2;
                   4344:                     }
1.714     raeburn  4345:                 }
                   4346:             }
                   4347:         }
                   4348:     }
                   4349: 
1.159     www      4350: # Free bre to public access
                   4351: 
                   4352:     if ($priv eq 'bre') {
1.238     www      4353:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4354: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4355:            return 'F'; 
                   4356:         }
1.238     www      4357:         if ($copyright eq 'priv') {
                   4358:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4359: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4360: 		return '';
                   4361:             }
                   4362:         }
                   4363:         if ($copyright eq 'domain') {
                   4364:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4365: 	    unless (($env{'user.domain'} eq $1) ||
                   4366:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4367: 		return '';
                   4368:             }
1.262     matthew  4369:         }
1.620     albertel 4370:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4371:             # Library role, so allow browsing of resources in this domain.
                   4372:             return 'F';
1.238     www      4373:         }
1.341     www      4374:         if ($copyright eq 'custom') {
                   4375: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4376:         }
1.14      www      4377:     }
1.264     matthew  4378:     # Domain coordinator is trying to create a course
1.620     albertel 4379:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4380:         # uri is the requested domain in this case.
                   4381:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4382:         # a role of dc for the domain in question.
1.620     albertel 4383:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4384:     }
1.29      www      4385: 
1.52      www      4386:     my $thisallowed='';
                   4387:     my $statecond=0;
                   4388:     my $courseprivid='';
                   4389: 
                   4390: # Course
                   4391: 
1.620     albertel 4392:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4393:        $thisallowed.=$1;
                   4394:     }
1.29      www      4395: 
1.52      www      4396: # Domain
                   4397: 
1.620     albertel 4398:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4399:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4400:        $thisallowed.=$1;
                   4401:     }
1.52      www      4402: 
                   4403: # Course: uri itself is a course
1.66      www      4404:     my $courseuri=$uri;
                   4405:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4406:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4407: 
1.620     albertel 4408:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4409:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4410:        $thisallowed.=$1;
                   4411:     }
1.29      www      4412: 
1.665     albertel 4413: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4414: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4415:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4416: 	$thisallowed='';
1.671     raeburn  4417:         my ($match)=&is_on_map($uri);
                   4418:         if ($match) {
                   4419:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4420:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4421:                 $thisallowed.=$1;
                   4422:             }
                   4423:         } else {
1.705     albertel 4424:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4425:             if ($refuri) {
                   4426:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4427:                     $thisallowed='F';
1.671     raeburn  4428:                 } else {
                   4429:                     $refuri=&declutter($refuri);
                   4430:                     my ($match) = &is_on_map($refuri);
                   4431:                     if ($match) {
                   4432:                         $thisallowed='F';
                   4433:                     }
1.669     raeburn  4434:                 }
1.671     raeburn  4435:             }
                   4436:         }
1.314     www      4437:     }
1.492     albertel 4438: 
1.766     albertel 4439:     if ($priv eq 'bre'
                   4440: 	&& $thisallowed ne 'F' 
                   4441: 	&& $thisallowed ne '2'
                   4442: 	&& &is_portfolio_url($uri)) {
                   4443: 	$thisallowed = &portfolio_access($uri);
                   4444:     }
                   4445:     
1.52      www      4446: # Full access at system, domain or course-wide level? Exit.
1.29      www      4447: 
                   4448:     if ($thisallowed=~/F/) {
                   4449: 	return 'F';
                   4450:     }
                   4451: 
1.52      www      4452: # If this is generating or modifying users, exit with special codes
1.29      www      4453: 
1.643     www      4454:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4455: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4456: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4457: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4458: 	    unless ($auname) { return $thisallowed; }
                   4459: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4460: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4461: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4462: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4463: 	}
1.52      www      4464: 	return $thisallowed;
                   4465:     }
                   4466: #
1.103     harris41 4467: # Gathered so far: system, domain and course wide privileges
1.52      www      4468: #
                   4469: # Course: See if uri or referer is an individual resource that is part of 
                   4470: # the course
                   4471: 
1.620     albertel 4472:     if ($env{'request.course.id'}) {
1.232     www      4473: 
1.620     albertel 4474:        $courseprivid=$env{'request.course.id'};
                   4475:        if ($env{'request.course.sec'}) {
                   4476:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4477:        }
                   4478:        $courseprivid=~s/\_/\//;
                   4479:        my $checkreferer=1;
1.232     www      4480:        my ($match,$cond)=&is_on_map($uri);
                   4481:        if ($match) {
                   4482:            $statecond=$cond;
1.620     albertel 4483:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4484:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4485:                $thisallowed.=$1;
                   4486:                $checkreferer=0;
                   4487:            }
1.29      www      4488:        }
1.83      www      4489:        
1.148     www      4490:        if ($checkreferer) {
1.620     albertel 4491: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4492:             unless ($refuri) {
1.800     albertel 4493:                 foreach my $key (keys(%env)) {
                   4494: 		    if ($key=~/^httpref\..*\*/) {
                   4495: 			my $pattern=$key;
1.156     www      4496:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4497:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4498:                         $pattern=~s/\//\\\//g;
1.152     www      4499:                         if ($orguri=~/$pattern/) {
1.800     albertel 4500: 			    $refuri=$env{$key};
1.148     www      4501:                         }
                   4502:                     }
1.191     harris41 4503:                 }
1.148     www      4504:             }
1.232     www      4505: 
1.148     www      4506:          if ($refuri) { 
1.152     www      4507: 	  $refuri=&declutter($refuri);
1.232     www      4508:           my ($match,$cond)=&is_on_map($refuri);
                   4509:             if ($match) {
                   4510:               my $refstatecond=$cond;
1.620     albertel 4511:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4512:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4513:                   $thisallowed.=$1;
1.53      www      4514:                   $uri=$refuri;
                   4515:                   $statecond=$refstatecond;
1.52      www      4516:               }
                   4517:           }
1.148     www      4518:         }
1.29      www      4519:        }
1.52      www      4520:    }
1.29      www      4521: 
1.52      www      4522: #
1.103     harris41 4523: # Gathered now: all privileges that could apply, and condition number
1.52      www      4524: # 
                   4525: #
                   4526: # Full or no access?
                   4527: #
1.29      www      4528: 
1.52      www      4529:     if ($thisallowed=~/F/) {
                   4530: 	return 'F';
                   4531:     }
1.29      www      4532: 
1.52      www      4533:     unless ($thisallowed) {
                   4534:         return '';
                   4535:     }
1.29      www      4536: 
1.52      www      4537: # Restrictions exist, deal with them
                   4538: #
                   4539: #   C:according to course preferences
                   4540: #   R:according to resource settings
                   4541: #   L:unless locked
                   4542: #   X:according to user session state
                   4543: #
                   4544: 
                   4545: # Possibly locked functionality, check all courses
1.54      www      4546: # Locks might take effect only after 10 minutes cache expiration for other
                   4547: # courses, and 2 minutes for current course
1.52      www      4548: 
                   4549:     my $envkey;
                   4550:     if ($thisallowed=~/L/) {
1.620     albertel 4551:         foreach $envkey (keys %env) {
1.54      www      4552:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4553:                my $courseid=$2;
                   4554:                my $roleid=$1.'.'.$2;
1.92      www      4555:                $courseid=~s/^\///;
1.54      www      4556:                my $expiretime=600;
1.620     albertel 4557:                if ($env{'request.role'} eq $roleid) {
1.54      www      4558: 		  $expiretime=120;
                   4559:                }
                   4560: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4561:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4562:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4563: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4564:                }
1.620     albertel 4565:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4566:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4567: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4568:                        &log($env{'user.domain'},$env{'user.name'},
                   4569:                             $env{'user.home'},
1.57      www      4570:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4571:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4572:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4573: 		       return '';
                   4574:                    }
                   4575:                }
1.620     albertel 4576:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4577:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4578: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4579:                        &log($env{'user.domain'},$env{'user.name'},
                   4580:                             $env{'user.home'},
1.57      www      4581:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4582:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4583:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4584: 		       return '';
                   4585:                    }
                   4586:                }
                   4587: 	   }
1.29      www      4588:        }
1.52      www      4589:     }
                   4590:    
                   4591: #
                   4592: # Rest of the restrictions depend on selected course
                   4593: #
                   4594: 
1.620     albertel 4595:     unless ($env{'request.course.id'}) {
1.766     albertel 4596: 	if ($thisallowed eq 'A') {
                   4597: 	    return 'A';
1.814     raeburn  4598:         } elsif ($thisallowed eq 'B') {
                   4599:             return 'B';
1.766     albertel 4600: 	} else {
                   4601: 	    return '1';
                   4602: 	}
1.52      www      4603:     }
1.29      www      4604: 
1.52      www      4605: #
                   4606: # Now user is definitely in a course
                   4607: #
1.53      www      4608: 
                   4609: 
                   4610: # Course preferences
                   4611: 
                   4612:    if ($thisallowed=~/C/) {
1.620     albertel 4613:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4614:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4615:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4616: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4617: 	   if ($priv ne 'pch') { 
                   4618: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4619: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4620: 			$env{'request.course.id'});
                   4621: 	   }
1.237     www      4622:            return '';
                   4623:        }
                   4624: 
1.620     albertel 4625:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4626: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4627: 	   if ($priv ne 'pch') { 
                   4628: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4629: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4630: 			$env{'request.course.id'});
                   4631: 	   }
1.54      www      4632:            return '';
                   4633:        }
1.53      www      4634:    }
                   4635: 
                   4636: # Resource preferences
                   4637: 
                   4638:    if ($thisallowed=~/R/) {
1.620     albertel 4639:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4640:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4641: 	   if ($priv ne 'pch') { 
                   4642: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4643: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4644: 	   }
                   4645: 	   return '';
1.54      www      4646:        }
1.53      www      4647:    }
1.30      www      4648: 
1.246     www      4649: # Restricted by state or randomout?
1.30      www      4650: 
1.52      www      4651:    if ($thisallowed=~/X/) {
1.620     albertel 4652:       if ($env{'acc.randomout'}) {
1.579     albertel 4653: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4654:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4655:             return ''; 
                   4656:          }
1.247     www      4657:       }
                   4658:       if (&condval($statecond)) {
1.52      www      4659: 	 return '2';
                   4660:       } else {
                   4661:          return '';
                   4662:       }
                   4663:    }
1.30      www      4664: 
1.766     albertel 4665:     if ($thisallowed eq 'A') {
                   4666: 	return 'A';
1.814     raeburn  4667:     } elsif ($thisallowed eq 'B') {
                   4668:         return 'B';
1.766     albertel 4669:     }
1.52      www      4670:    return 'F';
1.232     www      4671: }
                   4672: 
1.710     albertel 4673: sub split_uri_for_cond {
                   4674:     my $uri=&deversion(&declutter(shift));
                   4675:     my @uriparts=split(/\//,$uri);
                   4676:     my $filename=pop(@uriparts);
                   4677:     my $pathname=join('/',@uriparts);
                   4678:     return ($pathname,$filename);
                   4679: }
1.232     www      4680: # --------------------------------------------------- Is a resource on the map?
                   4681: 
                   4682: sub is_on_map {
1.710     albertel 4683:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4684:     #Trying to find the conditional for the file
1.620     albertel 4685:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4686: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4687:     if ($match) {
1.289     bowersj2 4688: 	return (1,$1);
                   4689:     } else {
1.434     www      4690: 	return (0,0);
1.289     bowersj2 4691:     }
1.12      www      4692: }
                   4693: 
1.427     www      4694: # --------------------------------------------------------- Get symb from alias
                   4695: 
                   4696: sub get_symb_from_alias {
                   4697:     my $symb=shift;
                   4698:     my ($map,$resid,$url)=&decode_symb($symb);
                   4699: # Already is a symb
                   4700:     if ($url) { return $symb; }
                   4701: # Must be an alias
                   4702:     my $aliassymb='';
                   4703:     my %bighash;
1.620     albertel 4704:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4705:                             &GDBM_READER(),0640)) {
                   4706:         my $rid=$bighash{'mapalias_'.$symb};
                   4707: 	if ($rid) {
                   4708: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4709: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4710: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4711: 	}
                   4712:         untie %bighash;
                   4713:     }
                   4714:     return $aliassymb;
                   4715: }
                   4716: 
1.12      www      4717: # ----------------------------------------------------------------- Define Role
                   4718: 
                   4719: sub definerole {
                   4720:   if (allowed('mcr','/')) {
                   4721:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4722:     foreach my $role (split(':',$sysrole)) {
                   4723: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4724:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4725:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4726: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4727:                return "refused:s:$crole&$cqual"; 
                   4728:             }
                   4729:         }
1.191     harris41 4730:     }
1.800     albertel 4731:     foreach my $role (split(':',$domrole)) {
                   4732: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4733:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4734:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4735: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4736:                return "refused:d:$crole&$cqual"; 
                   4737:             }
                   4738:         }
1.191     harris41 4739:     }
1.800     albertel 4740:     foreach my $role (split(':',$courole)) {
                   4741: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4742:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4743:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4744: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4745:                return "refused:c:$crole&$cqual"; 
                   4746:             }
                   4747:         }
1.191     harris41 4748:     }
1.620     albertel 4749:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4750:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4751: 	        "rolesdef_$rolename=".
                   4752:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4753:     return reply($command,$env{'user.home'});
1.12      www      4754:   } else {
                   4755:     return 'refused';
                   4756:   }
1.105     harris41 4757: }
                   4758: 
                   4759: # ---------------- Make a metadata query against the network of library servers
                   4760: 
                   4761: sub metadata_query {
1.244     matthew  4762:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4763:     my %rhash;
1.845     albertel 4764:     my %libserv = &all_library();
1.244     matthew  4765:     my @server_list = (defined($server_array) ? @$server_array
                   4766:                                               : keys(%libserv) );
                   4767:     for my $server (@server_list) {
1.118     harris41 4768: 	unless ($custom or $customshow) {
                   4769: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4770: 	    $rhash{$server}=$reply;
                   4771: 	}
                   4772: 	else {
                   4773: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4774: 			     &escape($custom).':'.&escape($customshow),
                   4775: 			     $server);
                   4776: 	    $rhash{$server}=$reply;
                   4777: 	}
1.112     harris41 4778:     }
1.118     harris41 4779:     return \%rhash;
1.240     www      4780: }
                   4781: 
                   4782: # ----------------------------------------- Send log queries and wait for reply
                   4783: 
                   4784: sub log_query {
                   4785:     my ($uname,$udom,$query,%filters)=@_;
                   4786:     my $uhome=&homeserver($uname,$udom);
                   4787:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4788:     my $uhost=&hostname($uhome);
1.800     albertel 4789:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4790:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4791:                        $uhome);
1.479     albertel 4792:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4793:     return get_query_reply($queryid);
                   4794: }
                   4795: 
1.818     raeburn  4796: # -------------------------- Update MySQL table for portfolio file
                   4797: 
                   4798: sub update_portfolio_table {
1.821     raeburn  4799:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4800:     my $homeserver = &homeserver($uname,$udom);
                   4801:     my $queryid=
1.821     raeburn  4802:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4803:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4804:     my $reply = &get_query_reply($queryid);
                   4805:     return $reply;
                   4806: }
                   4807: 
1.899     raeburn  4808: # -------------------------- Update MySQL allusers table
                   4809: 
                   4810: sub update_allusers_table {
                   4811:     my ($uname,$udom,$names) = @_;
                   4812:     my $homeserver = &homeserver($uname,$udom);
                   4813:     my $queryid=
                   4814:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4815:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4816:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4817:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4818:                'generation='.&escape($names->{'generation'}).'%%'.
                   4819:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4820:                'id='.&escape($names->{'id'}),$homeserver);
                   4821:     my $reply = &get_query_reply($queryid);
                   4822:     return $reply;
                   4823: }
                   4824: 
1.508     raeburn  4825: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4826: 
                   4827: sub fetch_enrollment_query {
1.511     raeburn  4828:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4829:     my $homeserver;
1.547     raeburn  4830:     my $maxtries = 1;
1.508     raeburn  4831:     if ($context eq 'automated') {
                   4832:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4833:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4834:     } else {
                   4835:         $homeserver = &homeserver($cnum,$dom);
                   4836:     }
1.838     albertel 4837:     my $host=&hostname($homeserver);
1.506     raeburn  4838:     my $cmd = '';
1.800     albertel 4839:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4840:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4841:     }
                   4842:     $cmd =~ s/%%$//;
                   4843:     $cmd = &escape($cmd);
                   4844:     my $query = 'fetchenrollment';
1.620     albertel 4845:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4846:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4847:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4848:         return 'error: '.$queryid;
                   4849:     }
1.506     raeburn  4850:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4851:     my $tries = 1;
                   4852:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4853:         $reply = &get_query_reply($queryid);
                   4854:         $tries ++;
                   4855:     }
1.526     raeburn  4856:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4857:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4858:     } else {
1.901     albertel 4859:         my @responses = split(/:/,$reply);
1.515     raeburn  4860:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4861:             foreach my $line (@responses) {
                   4862:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4863:                 $$replyref{$key} = $value;
                   4864:             }
                   4865:         } else {
1.506     raeburn  4866:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4867:             foreach my $line (@responses) {
                   4868:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4869:                 $$replyref{$key} = $value;
                   4870:                 if ($value > 0) {
1.800     albertel 4871:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4872:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4873:                         my $destname = $pathname.'/'.$filename;
                   4874:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4875:                         if ($xml_classlist =~ /^error/) {
                   4876:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4877:                         } else {
1.506     raeburn  4878:                             if ( open(FILE,">$destname") ) {
                   4879:                                 print FILE &unescape($xml_classlist);
                   4880:                                 close(FILE);
1.526     raeburn  4881:                             } else {
                   4882:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4883:                             }
                   4884:                         }
                   4885:                     }
                   4886:                 }
                   4887:             }
                   4888:         }
                   4889:         return 'ok';
                   4890:     }
                   4891:     return 'error';
                   4892: }
                   4893: 
1.242     www      4894: sub get_query_reply {
                   4895:     my $queryid=shift;
1.240     www      4896:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4897:     my $reply='';
                   4898:     for (1..100) {
                   4899: 	sleep 2;
                   4900:         if (-e $replyfile.'.end') {
1.448     albertel 4901: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4902: 		$reply = join('',<$fh>);
                   4903: 		close($fh);
1.240     www      4904: 	   } else { return 'error: reply_file_error'; }
1.242     www      4905:            return &unescape($reply);
                   4906: 	}
1.240     www      4907:     }
1.242     www      4908:     return 'timeout:'.$queryid;
1.240     www      4909: }
                   4910: 
                   4911: sub courselog_query {
1.241     www      4912: #
                   4913: # possible filters:
                   4914: # url: url or symb
                   4915: # username
                   4916: # domain
                   4917: # action: view, submit, grade
                   4918: # start: timestamp
                   4919: # end: timestamp
                   4920: #
1.240     www      4921:     my (%filters)=@_;
1.620     albertel 4922:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4923:     if ($filters{'url'}) {
                   4924: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4925:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4926:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4927:     }
1.620     albertel 4928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4930:     return &log_query($cname,$cdom,'courselog',%filters);
                   4931: }
                   4932: 
                   4933: sub userlog_query {
1.858     raeburn  4934: #
                   4935: # possible filters:
                   4936: # action: log check role
                   4937: # start: timestamp
                   4938: # end: timestamp
                   4939: #
1.240     www      4940:     my ($uname,$udom,%filters)=@_;
                   4941:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4942: }
                   4943: 
1.506     raeburn  4944: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4945: 
                   4946: sub auto_run {
1.508     raeburn  4947:     my ($cnum,$cdom) = @_;
1.876     raeburn  4948:     my $response = 0;
                   4949:     my $settings;
                   4950:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4951:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4952:         $settings = $domconfig{'autoenroll'};
                   4953:         if ($settings->{'run'} eq '1') {
                   4954:             $response = 1;
                   4955:         }
                   4956:     } else {
1.934     raeburn  4957:         my $homeserver;
                   4958:         if (&is_course($cdom,$cnum)) {
                   4959:             $homeserver = &homeserver($cnum,$cdom);
                   4960:         } else {
                   4961:             $homeserver = &domain($cdom,'primary');
                   4962:         }
                   4963:         if ($homeserver ne 'no_host') {
                   4964:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4965:         }
1.876     raeburn  4966:     }
1.506     raeburn  4967:     return $response;
                   4968: }
1.776     albertel 4969: 
1.506     raeburn  4970: sub auto_get_sections {
1.508     raeburn  4971:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4972:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4973:     my @secs = ();
1.511     raeburn  4974:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4975:     unless ($response eq 'refused') {
1.901     albertel 4976:         @secs = split(/:/,$response);
1.506     raeburn  4977:     }
                   4978:     return @secs;
                   4979: }
1.776     albertel 4980: 
1.506     raeburn  4981: sub auto_new_course {
1.508     raeburn  4982:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4983:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4984:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4985:     return $response;
                   4986: }
1.776     albertel 4987: 
1.506     raeburn  4988: sub auto_validate_courseID {
1.508     raeburn  4989:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4990:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4991:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4992:     return $response;
                   4993: }
1.776     albertel 4994: 
1.506     raeburn  4995: sub auto_create_password {
1.873     raeburn  4996:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4997:     my ($homeserver,$response);
1.506     raeburn  4998:     my $create_passwd = 0;
                   4999:     my $authchk = '';
1.873     raeburn  5000:     if ($udom =~ /^$match_domain$/) {
                   5001:         $homeserver = &domain($udom,'primary');
                   5002:     }
                   5003:     if ($homeserver eq '') {
                   5004:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5005:             $homeserver = &homeserver($cnum,$cdom);
                   5006:         }
                   5007:     }
                   5008:     if ($homeserver eq '') {
                   5009:         $authchk = 'nodomain';
1.506     raeburn  5010:     } else {
1.873     raeburn  5011:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5012:         if ($response eq 'refused') {
                   5013:             $authchk = 'refused';
                   5014:         } else {
1.901     albertel 5015:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5016:         }
1.506     raeburn  5017:     }
                   5018:     return ($authparam,$create_passwd,$authchk);
                   5019: }
                   5020: 
1.706     raeburn  5021: sub auto_photo_permission {
                   5022:     my ($cnum,$cdom,$students) = @_;
                   5023:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5024:     my ($outcome,$perm_reqd,$conditions) = 
                   5025: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5026:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5027: 	return (undef,undef);
                   5028:     }
1.706     raeburn  5029:     return ($outcome,$perm_reqd,$conditions);
                   5030: }
                   5031: 
                   5032: sub auto_checkphotos {
                   5033:     my ($uname,$udom,$pid) = @_;
                   5034:     my $homeserver = &homeserver($uname,$udom);
                   5035:     my ($result,$resulttype);
                   5036:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5037: 				   &escape($uname).':'.&escape($pid),
                   5038: 				   $homeserver));
1.709     albertel 5039:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5040: 	return (undef,undef);
                   5041:     }
1.706     raeburn  5042:     if ($outcome) {
                   5043:         ($result,$resulttype) = split(/:/,$outcome);
                   5044:     } 
                   5045:     return ($result,$resulttype);
                   5046: }
                   5047: 
                   5048: sub auto_photochoice {
                   5049:     my ($cnum,$cdom) = @_;
                   5050:     my $homeserver = &homeserver($cnum,$cdom);
                   5051:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5052: 						       &escape($cdom),
                   5053: 						       $homeserver)));
1.709     albertel 5054:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5055: 	return (undef,undef);
                   5056:     }
1.706     raeburn  5057:     return ($update,$comment);
                   5058: }
                   5059: 
                   5060: sub auto_photoupdate {
                   5061:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5062:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5063:     my $host=&hostname($homeserver);
1.706     raeburn  5064:     my $cmd = '';
                   5065:     my $maxtries = 1;
1.800     albertel 5066:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5067:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5068:     }
                   5069:     $cmd =~ s/%%$//;
                   5070:     $cmd = &escape($cmd);
                   5071:     my $query = 'institutionalphotos';
                   5072:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5073:     unless ($queryid=~/^\Q$host\E\_/) {
                   5074:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5075:         return 'error: '.$queryid;
                   5076:     }
                   5077:     my $reply = &get_query_reply($queryid);
                   5078:     my $tries = 1;
                   5079:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5080:         $reply = &get_query_reply($queryid);
                   5081:         $tries ++;
                   5082:     }
                   5083:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5084:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5085:     } else {
                   5086:         my @responses = split(/:/,$reply);
                   5087:         my $outcome = shift(@responses); 
                   5088:         foreach my $item (@responses) {
                   5089:             my ($key,$value) = split(/=/,$item);
                   5090:             $$photo{$key} = $value;
                   5091:         }
                   5092:         return $outcome;
                   5093:     }
                   5094:     return 'error';
                   5095: }
                   5096: 
1.521     raeburn  5097: sub auto_instcode_format {
1.793     albertel 5098:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5099: 	$cat_order) = @_;
1.521     raeburn  5100:     my $courses = '';
1.772     raeburn  5101:     my @homeservers;
1.521     raeburn  5102:     if ($caller eq 'global') {
1.841     albertel 5103: 	my %servers = &get_servers($codedom,'library');
                   5104: 	foreach my $tryserver (keys(%servers)) {
                   5105: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5106: 		push(@homeservers,$tryserver);
                   5107: 	    }
1.584     raeburn  5108:         }
1.521     raeburn  5109:     } else {
1.772     raeburn  5110:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5111:     }
1.793     albertel 5112:     foreach my $code (keys(%{$instcodes})) {
                   5113:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5114:     }
                   5115:     chop($courses);
1.772     raeburn  5116:     my $ok_response = 0;
                   5117:     my $response;
                   5118:     while (@homeservers > 0 && $ok_response == 0) {
                   5119:         my $server = shift(@homeservers); 
                   5120:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5121:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5122:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5123: 		split(/:/,$response);
1.772     raeburn  5124:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5125:             push(@{$codetitles},&str2array($codetitles_str));
                   5126:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5127:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5128:             $ok_response = 1;
                   5129:         }
                   5130:     }
                   5131:     if ($ok_response) {
1.521     raeburn  5132:         return 'ok';
1.772     raeburn  5133:     } else {
                   5134:         return $response;
1.521     raeburn  5135:     }
                   5136: }
                   5137: 
1.792     raeburn  5138: sub auto_instcode_defaults {
                   5139:     my ($domain,$returnhash,$code_order) = @_;
                   5140:     my @homeservers;
1.841     albertel 5141: 
                   5142:     my %servers = &get_servers($domain,'library');
                   5143:     foreach my $tryserver (keys(%servers)) {
                   5144: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5145: 	    push(@homeservers,$tryserver);
                   5146: 	}
1.792     raeburn  5147:     }
1.841     albertel 5148: 
1.792     raeburn  5149:     my $response;
1.841     albertel 5150:     foreach my $server (@homeservers) {
1.792     raeburn  5151:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5152:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5153: 	
                   5154: 	foreach my $pair (split(/\&/,$response)) {
                   5155: 	    my ($name,$value)=split(/\=/,$pair);
                   5156: 	    if ($name eq 'code_order') {
                   5157: 		@{$code_order} = split(/\&/,&unescape($value));
                   5158: 	    } else {
                   5159: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5160: 	    }
                   5161: 	}
                   5162: 	return 'ok';
1.792     raeburn  5163:     }
1.841     albertel 5164: 
                   5165:     return $response;
1.792     raeburn  5166: } 
                   5167: 
1.777     albertel 5168: sub auto_validate_class_sec {
1.918     raeburn  5169:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5170:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5171:     my $ownerlist;
                   5172:     if (ref($owners) eq 'ARRAY') {
                   5173:         $ownerlist = join(',',@{$owners});
                   5174:     } else {
                   5175:         $ownerlist = $owners;
                   5176:     }
1.773     raeburn  5177:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5178:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5179:     return $response;
                   5180: }
                   5181: 
1.679     raeburn  5182: # ------------------------------------------------------- Course Group routines
                   5183: 
                   5184: sub get_coursegroups {
1.809     raeburn  5185:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5186:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5187: }
                   5188: 
1.679     raeburn  5189: sub modify_coursegroup {
                   5190:     my ($cdom,$cnum,$groupsettings) = @_;
                   5191:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5192: }
                   5193: 
1.809     raeburn  5194: sub toggle_coursegroup_status {
                   5195:     my ($cdom,$cnum,$group,$action) = @_;
                   5196:     my ($from_namespace,$to_namespace);
                   5197:     if ($action eq 'delete') {
                   5198:         $from_namespace = 'coursegroups';
                   5199:         $to_namespace = 'deleted_groups';
                   5200:     } else {
                   5201:         $from_namespace = 'deleted_groups';
                   5202:         $to_namespace = 'coursegroups';
                   5203:     }
                   5204:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5205:     if (my $tmp = &error(%curr_group)) {
                   5206:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5207:         return ('read error',$tmp);
                   5208:     } else {
                   5209:         my %savedsettings = %curr_group; 
1.809     raeburn  5210:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5211:         my $deloutcome;
                   5212:         if ($result eq 'ok') {
1.809     raeburn  5213:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5214:         } else {
                   5215:             return ('write error',$result);
                   5216:         }
                   5217:         if ($deloutcome eq 'ok') {
                   5218:             return 'ok';
                   5219:         } else {
                   5220:             return ('delete error',$deloutcome);
                   5221:         }
                   5222:     }
                   5223: }
                   5224: 
1.679     raeburn  5225: sub modify_group_roles {
                   5226:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5227:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5228:     my $role = 'gr/'.&escape($userprivs);
                   5229:     my ($uname,$udom) = split(/:/,$user);
                   5230:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5231:     if ($result eq 'ok') {
                   5232:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5233:     }
1.679     raeburn  5234:     return $result;
                   5235: }
                   5236: 
                   5237: sub modify_coursegroup_membership {
                   5238:     my ($cdom,$cnum,$membership) = @_;
                   5239:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5240:     return $result;
                   5241: }
                   5242: 
1.682     raeburn  5243: sub get_active_groups {
                   5244:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5245:     my $now = time;
                   5246:     my %groups = ();
                   5247:     foreach my $key (keys(%env)) {
1.811     albertel 5248:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5249:             my ($start,$end) = split(/\./,$env{$key});
                   5250:             if (($end!=0) && ($end<$now)) { next; }
                   5251:             if (($start!=0) && ($start>$now)) { next; }
                   5252:             if ($1 eq $cdom && $2 eq $cnum) {
                   5253:                 $groups{$3} = $env{$key} ;
                   5254:             }
                   5255:         }
                   5256:     }
                   5257:     return %groups;
                   5258: }
                   5259: 
1.683     raeburn  5260: sub get_group_membership {
                   5261:     my ($cdom,$cnum,$group) = @_;
                   5262:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5263: }
                   5264: 
                   5265: sub get_users_groups {
                   5266:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5267:     my @usersgroups;
1.683     raeburn  5268:     my $cachetime=1800;
                   5269: 
                   5270:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5271:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5272:     if (defined($cached)) {
1.734     albertel 5273:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5274:     } else {  
                   5275:         $grouplist = '';
1.816     raeburn  5276:         my $courseurl = &courseid_to_courseurl($courseid);
                   5277:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5278:         my $access_end = $env{'course.'.$courseid.
                   5279:                               '.default_enrollment_end_date'};
                   5280:         my $now = time;
                   5281:         foreach my $key (keys(%roleshash)) {
                   5282:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5283:                 my $group = $1;
                   5284:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5285:                     my $start = $2;
                   5286:                     my $end = $1;
                   5287:                     if ($start == -1) { next; } # deleted from group
                   5288:                     if (($start!=0) && ($start>$now)) { next; }
                   5289:                     if (($end!=0) && ($end<$now)) {
                   5290:                         if ($access_end && $access_end < $now) {
                   5291:                             if ($access_end - $end < 86400) {
                   5292:                                 push(@usersgroups,$group);
1.733     raeburn  5293:                             }
                   5294:                         }
1.817     raeburn  5295:                         next;
1.733     raeburn  5296:                     }
1.817     raeburn  5297:                     push(@usersgroups,$group);
1.683     raeburn  5298:                 }
                   5299:             }
                   5300:         }
1.817     raeburn  5301:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5302:         $grouplist = join(':',@usersgroups);
                   5303:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5304:     }
1.733     raeburn  5305:     return @usersgroups;
1.683     raeburn  5306: }
                   5307: 
                   5308: sub devalidate_getgroups_cache {
                   5309:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5310:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5311: 
1.683     raeburn  5312:     my $hashid="$udom:$uname:$courseid";
                   5313:     &devalidate_cache_new('getgroups',$hashid);
                   5314: }
                   5315: 
1.12      www      5316: # ------------------------------------------------------------------ Plain Text
                   5317: 
                   5318: sub plaintext {
1.742     raeburn  5319:     my ($short,$type,$cid) = @_;
1.758     albertel 5320:     if ($short =~ /^cr/) {
                   5321: 	return (split('/',$short))[-1];
                   5322:     }
1.742     raeburn  5323:     if (!defined($cid)) {
                   5324:         $cid = $env{'request.course.id'};
                   5325:     }
                   5326:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5327:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5328:                                           '.plaintext'});
                   5329:     }
                   5330:     my %rolenames = (
                   5331:                       Course => 'std',
                   5332:                       Group => 'alt1',
                   5333:                     );
                   5334:     if (defined($type) && 
                   5335:          defined($rolenames{$type}) && 
                   5336:          defined($prp{$short}{$rolenames{$type}})) {
                   5337:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5338:     } else {
                   5339:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5340:     }
1.12      www      5341: }
                   5342: 
                   5343: # ----------------------------------------------------------------- Assign Role
                   5344: 
                   5345: sub assignrole {
1.947     raeburn  5346:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
1.21      www      5347:     my $mrole;
                   5348:     if ($role =~ /^cr\//) {
1.393     www      5349:         my $cwosec=$url;
1.811     albertel 5350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5351: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5352:            &logthis('Refused custom assignrole: '.
                   5353:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5354: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5355:            return 'refused'; 
                   5356:         }
1.21      www      5357:         $mrole='cr';
1.678     raeburn  5358:     } elsif ($role =~ /^gr\//) {
                   5359:         my $cwogrp=$url;
1.811     albertel 5360:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5361:         unless (&allowed('mdg',$cwogrp)) {
                   5362:             &logthis('Refused group assignrole: '.
                   5363:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5364:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5365:             return 'refused';
                   5366:         }
                   5367:         $mrole='gr';
1.21      www      5368:     } else {
1.82      www      5369:         my $cwosec=$url;
1.811     albertel 5370:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5371:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5372:             my $refused;
                   5373:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5374:                 if (!(&allowed('c'.$role,$url))) {
                   5375:                     $refused = 1;
                   5376:                 }
                   5377:             } else {
                   5378:                 $refused = 1;
                   5379:             }
1.947     raeburn  5380:             if ($refused) {
                   5381:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5382:                     $refused = '';
                   5383:                 } else {
                   5384:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5385:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5386: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5387:                     return 'refused';
                   5388:                 }
1.932     raeburn  5389:             }
1.104     www      5390:         }
1.21      www      5391:         $mrole=$role;
                   5392:     }
1.620     albertel 5393:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5394:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5395:     if ($end) { $command.='_'.$end; }
1.21      www      5396:     if ($start) {
                   5397: 	if ($end) { 
1.81      www      5398:            $command.='_'.$start; 
1.21      www      5399:         } else {
1.81      www      5400:            $command.='_0_'.$start;
1.21      www      5401:         }
                   5402:     }
1.739     raeburn  5403:     my $origstart = $start;
                   5404:     my $origend = $end;
1.357     www      5405: # actually delete
                   5406:     if ($deleteflag) {
1.373     www      5407: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5408: # modify command to delete the role
1.620     albertel 5409:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5410:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5411: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5412: # set start and finish to negative values for userrolelog
                   5413:            $start=-1;
                   5414:            $end=-1;
                   5415:         }
                   5416:     }
                   5417: # send command
1.349     www      5418:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5419: # log new user role if status is ok
1.349     www      5420:     if ($answer eq 'ok') {
1.663     raeburn  5421: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5422: # for course roles, perform group memberships changes triggered by role change.
                   5423:         unless ($role =~ /^gr/) {
                   5424:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5425:                                              $origstart);
                   5426:         }
1.349     www      5427:     }
                   5428:     return $answer;
1.169     harris41 5429: }
                   5430: 
                   5431: # -------------------------------------------------- Modify user authentication
1.197     www      5432: # Overrides without validation
                   5433: 
1.169     harris41 5434: sub modifyuserauth {
                   5435:     my ($udom,$uname,$umode,$upass)=@_;
                   5436:     my $uhome=&homeserver($uname,$udom);
1.197     www      5437:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5438:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5439:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5440:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5441:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5442: 		     &escape($upass),$uhome);
1.620     albertel 5443:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5444:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5445:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5446:     &log($udom,,$uname,$uhome,
1.620     albertel 5447:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5448:                                      $env{'user.name'}.', '.$umode.
1.197     www      5449:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5450:     unless ($reply eq 'ok') {
1.197     www      5451:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5452: 	return 'error: '.$reply;
                   5453:     }   
1.170     harris41 5454:     return 'ok';
1.80      www      5455: }
                   5456: 
1.81      www      5457: # --------------------------------------------------------------- Modify a user
1.80      www      5458: 
1.81      www      5459: sub modifyuser {
1.206     matthew  5460:     my ($udom,    $uname, $uid,
                   5461:         $umode,   $upass, $first,
                   5462:         $middle,  $last,  $gene,
1.387     www      5463:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5464:     $udom= &LONCAPA::clean_domain($udom);
                   5465:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5466:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5467:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5468: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5469:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5470:                                      ' desiredhome not specified'). 
1.620     albertel 5471:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5472:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5473:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5474: # ----------------------------------------------------------------- Create User
1.406     albertel 5475:     if (($uhome eq 'no_host') && 
                   5476: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5477:         my $unhome='';
1.844     albertel 5478:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5479:             $unhome = $desiredhome;
1.620     albertel 5480: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5481: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5482:         } else { # load balancing routine for determining $unhome
1.81      www      5483:             my $loadm=10000000;
1.841     albertel 5484: 	    my %servers = &get_servers($udom,'library');
                   5485: 	    foreach my $tryserver (keys(%servers)) {
                   5486: 		my $answer=reply('load',$tryserver);
                   5487: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5488: 		    $loadm=$answer;
                   5489: 		    $unhome=$tryserver;
                   5490: 		}
1.80      www      5491: 	    }
                   5492:         }
                   5493:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5494: 	    return 'error: unable to find a home server for '.$uname.
                   5495:                    ' in domain '.$udom;
1.80      www      5496:         }
                   5497:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5498:                          &escape($upass),$unhome);
                   5499: 	unless ($reply eq 'ok') {
                   5500:             return 'error: '.$reply;
                   5501:         }   
1.230     stredwic 5502:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5503:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5504: 	    return 'error: unable verify users home machine.';
1.80      www      5505:         }
1.209     matthew  5506:     }   # End of creation of new user
1.80      www      5507: # ---------------------------------------------------------------------- Add ID
                   5508:     if ($uid) {
                   5509:        $uid=~tr/A-Z/a-z/;
                   5510:        my %uidhash=&idrget($udom,$uname);
1.196     www      5511:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5512:          && (!$forceid)) {
1.80      www      5513: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5514: 	      return 'error: user id "'.$uid.'" does not match '.
                   5515:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5516:           }
                   5517:        } else {
                   5518: 	  &idput($udom,($uname => $uid));
                   5519:        }
                   5520:     }
                   5521: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5522:     my @tmp=&get('environment',
1.899     raeburn  5523: 		   ['firstname','middlename','lastname','generation','id',
                   5524:                     'permanentemail'],
1.134     albertel 5525: 		   $udom,$uname);
1.313     matthew  5526:     my %names;
                   5527:     if ($tmp[0] =~ m/^error:.*/) { 
                   5528:         %names=(); 
                   5529:     } else {
                   5530:         %names = @tmp;
                   5531:     }
1.388     www      5532: #
                   5533: # Make sure to not trash student environment if instructor does not bother
                   5534: # to supply name and email information
                   5535: #
                   5536:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5537:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5538:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5539:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5540:     if ($email) {
                   5541:        $email=~s/[^\w\@\.\-\,]//gs;
                   5542:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5543: 			   $names{'critnotification'} = $email;
                   5544: 			   $names{'permanentemail'} = $email; }
                   5545:     }
1.899     raeburn  5546:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5547:     my $reply = &put('environment', \%names, $udom,$uname);
                   5548:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5549:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5550:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5551:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5552:              $umode.', '.$first.', '.$middle.', '.
                   5553: 	     $last.', '.$gene.' by '.
1.620     albertel 5554:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5555:     return 'ok';
1.80      www      5556: }
                   5557: 
1.81      www      5558: # -------------------------------------------------------------- Modify student
1.80      www      5559: 
1.81      www      5560: sub modifystudent {
                   5561:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5562:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5563:     if (!$cid) {
1.620     albertel 5564: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5565: 	    return 'not_in_class';
                   5566: 	}
1.80      www      5567:     }
                   5568: # --------------------------------------------------------------- Make the user
1.81      www      5569:     my $reply=&modifyuser
1.209     matthew  5570: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5571:          $desiredhome,$email);
1.80      www      5572:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5573:     # This will cause &modify_student_enrollment to get the uid from the
                   5574:     # students environment
                   5575:     $uid = undef if (!$forceid);
1.455     albertel 5576:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5577: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5578:     return $reply;
                   5579: }
                   5580: 
                   5581: sub modify_student_enrollment {
1.947     raeburn  5582:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
1.455     albertel 5583:     my ($cdom,$cnum,$chome);
                   5584:     if (!$cid) {
1.620     albertel 5585: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5586: 	    return 'not_in_class';
                   5587: 	}
1.620     albertel 5588: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5589: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5590:     } else {
                   5591: 	($cdom,$cnum)=split(/_/,$cid);
                   5592:     }
1.620     albertel 5593:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5594:     if (!$chome) {
1.457     raeburn  5595: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5596:     }
1.455     albertel 5597:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5598:     # Make sure the user exists
1.81      www      5599:     my $uhome=&homeserver($uname,$udom);
                   5600:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5601: 	return 'error: no such user';
                   5602:     }
1.297     matthew  5603:     # Get student data if we were not given enough information
                   5604:     if (!defined($first)  || $first  eq '' || 
                   5605:         !defined($last)   || $last   eq '' || 
                   5606:         !defined($uid)    || $uid    eq '' || 
                   5607:         !defined($middle) || $middle eq '' || 
                   5608:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5609:         # They did not supply us with enough data to enroll the student, so
                   5610:         # we need to pick up more information.
1.297     matthew  5611:         my %tmp = &get('environment',
1.294     matthew  5612:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5613:                        ,$udom,$uname);
                   5614: 
1.800     albertel 5615:         #foreach my $key (keys(%tmp)) {
                   5616:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5617:         #}
1.294     matthew  5618:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5619:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5620:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5621:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5622:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5623:     }
1.556     albertel 5624:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5625:     my $reply=cput('classlist',
                   5626: 		   {"$uname:$udom" => 
1.515     raeburn  5627: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5628: 		   $cdom,$cnum);
1.81      www      5629:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5630: 	return 'error: '.$reply;
1.652     albertel 5631:     } else {
                   5632: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5633:     }
1.297     matthew  5634:     # Add student role to user
1.83      www      5635:     my $uurl='/'.$cid;
1.81      www      5636:     $uurl=~s/\_/\//g;
                   5637:     if ($usec) {
                   5638: 	$uurl.='/'.$usec;
                   5639:     }
1.947     raeburn  5640:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
1.21      www      5641: }
                   5642: 
1.556     albertel 5643: sub format_name {
                   5644:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5645:     my $name;
                   5646:     if ($first ne 'lastname') {
                   5647: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5648:     } else {
                   5649: 	if ($lastname=~/\S/) {
                   5650: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5651: 	    $name=~s/\s+,/,/;
                   5652: 	} else {
                   5653: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5654: 	}
                   5655:     }
                   5656:     $name=~s/^\s+//;
                   5657:     $name=~s/\s+$//;
                   5658:     $name=~s/\s+/ /g;
                   5659:     return $name;
                   5660: }
                   5661: 
1.84      www      5662: # ------------------------------------------------- Write to course preferences
                   5663: 
                   5664: sub writecoursepref {
                   5665:     my ($courseid,%prefs)=@_;
                   5666:     $courseid=~s/^\///;
                   5667:     $courseid=~s/\_/\//g;
                   5668:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5669:     my $chome=homeserver($cnum,$cdomain);
                   5670:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5671: 	return 'error: no such course';
                   5672:     }
                   5673:     my $cstring='';
1.800     albertel 5674:     foreach my $pref (keys(%prefs)) {
                   5675: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5676:     }
1.84      www      5677:     $cstring=~s/\&$//;
                   5678:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5679: }
                   5680: 
                   5681: # ---------------------------------------------------------- Make/modify course
                   5682: 
                   5683: sub createcourse {
1.741     raeburn  5684:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5685:         $course_owner,$crstype)=@_;
1.84      www      5686:     $url=&declutter($url);
                   5687:     my $cid='';
1.264     matthew  5688:     unless (&allowed('ccc',$udom)) {
1.84      www      5689:         return 'refused';
                   5690:     }
                   5691: # ------------------------------------------------------------------- Create ID
1.674     www      5692:    my $uname=int(1+rand(9)).
                   5693:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5694:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5695:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5696: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5697:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5698:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5699:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5700:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5701:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5702:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5703:            return 'error: unable to generate unique course-ID';
                   5704:        } 
                   5705:    }
1.264     matthew  5706: # ------------------------------------------------ Check supplied server name
1.620     albertel 5707:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5708:     if (! &is_library($course_server)) {
1.264     matthew  5709:         return 'error:bad server name '.$course_server;
                   5710:     }
1.84      www      5711: # ------------------------------------------------------------- Make the course
                   5712:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5713:                       $course_server);
1.84      www      5714:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5715:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5716:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5717: 	return 'error: no such course';
                   5718:     }
1.271     www      5719: # ----------------------------------------------------------------- Course made
1.516     raeburn  5720: # log existence
1.918     raeburn  5721:     my $newcourse = {
                   5722:                     $udom.'_'.$uname => {
1.921     raeburn  5723:                                      description => $description,
                   5724:                                      inst_code   => $inst_code,
                   5725:                                      owner       => $course_owner,
                   5726:                                      type        => $crstype,
1.918     raeburn  5727:                                                 },
                   5728:                     };
1.921     raeburn  5729:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5730: # set toplevel url
1.271     www      5731:     my $topurl=$url;
                   5732:     unless ($nonstandard) {
                   5733: # ------------------------------------------ For standard courses, make top url
                   5734:         my $mapurl=&clutter($url);
1.278     www      5735:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5736:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5737: <map>
                   5738: <resource id="1" type="start"></resource>
                   5739: <resource id="2" src="$mapurl"></resource>
                   5740: <resource id="3" type="finish"></resource>
                   5741: <link index="1" from="1" to="2"></link>
                   5742: <link index="2" from="2" to="3"></link>
                   5743: </map>
                   5744: ENDINITMAP
                   5745:         $topurl=&declutter(
1.638     albertel 5746:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5747:                           );
                   5748:     }
                   5749: # ----------------------------------------------------------- Write preferences
1.84      www      5750:     &writecoursepref($udom.'_'.$uname,
                   5751:                      ('description' => $description,
1.271     www      5752:                       'url'         => $topurl));
1.84      www      5753:     return '/'.$udom.'/'.$uname;
                   5754: }
                   5755: 
1.813     albertel 5756: sub is_course {
                   5757:     my ($cdom,$cnum) = @_;
                   5758:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5759: 				undef,'.');
1.813     albertel 5760:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5761:         return 1;
                   5762:     }
                   5763:     return 0;
                   5764: }
                   5765: 
1.21      www      5766: # ---------------------------------------------------------- Assign Custom Role
                   5767: 
                   5768: sub assigncustomrole {
1.357     www      5769:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5770:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5771:                        $end,$start,$deleteflag);
1.21      www      5772: }
                   5773: 
                   5774: # ----------------------------------------------------------------- Revoke Role
                   5775: 
                   5776: sub revokerole {
1.357     www      5777:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5778:     my $now=time;
1.357     www      5779:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5780: }
                   5781: 
                   5782: # ---------------------------------------------------------- Revoke Custom Role
                   5783: 
                   5784: sub revokecustomrole {
1.357     www      5785:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5786:     my $now=time;
1.357     www      5787:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5788:            $deleteflag);
1.17      www      5789: }
                   5790: 
1.533     banghart 5791: # ------------------------------------------------------------ Disk usage
1.535     albertel 5792: sub diskusage {
1.533     banghart 5793:     my ($udom,$uname,$directoryRoot)=@_;
                   5794:     $directoryRoot =~ s/\/$//;
1.535     albertel 5795:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5796:     return $listing;
1.512     banghart 5797: }
                   5798: 
1.566     banghart 5799: sub is_locked {
                   5800:     my ($file_name, $domain, $user) = @_;
                   5801:     my @check;
                   5802:     my $is_locked;
                   5803:     push @check, $file_name;
1.613     albertel 5804:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5805: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5806:     my ($tmp)=keys(%locked);
                   5807:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5808:     
1.566     banghart 5809:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5810:         $is_locked = 'false';
                   5811:         foreach my $entry (@{$locked{$file_name}}) {
                   5812:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5813:                $is_locked = 'true';
                   5814:                last;
1.745     raeburn  5815:            }
                   5816:        }
1.566     banghart 5817:     } else {
                   5818:         $is_locked = 'false';
                   5819:     }
                   5820: }
                   5821: 
1.759     albertel 5822: sub declutter_portfile {
                   5823:     my ($file) = @_;
1.833     albertel 5824:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5825:     return $file;
                   5826: }
                   5827: 
1.559     banghart 5828: # ------------------------------------------------------------- Mark as Read Only
                   5829: 
                   5830: sub mark_as_readonly {
                   5831:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5832:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5833:     my ($tmp)=keys(%current_permissions);
                   5834:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5835:     foreach my $file (@{$files}) {
1.759     albertel 5836: 	$file = &declutter_portfile($file);
1.561     banghart 5837:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5838:     }
1.613     albertel 5839:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5840:     return;
                   5841: }
                   5842: 
1.572     banghart 5843: # ------------------------------------------------------------Save Selected Files
                   5844: 
                   5845: sub save_selected_files {
                   5846:     my ($user, $path, @files) = @_;
                   5847:     my $filename = $user."savedfiles";
1.573     banghart 5848:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5849:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5850:     foreach my $file (@files) {
1.620     albertel 5851:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5852:     }
                   5853:     foreach my $file (@other_files) {
1.574     banghart 5854:         print (OUT $file."\n");
1.572     banghart 5855:     }
1.574     banghart 5856:     close (OUT);
1.572     banghart 5857:     return 'ok';
                   5858: }
                   5859: 
1.574     banghart 5860: sub clear_selected_files {
                   5861:     my ($user) = @_;
                   5862:     my $filename = $user."savedfiles";
                   5863:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5864:     print (OUT undef);
                   5865:     close (OUT);
                   5866:     return ("ok");    
                   5867: }
                   5868: 
1.572     banghart 5869: sub files_in_path {
                   5870:     my ($user, $path) = @_;
                   5871:     my $filename = $user."savedfiles";
                   5872:     my %return_files;
1.574     banghart 5873:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5874:     while (my $line_in = <IN>) {
1.574     banghart 5875:         chomp ($line_in);
                   5876:         my @paths_and_file = split (m!/!, $line_in);
                   5877:         my $file_part = pop (@paths_and_file);
                   5878:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5879:         $path_part.='/';
                   5880:         my $path_and_file = $path_part.$file_part;
                   5881:         if ($path_part eq $path) {
                   5882:             $return_files{$file_part}= 'selected';
                   5883:         }
                   5884:     }
1.574     banghart 5885:     close (IN);
                   5886:     return (\%return_files);
1.572     banghart 5887: }
                   5888: 
                   5889: # called in portfolio select mode, to show files selected NOT in current directory
                   5890: sub files_not_in_path {
                   5891:     my ($user, $path) = @_;
                   5892:     my $filename = $user."savedfiles";
                   5893:     my @return_files;
                   5894:     my $path_part;
1.800     albertel 5895:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5896:     while (my $line = <IN>) {
1.572     banghart 5897:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5898:         my @paths_and_file = split(m|/|, $line);
                   5899:         my $file_part = pop(@paths_and_file);
                   5900:         chomp($file_part);
                   5901:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5902:         $path_part .= '/';
                   5903:         my $path_and_file = $path_part.$file_part;
                   5904:         if ($path_part ne $path) {
1.800     albertel 5905:             push(@return_files, ($path_and_file));
1.572     banghart 5906:         }
                   5907:     }
1.800     albertel 5908:     close(OUT);
1.574     banghart 5909:     return (@return_files);
1.572     banghart 5910: }
                   5911: 
1.745     raeburn  5912: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5913: 
1.745     raeburn  5914: sub get_portfile_permissions {
                   5915:     my ($domain,$user) = @_;
1.613     albertel 5916:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5917:     my ($tmp)=keys(%current_permissions);
                   5918:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5919:     return \%current_permissions;
                   5920: }
                   5921: 
                   5922: #---------------------------------------------Get portfolio file access controls
                   5923: 
1.749     raeburn  5924: sub get_access_controls {
1.745     raeburn  5925:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5926:     my %access;
                   5927:     my $real_file = $file;
                   5928:     $file =~ s/\.meta$//;
1.745     raeburn  5929:     if (defined($file)) {
1.749     raeburn  5930:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5931:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5932:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5933:             }
                   5934:         }
1.745     raeburn  5935:     } else {
1.749     raeburn  5936:         foreach my $key (keys(%{$current_permissions})) {
                   5937:             if ($key =~ /\0accesscontrol$/) {
                   5938:                 if (defined($group)) {
                   5939:                     if ($key !~ m-^\Q$group\E/-) {
                   5940:                         next;
                   5941:                     }
                   5942:                 }
                   5943:                 my ($fullpath) = split(/\0/,$key);
                   5944:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5945:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5946:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5947:                     }
                   5948:                 }
                   5949:             }
                   5950:         }
                   5951:     }
                   5952:     return %access;
                   5953: }
                   5954: 
                   5955: sub modify_access_controls {
                   5956:     my ($file_name,$changes,$domain,$user)=@_;
                   5957:     my ($outcome,$deloutcome);
                   5958:     my %store_permissions;
                   5959:     my %new_values;
                   5960:     my %new_control;
                   5961:     my %translation;
                   5962:     my @deletions = ();
                   5963:     my $now = time;
                   5964:     if (exists($$changes{'activate'})) {
                   5965:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5966:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5967:             my $numnew = scalar(@newitems);
                   5968:             for (my $i=0; $i<$numnew; $i++) {
                   5969:                 my $newkey = $newitems[$i];
                   5970:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5971:                 if ($newkey =~ /^\d+:/) { 
                   5972:                     $newkey =~ s/^(\d+)/$newid/;
                   5973:                     $translation{$1} = $newid;
                   5974:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5975:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5976:                     $translation{$1} = $newid;
                   5977:                 }
1.749     raeburn  5978:                 $new_values{$file_name."\0".$newkey} = 
                   5979:                                           $$changes{'activate'}{$newitems[$i]};
                   5980:                 $new_control{$newkey} = $now;
                   5981:             }
                   5982:         }
                   5983:     }
                   5984:     my %todelete;
                   5985:     my %changed_items;
                   5986:     foreach my $action ('delete','update') {
                   5987:         if (exists($$changes{$action})) {
                   5988:             if (ref($$changes{$action}) eq 'HASH') {
                   5989:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5990:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5991:                     if ($action eq 'delete') { 
                   5992:                         $todelete{$itemnum} = 1;
                   5993:                     } else {
                   5994:                         $changed_items{$itemnum} = $key;
                   5995:                     }
                   5996:                 }
1.745     raeburn  5997:             }
                   5998:         }
1.749     raeburn  5999:     }
                   6000:     # get lock on access controls for file.
                   6001:     my $lockhash = {
                   6002:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6003:                                                        ':'.$env{'user.domain'},
                   6004:                    }; 
                   6005:     my $tries = 0;
                   6006:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6007:    
                   6008:     while (($gotlock ne 'ok') && $tries <3) {
                   6009:         $tries ++;
                   6010:         sleep 1;
                   6011:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6012:     }
                   6013:     if ($gotlock eq 'ok') {
                   6014:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6015:         my ($tmp)=keys(%curr_permissions);
                   6016:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6017:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6018:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6019:             if (ref($curr_controls) eq 'HASH') {
                   6020:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6021:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6022:                     if (defined($todelete{$itemnum})) {
                   6023:                         push(@deletions,$file_name."\0".$control_item);
                   6024:                     } else {
                   6025:                         if (defined($changed_items{$itemnum})) {
                   6026:                             $new_control{$changed_items{$itemnum}} = $now;
                   6027:                             push(@deletions,$file_name."\0".$control_item);
                   6028:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6029:                         } else {
                   6030:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6031:                         }
                   6032:                     }
1.745     raeburn  6033:                 }
                   6034:             }
                   6035:         }
1.749     raeburn  6036:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6037:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6038:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6039:         #  remove lock
                   6040:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6041:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6042:         my ($file,$group);
                   6043:         if (&is_course($domain,$user)) {
                   6044:             ($group,$file) = split(/\//,$file_name,2);
                   6045:         } else {
                   6046:             $file = $file_name;
                   6047:         }
                   6048:         my $sqlresult =
                   6049:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6050:                                     $group);
1.749     raeburn  6051:     } else {
                   6052:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6053:     }
1.749     raeburn  6054:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6055: }
                   6056: 
1.827     raeburn  6057: sub make_public_indefinitely {
                   6058:     my ($requrl) = @_;
                   6059:     my $now = time;
                   6060:     my $action = 'activate';
                   6061:     my $aclnum = 0;
                   6062:     if (&is_portfolio_url($requrl)) {
                   6063:         my (undef,$udom,$unum,$file_name,$group) =
                   6064:             &parse_portfolio_url($requrl);
                   6065:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6066:         my %access_controls = &get_access_controls($current_perms,
                   6067:                                                    $group,$file_name);
                   6068:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6069:             my ($num,$scope,$end,$start) = 
                   6070:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6071:             if ($scope eq 'public') {
                   6072:                 if ($start <= $now && $end == 0) {
                   6073:                     $action = 'none';
                   6074:                 } else {
                   6075:                     $action = 'update';
                   6076:                     $aclnum = $num;
                   6077:                 }
                   6078:                 last;
                   6079:             }
                   6080:         }
                   6081:         if ($action eq 'none') {
                   6082:              return 'ok';
                   6083:         } else {
                   6084:             my %changes;
                   6085:             my $newend = 0;
                   6086:             my $newstart = $now;
                   6087:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6088:             $changes{$action}{$newkey} = {
                   6089:                 type => 'public',
                   6090:                 time => {
                   6091:                     start => $newstart,
                   6092:                     end   => $newend,
                   6093:                 },
                   6094:             };
                   6095:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6096:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6097:             return $outcome;
                   6098:         }
                   6099:     } else {
                   6100:         return 'invalid';
                   6101:     }
                   6102: }
                   6103: 
1.745     raeburn  6104: #------------------------------------------------------Get Marked as Read Only
                   6105: 
                   6106: sub get_marked_as_readonly {
                   6107:     my ($domain,$user,$what,$group) = @_;
                   6108:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6109:     my @readonly_files;
1.629     banghart 6110:     my $cmp1=$what;
                   6111:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6112:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6113:         if (defined($group)) {
                   6114:             if ($file_name !~ m-^\Q$group\E/-) {
                   6115:                 next;
                   6116:             }
                   6117:         }
1.561     banghart 6118:         if (ref($value) eq "ARRAY"){
                   6119:             foreach my $stored_what (@{$value}) {
1.629     banghart 6120:                 my $cmp2=$stored_what;
1.759     albertel 6121:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6122:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6123:                 }
1.629     banghart 6124:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6125:                     push(@readonly_files, $file_name);
1.745     raeburn  6126:                     last;
1.563     banghart 6127:                 } elsif (!defined($what)) {
                   6128:                     push(@readonly_files, $file_name);
1.745     raeburn  6129:                     last;
1.561     banghart 6130:                 }
                   6131:             }
1.745     raeburn  6132:         }
1.561     banghart 6133:     }
                   6134:     return @readonly_files;
                   6135: }
1.577     banghart 6136: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6137: 
1.577     banghart 6138: sub get_marked_as_readonly_hash {
1.745     raeburn  6139:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6140:     my %readonly_files;
1.745     raeburn  6141:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6142:         if (defined($group)) {
                   6143:             if ($file_name !~ m-^\Q$group\E/-) {
                   6144:                 next;
                   6145:             }
                   6146:         }
1.577     banghart 6147:         if (ref($value) eq "ARRAY"){
                   6148:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6149:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6150:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6151:                         if ($lock_descriptor eq 'graded') {
                   6152:                             $readonly_files{$file_name} = 'graded';
                   6153:                         } elsif ($lock_descriptor eq 'handback') {
                   6154:                             $readonly_files{$file_name} = 'handback';
                   6155:                         } else {
                   6156:                             if (!exists($readonly_files{$file_name})) {
                   6157:                                 $readonly_files{$file_name} = 'locked';
                   6158:                             }
                   6159:                         }
1.745     raeburn  6160:                     }
1.750     banghart 6161:                 } 
1.577     banghart 6162:             }
                   6163:         } 
                   6164:     }
                   6165:     return %readonly_files;
                   6166: }
1.559     banghart 6167: # ------------------------------------------------------------ Unmark as Read Only
                   6168: 
                   6169: sub unmark_as_readonly {
1.629     banghart 6170:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6171:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6172:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6173:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6174:     my $symb_crs = $what;
                   6175:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6176:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6177:     my ($tmp)=keys(%current_permissions);
                   6178:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6179:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6180:     foreach my $file (@readonly_files) {
1.759     albertel 6181: 	my $clean_file = &declutter_portfile($file);
                   6182: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6183: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6184:         my @new_locks;
                   6185:         my @del_keys;
                   6186:         if (ref($current_locks) eq "ARRAY"){
                   6187:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6188:                 my $compare=$locker;
1.749     raeburn  6189:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6190:                     $compare=join('',@{$locker});
1.746     raeburn  6191:                     if ($compare ne $symb_crs) {
                   6192:                         push(@new_locks, $locker);
                   6193:                     }
1.563     banghart 6194:                 }
                   6195:             }
1.650     albertel 6196:             if (scalar(@new_locks) > 0) {
1.563     banghart 6197:                 $current_permissions{$file} = \@new_locks;
                   6198:             } else {
                   6199:                 push(@del_keys, $file);
1.613     albertel 6200:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6201:                 delete($current_permissions{$file});
1.563     banghart 6202:             }
                   6203:         }
1.561     banghart 6204:     }
1.613     albertel 6205:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6206:     return;
                   6207: }
1.512     banghart 6208: 
1.17      www      6209: # ------------------------------------------------------------ Directory lister
                   6210: 
                   6211: sub dirlist {
1.253     stredwic 6212:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6213: 
1.18      www      6214:     $uri=~s/^\///;
                   6215:     $uri=~s/\/$//;
1.253     stredwic 6216:     my ($udom, $uname);
                   6217:     (undef,$udom,$uname)=split(/\//,$uri);
                   6218:     if(defined($userdomain)) {
                   6219:         $udom = $userdomain;
                   6220:     }
                   6221:     if(defined($username)) {
                   6222:         $uname = $username;
                   6223:     }
                   6224: 
                   6225:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6226:     if(defined($alternateDirectoryRoot)) {
                   6227:         $dirRoot = $alternateDirectoryRoot;
                   6228:         $dirRoot =~ s/\/$//;
1.751     banghart 6229:     }
1.253     stredwic 6230: 
                   6231:     if($udom) {
                   6232:         if($uname) {
1.800     albertel 6233:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6234: 				 &homeserver($uname,$udom));
1.605     matthew  6235:             my @listing_results;
                   6236:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6237:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6238: 				  &homeserver($uname,$udom));
1.605     matthew  6239:                 @listing_results = split(/:/,$listing);
                   6240:             } else {
                   6241:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6242:             }
                   6243:             return @listing_results;
1.253     stredwic 6244:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6245:             my %allusers;
1.841     albertel 6246: 	    my %servers = &get_servers($udom,'library');
                   6247: 	    foreach my $tryserver (keys(%servers)) {
                   6248: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6249: 				     $udom, $tryserver);
                   6250: 		my @listing_results;
                   6251: 		if ($listing eq 'unknown_cmd') {
                   6252: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6253: 				      $udom, $tryserver);
                   6254: 		    @listing_results = split(/:/,$listing);
                   6255: 		} else {
                   6256: 		    @listing_results =
                   6257: 			map { &unescape($_); } split(/:/,$listing);
                   6258: 		}
                   6259: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6260: 		    $listing_results[0] ne 'empty'       &&
                   6261: 		    $listing_results[0] ne 'con_lost') {
                   6262: 		    foreach my $line (@listing_results) {
                   6263: 			my ($entry) = split(/&/,$line,2);
                   6264: 			$allusers{$entry} = 1;
                   6265: 		    }
                   6266: 		}
1.253     stredwic 6267:             }
                   6268:             my $alluserstr='';
1.800     albertel 6269:             foreach my $user (sort(keys(%allusers))) {
                   6270:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6271:             }
                   6272:             $alluserstr=~s/:$//;
                   6273:             return split(/:/,$alluserstr);
                   6274:         } else {
1.800     albertel 6275:             return ('missing user name');
1.253     stredwic 6276:         }
                   6277:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6278:         my @all_domains = sort(&all_domains());
                   6279:          foreach my $domain (@all_domains) {
                   6280:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6281:          }
                   6282:          return @all_domains;
                   6283:      } else {
1.800     albertel 6284:         return ('missing domain');
1.275     stredwic 6285:     }
                   6286: }
                   6287: 
                   6288: # --------------------------------------------- GetFileTimestamp
                   6289: # This function utilizes dirlist and returns the date stamp for
                   6290: # when it was last modified.  It will also return an error of -1
                   6291: # if an error occurs
                   6292: 
1.410     matthew  6293: ##
                   6294: ## FIXME: This subroutine assumes its caller knows something about the
                   6295: ## directory structure of the home server for the student ($root).
                   6296: ## Not a good assumption to make.  Since this is for looking up files
                   6297: ## in user directories, the full path should be constructed by lond, not
                   6298: ## whatever machine we request data from.
                   6299: ##
1.275     stredwic 6300: sub GetFileTimestamp {
                   6301:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6302:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6303:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6304:     my $subdir=$studentName.'__';
                   6305:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6306:     my $proname="$studentDomain/$subdir/$studentName";
                   6307:     $proname .= '/'.$filename;
1.375     matthew  6308:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6309:                                               $studentName, $root);
1.275     stredwic 6310:     my @stats = split('&', $fileStat);
                   6311:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6312:         # @stats contains first the filename, then the stat output
                   6313:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6314:     } else {
                   6315:         return -1;
1.253     stredwic 6316:     }
1.26      www      6317: }
                   6318: 
1.712     albertel 6319: sub stat_file {
                   6320:     my ($uri) = @_;
1.787     albertel 6321:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6322: 
1.712     albertel 6323:     my ($udom,$uname,$file,$dir);
                   6324:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6325: 	($udom,$uname,$file) =
1.811     albertel 6326: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6327: 	$file = 'userfiles/'.$file;
1.740     www      6328: 	$dir = &propath($udom,$uname);
1.712     albertel 6329:     }
                   6330:     if ($uri =~ m-^/res/-) {
                   6331: 	($udom,$uname) = 
1.807     albertel 6332: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6333: 	$file = $uri;
                   6334:     }
                   6335: 
                   6336:     if (!$udom || !$uname || !$file) {
                   6337: 	# unable to handle the uri
                   6338: 	return ();
                   6339:     }
                   6340: 
                   6341:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6342:     my @stats = split('&', $result);
1.721     banghart 6343:     
1.712     albertel 6344:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6345: 	shift(@stats); #filename is first
                   6346: 	return @stats;
                   6347:     }
                   6348:     return ();
                   6349: }
                   6350: 
1.26      www      6351: # -------------------------------------------------------- Value of a Condition
                   6352: 
1.713     albertel 6353: # gets the value of a specific preevaluated condition
                   6354: #    stored in the string  $env{user.state.<cid>}
                   6355: # or looks up a condition reference in the bighash and if if hasn't
                   6356: # already been evaluated recurses into docondval to get the value of
                   6357: # the condition, then memoizing it to 
                   6358: #   $env{user.state.<cid>.<condition>}
1.40      www      6359: sub directcondval {
                   6360:     my $number=shift;
1.620     albertel 6361:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6362: 	&Apache::lonuserstate::evalstate();
                   6363:     }
1.713     albertel 6364:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6365: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6366:     } elsif ($number =~ /^_/) {
                   6367: 	my $sub_condition;
                   6368: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6369: 		&GDBM_READER(),0640)) {
                   6370: 	    $sub_condition=$bighash{'conditions'.$number};
                   6371: 	    untie(%bighash);
                   6372: 	}
                   6373: 	my $value = &docondval($sub_condition);
1.949     raeburn  6374: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6375: 	return $value;
                   6376:     }
1.620     albertel 6377:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6378:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6379:     } else {
                   6380:        return 2;
                   6381:     }
                   6382: }
                   6383: 
1.713     albertel 6384: # get the collection of conditions for this resource
1.26      www      6385: sub condval {
                   6386:     my $condidx=shift;
1.54      www      6387:     my $allpathcond='';
1.713     albertel 6388:     foreach my $cond (split(/\|/,$condidx)) {
                   6389: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6390: 	    $allpathcond.=
                   6391: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6392: 	}
1.191     harris41 6393:     }
1.54      www      6394:     $allpathcond=~s/\|$//;
1.713     albertel 6395:     return &docondval($allpathcond);
                   6396: }
                   6397: 
                   6398: #evaluates an expression of conditions
                   6399: sub docondval {
                   6400:     my ($allpathcond) = @_;
                   6401:     my $result=0;
                   6402:     if ($env{'request.course.id'}
                   6403: 	&& defined($allpathcond)) {
                   6404: 	my $operand='|';
                   6405: 	my @stack;
                   6406: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6407: 	    if ($chunk eq '(') {
                   6408: 		push @stack,($operand,$result);
                   6409: 	    } elsif ($chunk eq ')') {
                   6410: 		my $before=pop @stack;
                   6411: 		if (pop @stack eq '&') {
                   6412: 		    $result=$result>$before?$before:$result;
                   6413: 		} else {
                   6414: 		    $result=$result>$before?$result:$before;
                   6415: 		}
                   6416: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6417: 		$operand=$chunk;
                   6418: 	    } else {
                   6419: 		my $new=directcondval($chunk);
                   6420: 		if ($operand eq '&') {
                   6421: 		    $result=$result>$new?$new:$result;
                   6422: 		} else {
                   6423: 		    $result=$result>$new?$result:$new;
                   6424: 		}
                   6425: 	    }
                   6426: 	}
1.26      www      6427:     }
                   6428:     return $result;
1.421     albertel 6429: }
                   6430: 
                   6431: # ---------------------------------------------------- Devalidate courseresdata
                   6432: 
                   6433: sub devalidatecourseresdata {
                   6434:     my ($coursenum,$coursedomain)=@_;
                   6435:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6436:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6437: }
                   6438: 
1.763     www      6439: 
1.200     www      6440: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6441: #
                   6442: #  Parameters:
                   6443: #      $coursenum    - Number of the course.
                   6444: #      $coursedomain - Domain at which the course was created.
                   6445: #  Returns:
                   6446: #     A hash of the course parameters along (I think) with timestamps
                   6447: #     and version info.
1.877     foxr     6448: 
1.624     albertel 6449: sub get_courseresdata {
                   6450:     my ($coursenum,$coursedomain)=@_;
1.200     www      6451:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6452:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6453:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6454:     my %dumpreply;
1.417     albertel 6455:     unless (defined($cached)) {
1.624     albertel 6456: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6457: 	$result=\%dumpreply;
1.251     albertel 6458: 	my ($tmp) = keys(%dumpreply);
                   6459: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6460: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6461: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6462: 	    return $tmp;
1.416     albertel 6463: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6464: 	    $result=undef;
1.599     albertel 6465: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6466: 	}
                   6467:     }
1.624     albertel 6468:     return $result;
                   6469: }
                   6470: 
1.633     albertel 6471: sub devalidateuserresdata {
                   6472:     my ($uname,$udom)=@_;
                   6473:     my $hashid="$udom:$uname";
                   6474:     &devalidate_cache_new('userres',$hashid);
                   6475: }
                   6476: 
1.624     albertel 6477: sub get_userresdata {
                   6478:     my ($uname,$udom)=@_;
                   6479:     #most student don\'t have any data set, check if there is some data
                   6480:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6481: 
                   6482:     my $hashid="$udom:$uname";
                   6483:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6484:     if (!defined($cached)) {
                   6485: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6486: 	$result=\%resourcedata;
                   6487: 	&do_cache_new('userres',$hashid,$result,600);
                   6488:     }
                   6489:     my ($tmp)=keys(%$result);
                   6490:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6491: 	return $result;
                   6492:     }
                   6493:     #error 2 occurs when the .db doesn't exist
                   6494:     if ($tmp!~/error: 2 /) {
1.672     albertel 6495: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6496: 		 " Trying to get resource data for ".
                   6497: 		 $uname." at ".$udom.": ".
                   6498: 		 $tmp."</font>");
                   6499:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6500: 	#&EXT_cache_set($udom,$uname);
                   6501: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6502: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6503:     }
                   6504:     return $tmp;
                   6505: }
1.879     foxr     6506: #----------------------------------------------- resdata - return resource data
                   6507: #  Purpose:
                   6508: #    Return resource data for either users or for a course.
                   6509: #  Parameters:
                   6510: #     $name      - Course/user name.
                   6511: #     $domain    - Name of the domain the user/course is registered on.
                   6512: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6513: #     @which     - Array of names of resources desired.
                   6514: #  Returns:
                   6515: #     The value of the first reasource in @which that is found in the
                   6516: #     resource hash.
                   6517: #  Exceptional Conditions:
                   6518: #     If the $type passed in is not valid (not the string 'course' or 
                   6519: #     'user', an undefined  reference is returned.
                   6520: #     If none of the resources are found, an undef is returned
1.624     albertel 6521: sub resdata {
                   6522:     my ($name,$domain,$type,@which)=@_;
                   6523:     my $result;
                   6524:     if ($type eq 'course') {
                   6525: 	$result=&get_courseresdata($name,$domain);
                   6526:     } elsif ($type eq 'user') {
                   6527: 	$result=&get_userresdata($name,$domain);
                   6528:     }
                   6529:     if (!ref($result)) { return $result; }    
1.251     albertel 6530:     foreach my $item (@which) {
1.927     albertel 6531: 	if (defined($result->{$item->[0]})) {
                   6532: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6533: 	}
1.250     albertel 6534:     }
1.291     albertel 6535:     return undef;
1.200     www      6536: }
                   6537: 
1.379     matthew  6538: #
                   6539: # EXT resource caching routines
                   6540: #
                   6541: 
                   6542: sub clear_EXT_cache_status {
1.383     albertel 6543:     &delenv('cache.EXT.');
1.379     matthew  6544: }
                   6545: 
                   6546: sub EXT_cache_status {
                   6547:     my ($target_domain,$target_user) = @_;
1.383     albertel 6548:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6549:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6550:         # We know already the user has no data
                   6551:         return 1;
                   6552:     } else {
                   6553:         return 0;
                   6554:     }
                   6555: }
                   6556: 
                   6557: sub EXT_cache_set {
                   6558:     my ($target_domain,$target_user) = @_;
1.383     albertel 6559:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6560:     #&appenv({$cachename => time});
1.379     matthew  6561: }
                   6562: 
1.28      www      6563: # --------------------------------------------------------- Value of a Variable
1.58      www      6564: sub EXT {
1.715     albertel 6565: 
1.395     albertel 6566:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6567:     unless ($varname) { return ''; }
1.218     albertel 6568:     #get real user name/domain, courseid and symb
                   6569:     my $courseid;
1.359     albertel 6570:     my $publicuser;
1.427     www      6571:     if ($symbparm) {
                   6572: 	$symbparm=&get_symb_from_alias($symbparm);
                   6573:     }
1.218     albertel 6574:     if (!($uname && $udom)) {
1.790     albertel 6575:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6576:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6577:     } else {
1.620     albertel 6578: 	$courseid=$env{'request.course.id'};
1.218     albertel 6579:     }
1.48      www      6580:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6581:     my $rest;
1.320     albertel 6582:     if (defined($therest[0])) {
1.48      www      6583:        $rest=join('.',@therest);
                   6584:     } else {
                   6585:        $rest='';
                   6586:     }
1.320     albertel 6587: 
1.57      www      6588:     my $qualifierrest=$qualifier;
                   6589:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6590:     my $spacequalifierrest=$space;
                   6591:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6592:     if ($realm eq 'user') {
1.48      www      6593: # --------------------------------------------------------------- user.resource
                   6594: 	if ($space eq 'resource') {
1.651     albertel 6595: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6596: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6597: 		 &&
1.744     albertel 6598: 		 ($symbparm eq &symbread()) ) {	
                   6599: 		# if we are in the middle of processing the resource the
                   6600: 		# get the value we are planning on committing
                   6601:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6602:                     return $Apache::lonhomework::results{$qualifierrest};
                   6603:                 } else {
                   6604:                     return $Apache::lonhomework::history{$qualifierrest};
                   6605:                 }
1.335     albertel 6606: 	    } else {
1.359     albertel 6607: 		my %restored;
1.620     albertel 6608: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6609: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6610: 		} else {
                   6611: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6612: 		}
1.335     albertel 6613: 		return $restored{$qualifierrest};
                   6614: 	    }
1.48      www      6615: # ----------------------------------------------------------------- user.access
                   6616:         } elsif ($space eq 'access') {
1.218     albertel 6617: 	    # FIXME - not supporting calls for a specific user
1.48      www      6618:             return &allowed($qualifier,$rest);
                   6619: # ------------------------------------------ user.preferences, user.environment
                   6620:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6621: 	    if (($uname eq $env{'user.name'}) &&
                   6622: 		($udom eq $env{'user.domain'})) {
                   6623: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6624: 	    } else {
1.359     albertel 6625: 		my %returnhash;
                   6626: 		if (!$publicuser) {
                   6627: 		    %returnhash=&userenvironment($udom,$uname,
                   6628: 						 $qualifierrest);
                   6629: 		}
1.218     albertel 6630: 		return $returnhash{$qualifierrest};
                   6631: 	    }
1.48      www      6632: # ----------------------------------------------------------------- user.course
                   6633:         } elsif ($space eq 'course') {
1.218     albertel 6634: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6635:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6636: # ------------------------------------------------------------------- user.role
                   6637:         } elsif ($space eq 'role') {
1.218     albertel 6638: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6639:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6640:             if ($qualifier eq 'value') {
                   6641: 		return $role;
                   6642:             } elsif ($qualifier eq 'extent') {
                   6643:                 return $where;
                   6644:             }
                   6645: # ----------------------------------------------------------------- user.domain
                   6646:         } elsif ($space eq 'domain') {
1.218     albertel 6647:             return $udom;
1.48      www      6648: # ------------------------------------------------------------------- user.name
                   6649:         } elsif ($space eq 'name') {
1.218     albertel 6650:             return $uname;
1.48      www      6651: # ---------------------------------------------------- Any other user namespace
1.29      www      6652:         } else {
1.359     albertel 6653: 	    my %reply;
                   6654: 	    if (!$publicuser) {
                   6655: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6656: 	    }
                   6657: 	    return $reply{$qualifierrest};
1.48      www      6658:         }
1.236     www      6659:     } elsif ($realm eq 'query') {
                   6660: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6661:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6662: 						[$spacequalifierrest]);
1.620     albertel 6663: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6664:    } elsif ($realm eq 'request') {
1.48      www      6665: # ------------------------------------------------------------- request.browser
                   6666:         if ($space eq 'browser') {
1.430     www      6667: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6668: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6669: 		    return 1;
                   6670: 		} else {
                   6671: 		    return 0;
                   6672: 		}
                   6673: 	    } else {
1.620     albertel 6674: 		return $env{'browser.'.$qualifier};
1.430     www      6675: 	    }
1.57      www      6676: # ------------------------------------------------------------ request.filename
                   6677:         } else {
1.620     albertel 6678:             return $env{'request.'.$spacequalifierrest};
1.29      www      6679:         }
1.28      www      6680:     } elsif ($realm eq 'course') {
1.48      www      6681: # ---------------------------------------------------------- course.description
1.620     albertel 6682:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6683:     } elsif ($realm eq 'resource') {
1.165     www      6684: 
1.620     albertel 6685: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6686: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6687: 	}
1.693     albertel 6688: 
                   6689: 	if ($space eq 'title') {
                   6690: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6691: 	    return &gettitle($symbparm);
                   6692: 	}
                   6693: 	
                   6694: 	if ($space eq 'map') {
                   6695: 	    my ($map) = &decode_symb($symbparm);
                   6696: 	    return &symbread($map);
                   6697: 	}
1.905     albertel 6698: 	if ($space eq 'filename') {
                   6699: 	    if ($symbparm) {
                   6700: 		return &clutter((&decode_symb($symbparm))[2]);
                   6701: 	    }
                   6702: 	    return &hreflocation('',$env{'request.filename'});
                   6703: 	}
1.693     albertel 6704: 
                   6705: 	my ($section, $group, @groups);
1.593     albertel 6706: 	my ($courselevelm,$courselevel);
1.539     albertel 6707: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6708: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6709: 
1.218     albertel 6710: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6711: 
1.60      www      6712: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6713: 	    my $symbp=$symbparm;
1.735     albertel 6714: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6715: 
                   6716: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6717: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6718: 
1.620     albertel 6719: 	    if (($env{'user.name'} eq $uname) &&
                   6720: 		($env{'user.domain'} eq $udom)) {
                   6721: 		$section=$env{'request.course.sec'};
1.733     raeburn  6722:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6723:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6724: 	    } else {
1.539     albertel 6725: 		if (! defined($usection)) {
1.551     albertel 6726: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6727: 		} else {
                   6728: 		    $section = $usection;
                   6729: 		}
1.733     raeburn  6730:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6731: 	    }
                   6732: 
                   6733: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6734: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6735: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6736: 
1.593     albertel 6737: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6738: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6739: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6740: 
1.60      www      6741: # ----------------------------------------------------------- first, check user
1.624     albertel 6742: 
                   6743: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6744: 				       ([$courselevelr,'resource'],
                   6745: 					[$courselevelm,'map'     ],
                   6746: 					[$courselevel, 'course'  ]));
1.931     albertel 6747: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6748: 
1.594     albertel 6749: # ------------------------------------------------ second, check some of course
1.684     raeburn  6750:             my $coursereply;
1.691     raeburn  6751:             if (@groups > 0) {
                   6752:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6753:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6754:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6755:             }
1.96      www      6756: 
1.684     raeburn  6757: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6758: 				  $env{'course.'.$courseid.'.domain'},
                   6759: 				  'course',
                   6760: 				  ([$seclevelr,   'resource'],
                   6761: 				   [$seclevelm,   'map'     ],
                   6762: 				   [$seclevel,    'course'  ],
                   6763: 				   [$courselevelr,'resource']));
                   6764: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6765: 
1.60      www      6766: # ------------------------------------------------------ third, check map parms
1.218     albertel 6767: 	    my %parmhash=();
                   6768: 	    my $thisparm='';
                   6769: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6770: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6771: 		    &GDBM_READER(),0640)) {
1.218     albertel 6772: 		$thisparm=$parmhash{$symbparm};
                   6773: 		untie(%parmhash);
                   6774: 	    }
1.927     albertel 6775: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6776: 	}
1.594     albertel 6777: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6778: 
1.218     albertel 6779: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6780: 	my $filename;
                   6781: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6782: 	if ($symbparm) {
1.409     www      6783: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6784: 	} else {
1.620     albertel 6785: 	    $filename=$env{'request.filename'};
1.282     albertel 6786: 	}
                   6787: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6788: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6789: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6790: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6791: 
1.927     albertel 6792: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6793: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6794: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6795: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6796: 				     $env{'course.'.$courseid.'.domain'},
                   6797: 				     'course',
1.927     albertel 6798: 				     ([$courselevelm,'map'   ],
                   6799: 				      [$courselevel, 'course']));
                   6800: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6801: 	}
1.145     www      6802: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6803: 	unless ($space eq '0') {
1.336     albertel 6804: 	    my @parts=split(/_/,$space);
                   6805: 	    my $id=pop(@parts);
                   6806: 	    my $part=join('_',@parts);
                   6807: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6808: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6809: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6810: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6811: 	}
1.395     albertel 6812: 	if ($recurse) { return undef; }
                   6813: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6814: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6815: # ---------------------------------------------------- Any other user namespace
                   6816:     } elsif ($realm eq 'environment') {
                   6817: # ----------------------------------------------------------------- environment
1.620     albertel 6818: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6819: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6820: 	} else {
1.770     albertel 6821: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6822: 		return '';
                   6823: 	    }
1.219     albertel 6824: 	    my %returnhash=&userenvironment($udom,$uname,
                   6825: 					    $spacequalifierrest);
                   6826: 	    return $returnhash{$spacequalifierrest};
                   6827: 	}
1.28      www      6828:     } elsif ($realm eq 'system') {
1.48      www      6829: # ----------------------------------------------------------------- system.time
                   6830: 	if ($space eq 'time') {
                   6831: 	    return time;
                   6832:         }
1.696     albertel 6833:     } elsif ($realm eq 'server') {
                   6834: # ----------------------------------------------------------------- system.time
                   6835: 	if ($space eq 'name') {
                   6836: 	    return $ENV{'SERVER_NAME'};
                   6837:         }
1.28      www      6838:     }
1.48      www      6839:     return '';
1.61      www      6840: }
                   6841: 
1.927     albertel 6842: sub get_reply {
                   6843:     my ($reply_value) = @_;
1.940     raeburn  6844:     if (ref($reply_value) eq 'ARRAY') {
                   6845:         if (wantarray) {
                   6846: 	    return @$reply_value;
                   6847:         }
                   6848:         return $reply_value->[0];
                   6849:     } else {
                   6850:         return $reply_value;
1.927     albertel 6851:     }
                   6852: }
                   6853: 
1.691     raeburn  6854: sub check_group_parms {
                   6855:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6856:     my @groupitems = ();
                   6857:     my $resultitem;
1.927     albertel 6858:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6859:     foreach my $group (@{$groups}) {
                   6860:         foreach my $level (@levels) {
1.927     albertel 6861:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6862:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6863:         }
                   6864:     }
                   6865:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6866:                             $env{'course.'.$courseid.'.domain'},
                   6867:                                      'course',@groupitems);
                   6868:     return $coursereply;
                   6869: }
                   6870: 
                   6871: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6872:     my ($courseid,@groups) = @_;
                   6873:     @groups = sort(@groups);
1.691     raeburn  6874:     return @groups;
                   6875: }
                   6876: 
1.395     albertel 6877: sub packages_tab_default {
                   6878:     my ($uri,$varname)=@_;
                   6879:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6880: 
                   6881:     my (@extension,@specifics,$do_default);
                   6882:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6883: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6884: 	if ($pack_type eq 'default') {
                   6885: 	    $do_default=1;
                   6886: 	} elsif ($pack_type eq 'extension') {
                   6887: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6888: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6889: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6890: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6891: 	}
                   6892:     }
                   6893:     # first look for a package that matches the requested part id
                   6894:     foreach my $package (@specifics) {
                   6895: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6896: 	next if ($pack_part ne $part);
                   6897: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6898: 	    return $packagetab{"$pack_type&$name&default"};
                   6899: 	}
                   6900:     }
                   6901:     # look for any possible matching non extension_ package
                   6902:     foreach my $package (@specifics) {
                   6903: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6904: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6905: 	    return $packagetab{"$pack_type&$name&default"};
                   6906: 	}
1.585     albertel 6907: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6908: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6909: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6910: 	}
                   6911:     }
1.738     albertel 6912:     # look for any posible extension_ match
                   6913:     foreach my $package (@extension) {
                   6914: 	my ($package,$pack_type)=@{$package};
                   6915: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6916: 	    return $packagetab{"$pack_type&$name&default"};
                   6917: 	}
                   6918: 	if (defined($packagetab{$package."&$name&default"})) {
                   6919: 	    return $packagetab{$package."&$name&default"};
                   6920: 	}
                   6921:     }
                   6922:     # look for a global default setting
                   6923:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6924: 	return $packagetab{"default&$name&default"};
                   6925:     }
1.395     albertel 6926:     return undef;
                   6927: }
                   6928: 
1.334     albertel 6929: sub add_prefix_and_part {
                   6930:     my ($prefix,$part)=@_;
                   6931:     my $keyroot;
                   6932:     if (defined($prefix) && $prefix !~ /^__/) {
                   6933: 	# prefix that has a part already
                   6934: 	$keyroot=$prefix;
                   6935:     } elsif (defined($prefix)) {
                   6936: 	# prefix that is missing a part
                   6937: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6938:     } else {
                   6939: 	# no prefix at all
                   6940: 	if (defined($part)) { $keyroot='_'.$part; }
                   6941:     }
                   6942:     return $keyroot;
                   6943: }
                   6944: 
1.71      www      6945: # ---------------------------------------------------------------- Get metadata
                   6946: 
1.599     albertel 6947: my %metaentry;
1.71      www      6948: sub metadata {
1.176     www      6949:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6950:     $uri=&declutter($uri);
1.288     albertel 6951:     # if it is a non metadata possible uri return quickly
1.529     albertel 6952:     if (($uri eq '') || 
                   6953: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6954: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6955:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6956: 	return undef;
                   6957:     }
                   6958:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6959: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6960: 	return undef;
1.288     albertel 6961:     }
1.73      www      6962:     my $filename=$uri;
                   6963:     $uri=~s/\.meta$//;
1.172     www      6964: #
                   6965: # Is the metadata already cached?
1.177     www      6966: # Look at timestamp of caching
1.172     www      6967: # Everything is cached by the main uri, libraries are never directly cached
                   6968: #
1.428     albertel 6969:     if (!defined($liburi)) {
1.599     albertel 6970: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6971: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6972:     }
                   6973:     {
1.172     www      6974: #
                   6975: # Is this a recursive call for a library?
                   6976: #
1.599     albertel 6977: #	if (! exists($metacache{$uri})) {
                   6978: #	    $metacache{$uri}={};
                   6979: #	}
1.924     albertel 6980: 	my $cachetime = 60*60;
1.171     www      6981:         if ($liburi) {
                   6982: 	    $liburi=&declutter($liburi);
                   6983:             $filename=$liburi;
1.401     bowersj2 6984:         } else {
1.599     albertel 6985: 	    &devalidate_cache_new('meta',$uri);
                   6986: 	    undef(%metaentry);
1.401     bowersj2 6987: 	}
1.140     www      6988:         my %metathesekeys=();
1.73      www      6989:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6990: 	my $metastring;
1.924     albertel 6991: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 6992: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 6993: 	    $metastring = 
1.929     albertel 6994: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 6995: 					  ('grade_target' => 'meta'));
                   6996: 	    $cachetime = 1; # only want this cached in the child not long term
                   6997: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 6998: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6999: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7000: 	    $metastring=&getfile($file);
1.489     albertel 7001: 	}
1.208     albertel 7002:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7003:         my $token;
1.140     www      7004:         undef %metathesekeys;
1.71      www      7005:         while ($token=$parser->get_token) {
1.339     albertel 7006: 	    if ($token->[0] eq 'S') {
                   7007: 		if (defined($token->[2]->{'package'})) {
1.172     www      7008: #
                   7009: # This is a package - get package info
                   7010: #
1.339     albertel 7011: 		    my $package=$token->[2]->{'package'};
                   7012: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7013: 		    if (defined($token->[2]->{'id'})) { 
                   7014: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7015: 		    }
1.599     albertel 7016: 		    if ($metaentry{':packages'}) {
                   7017: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7018: 		    } else {
1.599     albertel 7019: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7020: 		    }
1.736     albertel 7021: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7022: 			my $part=$keyroot;
                   7023: 			$part=~s/^\_//;
1.736     albertel 7024: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7025: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7026: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7027: 			    # ignore package.tab specified default values
                   7028:                             # here &package_tab_default() will fetch those
                   7029: 			    if ($subp eq 'default') { next; }
1.736     albertel 7030: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7031: 			    my $unikey;
                   7032: 			    if ($pack =~ /_0$/) {
                   7033: 				$unikey='parameter_0_'.$name;
                   7034: 				$part=0;
                   7035: 			    } else {
                   7036: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7037: 			    }
1.339     albertel 7038: 			    if ($subp eq 'display') {
                   7039: 				$value.=' [Part: '.$part.']';
                   7040: 			    }
1.599     albertel 7041: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7042: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7043: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7044: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7045: 			    }
1.599     albertel 7046: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7047: 				$metaentry{':'.$unikey}=
                   7048: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7049: 			    }
1.339     albertel 7050: 			}
                   7051: 		    }
                   7052: 		} else {
1.172     www      7053: #
                   7054: # This is not a package - some other kind of start tag
1.339     albertel 7055: #
                   7056: 		    my $entry=$token->[1];
                   7057: 		    my $unikey;
                   7058: 		    if ($entry eq 'import') {
                   7059: 			$unikey='';
                   7060: 		    } else {
                   7061: 			$unikey=$entry;
                   7062: 		    }
                   7063: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7064: 
                   7065: 		    if (defined($token->[2]->{'id'})) { 
                   7066: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7067: 		    }
1.175     www      7068: 
1.339     albertel 7069: 		    if ($entry eq 'import') {
1.175     www      7070: #
                   7071: # Importing a library here
1.339     albertel 7072: #
                   7073: 			if ($depthcount<20) {
                   7074: 			    my $location=$parser->get_text('/import');
                   7075: 			    my $dir=$filename;
                   7076: 			    $dir=~s|[^/]*$||;
                   7077: 			    $location=&filelocation($dir,$location);
1.736     albertel 7078: 			    my $metadata = 
                   7079: 				&metadata($uri,'keys', $location,$unikey,
                   7080: 					  $depthcount+1);
                   7081: 			    foreach my $meta (split(',',$metadata)) {
                   7082: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7083: 				$metathesekeys{$meta}=1;
1.339     albertel 7084: 			    }
                   7085: 			}
                   7086: 		    } else { 
                   7087: 			
                   7088: 			if (defined($token->[2]->{'name'})) { 
                   7089: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7090: 			}
                   7091: 			$metathesekeys{$unikey}=1;
1.736     albertel 7092: 			foreach my $param (@{$token->[3]}) {
                   7093: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7094: 				$token->[2]->{$param};
1.339     albertel 7095: 			}
                   7096: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7097: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7098: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7099: 		 # only ws inside the tag, and not in default, so use default
                   7100: 		 # as value
1.599     albertel 7101: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7102: 			} elsif ( $internaltext =~ /\S/ ) {
                   7103: 		  # something interesting inside the tag
                   7104: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7105: 			} else {
1.908     albertel 7106: 		  # no interesting values, don't set a default
1.339     albertel 7107: 			}
1.172     www      7108: # end of not-a-package not-a-library import
1.339     albertel 7109: 		    }
1.172     www      7110: # end of not-a-package start tag
1.339     albertel 7111: 		}
1.172     www      7112: # the next is the end of "start tag"
1.339     albertel 7113: 	    }
                   7114: 	}
1.483     albertel 7115: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7116: 	$extension = lc($extension);
                   7117: 	if ($extension eq 'htm') { $extension='html'; }
                   7118: 
1.737     albertel 7119: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7120: 	    #no specific packages #how's our extension
                   7121: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7122: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7123: 					 \%metathesekeys);
                   7124: 	}
1.883     albertel 7125: 
                   7126: 	if (!exists($metaentry{':packages'})
                   7127: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7128: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7129: 		#no specific packages well let's get default then
                   7130: 		if ($key!~/^default&/) { next; }
1.488     albertel 7131: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7132: 					     \%metathesekeys);
                   7133: 	    }
                   7134: 	}
1.338     www      7135: # are there custom rights to evaluate
1.599     albertel 7136: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7137: 
1.338     www      7138:     #
                   7139:     # Importing a rights file here
1.339     albertel 7140:     #
                   7141: 	    unless ($depthcount) {
1.599     albertel 7142: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7143: 		my $dir=$filename;
                   7144: 		$dir=~s|[^/]*$||;
                   7145: 		$location=&filelocation($dir,$location);
1.736     albertel 7146: 		my $rights_metadata =
                   7147: 		    &metadata($uri,'keys',$location,'_rights',
                   7148: 			      $depthcount+1);
                   7149: 		foreach my $rights (split(',',$rights_metadata)) {
                   7150: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7151: 		    $metathesekeys{$rights}=1;
1.339     albertel 7152: 		}
                   7153: 	    }
                   7154: 	}
1.737     albertel 7155: 	# uniqifiy package listing
                   7156: 	my %seen;
                   7157: 	my @uniq_packages =
                   7158: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7159: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7160: 
                   7161: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7162: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7163: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7164: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7165: # this is the end of "was not already recently cached
1.71      www      7166:     }
1.599     albertel 7167:     return $metaentry{':'.$what};
1.261     albertel 7168: }
                   7169: 
1.488     albertel 7170: sub metadata_create_package_def {
1.483     albertel 7171:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7172:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7173:     if ($subp eq 'default') { next; }
                   7174:     
1.599     albertel 7175:     if (defined($metaentry{':packages'})) {
                   7176: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7177:     } else {
1.599     albertel 7178: 	$metaentry{':packages'}=$package;
1.483     albertel 7179:     }
                   7180:     my $value=$packagetab{$key};
                   7181:     my $unikey;
                   7182:     $unikey='parameter_0_'.$name;
1.599     albertel 7183:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7184:     $$metathesekeys{$unikey}=1;
1.599     albertel 7185:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7186: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7187:     }
1.599     albertel 7188:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7189: 	$metaentry{':'.$unikey}=
                   7190: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7191:     }
                   7192: }
                   7193: 
1.261     albertel 7194: sub metadata_generate_part0 {
                   7195:     my ($metadata,$metacache,$uri) = @_;
                   7196:     my %allnames;
1.737     albertel 7197:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7198: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7199: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7200: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7201: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7202: 	    $allnames{$name}=$part;
                   7203: 	  }
                   7204: 	}
                   7205:     }
                   7206:     foreach my $name (keys(%allnames)) {
                   7207:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7208:       my $key=":parameter_0_$name";
1.261     albertel 7209:       $$metacache{"$key.part"}='0';
                   7210:       $$metacache{"$key.name"}=$name;
1.428     albertel 7211:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7212: 					   $allnames{$name}.'_'.$name.
                   7213: 					   '.type'};
1.428     albertel 7214:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7215: 			     '.display'};
1.644     www      7216:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7217:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7218:       $$metacache{"$key.display"}=$olddis;
                   7219:     }
1.71      www      7220: }
                   7221: 
1.764     albertel 7222: # ------------------------------------------------------ Devalidate title cache
                   7223: 
                   7224: sub devalidate_title_cache {
                   7225:     my ($url)=@_;
                   7226:     if (!$env{'request.course.id'}) { return; }
                   7227:     my $symb=&symbread($url);
                   7228:     if (!$symb) { return; }
                   7229:     my $key=$env{'request.course.id'}."\0".$symb;
                   7230:     &devalidate_cache_new('title',$key);
                   7231: }
                   7232: 
1.301     www      7233: # ------------------------------------------------- Get the title of a resource
                   7234: 
                   7235: sub gettitle {
                   7236:     my $urlsymb=shift;
                   7237:     my $symb=&symbread($urlsymb);
1.534     albertel 7238:     if ($symb) {
1.620     albertel 7239: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7240: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7241: 	if (defined($cached)) { 
                   7242: 	    return $result;
                   7243: 	}
1.534     albertel 7244: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7245: 	my $title='';
1.907     albertel 7246: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7247: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7248: 	} else {
                   7249: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7250: 		    &GDBM_READER(),0640)) {
                   7251: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7252: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7253: 		untie(%bighash);
                   7254: 	    }
1.534     albertel 7255: 	}
                   7256: 	$title=~s/\&colon\;/\:/gs;
                   7257: 	if ($title) {
1.599     albertel 7258: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7259: 	}
                   7260: 	$urlsymb=$url;
                   7261:     }
                   7262:     my $title=&metadata($urlsymb,'title');
                   7263:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7264:     return $title;
1.301     www      7265: }
1.613     albertel 7266: 
1.614     albertel 7267: sub get_slot {
                   7268:     my ($which,$cnum,$cdom)=@_;
                   7269:     if (!$cnum || !$cdom) {
1.790     albertel 7270: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7271: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7272: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7273:     }
1.703     albertel 7274:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7275:     my %slotinfo;
                   7276:     if (exists($remembered{$key})) {
                   7277: 	$slotinfo{$which} = $remembered{$key};
                   7278:     } else {
                   7279: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7280: 	&Apache::lonhomework::showhash(%slotinfo);
                   7281: 	my ($tmp)=keys(%slotinfo);
                   7282: 	if ($tmp=~/^error:/) { return (); }
                   7283: 	$remembered{$key} = $slotinfo{$which};
                   7284:     }
1.616     albertel 7285:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7286: 	return %{$slotinfo{$which}};
                   7287:     }
                   7288:     return $slotinfo{$which};
1.614     albertel 7289: }
1.31      www      7290: # ------------------------------------------------- Update symbolic store links
                   7291: 
                   7292: sub symblist {
                   7293:     my ($mapname,%newhash)=@_;
1.438     www      7294:     $mapname=&deversion(&declutter($mapname));
1.31      www      7295:     my %hash;
1.620     albertel 7296:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7297:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7298:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7299: 	    foreach my $url (keys %newhash) {
                   7300: 		next if ($url eq 'last_known'
                   7301: 			 && $env{'form.no_update_last_known'});
                   7302: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7303: 						    $newhash{$url}->[1],
                   7304: 						    $newhash{$url}->[0]);
1.191     harris41 7305:             }
1.31      www      7306:             if (untie(%hash)) {
                   7307: 		return 'ok';
                   7308:             }
                   7309:         }
                   7310:     }
                   7311:     return 'error';
1.212     www      7312: }
                   7313: 
                   7314: # --------------------------------------------------------------- Verify a symb
                   7315: 
                   7316: sub symbverify {
1.510     www      7317:     my ($symb,$thisurl)=@_;
                   7318:     my $thisfn=$thisurl;
1.439     www      7319:     $thisfn=&declutter($thisfn);
1.215     www      7320: # direct jump to resource in page or to a sequence - will construct own symbs
                   7321:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7322: # check URL part
1.409     www      7323:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7324: 
1.431     www      7325:     unless ($url eq $thisfn) { return 0; }
1.213     www      7326: 
1.216     www      7327:     $symb=&symbclean($symb);
1.510     www      7328:     $thisurl=&deversion($thisurl);
1.439     www      7329:     $thisfn=&deversion($thisfn);
1.213     www      7330: 
                   7331:     my %bighash;
                   7332:     my $okay=0;
1.431     www      7333: 
1.620     albertel 7334:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7335:                             &GDBM_READER(),0640)) {
1.510     www      7336:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7337:         unless ($ids) { 
1.510     www      7338:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7339:         }
                   7340:         if ($ids) {
                   7341: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7342: 	    foreach my $id (split(/\,/,$ids)) {
                   7343: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7344:                if (
                   7345:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7346:    eq $symb) { 
1.620     albertel 7347: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7348: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7349: 		       $okay=1; 
                   7350: 		   }
                   7351: 	       }
1.216     www      7352: 	   }
                   7353:         }
1.213     www      7354: 	untie(%bighash);
                   7355:     }
                   7356:     return $okay;
1.31      www      7357: }
                   7358: 
1.210     www      7359: # --------------------------------------------------------------- Clean-up symb
                   7360: 
                   7361: sub symbclean {
                   7362:     my $symb=shift;
1.568     albertel 7363:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7364: # remove version from map
                   7365:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7366: 
1.210     www      7367: # remove version from URL
                   7368:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7369: 
1.507     www      7370: # remove wrapper
                   7371: 
1.510     www      7372:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7373:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7374:     return $symb;
1.409     www      7375: }
                   7376: 
                   7377: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7378: 
                   7379: sub encode_symb {
                   7380:     my ($map,$resid,$url)=@_;
                   7381:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7382: }
1.409     www      7383: 
                   7384: sub decode_symb {
1.568     albertel 7385:     my $symb=shift;
                   7386:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7387:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7388:     return (&fixversion($map),$resid,&fixversion($url));
                   7389: }
                   7390: 
                   7391: sub fixversion {
                   7392:     my $fn=shift;
1.609     banghart 7393:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7394:     my %bighash;
                   7395:     my $uri=&clutter($fn);
1.620     albertel 7396:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7397: # is this cached?
1.599     albertel 7398:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7399:     if (defined($cached)) { return $result; }
                   7400: # unfortunately not cached, or expired
1.620     albertel 7401:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7402: 	    &GDBM_READER(),0640)) {
                   7403:  	if ($bighash{'version_'.$uri}) {
                   7404:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7405:  	    unless (($version eq 'mostrecent') || 
                   7406: 		    ($version==&getversion($uri))) {
1.440     www      7407:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7408:  	    }
                   7409:  	}
                   7410:  	untie %bighash;
1.413     www      7411:     }
1.599     albertel 7412:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7413: }
                   7414: 
                   7415: sub deversion {
                   7416:     my $url=shift;
                   7417:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7418:     return $url;
1.210     www      7419: }
                   7420: 
1.31      www      7421: # ------------------------------------------------------ Return symb list entry
                   7422: 
                   7423: sub symbread {
1.249     www      7424:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7425:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7426:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7427: # no filename provided? try from environment
1.44      www      7428:     unless ($thisfn) {
1.620     albertel 7429:         if ($env{'request.symb'}) {
                   7430: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7431: 	}
1.620     albertel 7432: 	$thisfn=$env{'request.filename'};
1.44      www      7433:     }
1.569     albertel 7434:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7435: # is that filename actually a symb? Verify, clean, and return
                   7436:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7437: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7438: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7439: 	}
1.242     www      7440:     }
1.44      www      7441:     $thisfn=declutter($thisfn);
1.31      www      7442:     my %hash;
1.37      www      7443:     my %bighash;
                   7444:     my $syval='';
1.620     albertel 7445:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7446:         my $targetfn = $thisfn;
1.609     banghart 7447:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7448:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7449:         }
1.687     albertel 7450: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7451: 	    $targetfn=$1;
                   7452: 	}
1.620     albertel 7453:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7454:                       &GDBM_READER(),0640)) {
1.481     raeburn  7455: 	    $syval=$hash{$targetfn};
1.37      www      7456:             untie(%hash);
                   7457:         }
                   7458: # ---------------------------------------------------------- There was an entry
                   7459:         if ($syval) {
1.601     albertel 7460: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7461: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7462: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7463: 		    #return $env{$cache_str}='';
1.601     albertel 7464: 		#}    
                   7465: 		#$syval.=$1;
                   7466: 	    #}
1.37      www      7467:         } else {
                   7468: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7469:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7470:                             &GDBM_READER(),0640)) {
1.37      www      7471: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7472:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7473:               unless ($ids) { 
                   7474:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7475:               }
                   7476:               unless ($ids) {
                   7477: # alias?
                   7478: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7479:               }
1.37      www      7480:               if ($ids) {
                   7481: # ------------------------------------------------------------------- Has ID(s)
                   7482:                  my @possibilities=split(/\,/,$ids);
1.39      www      7483:                  if ($#possibilities==0) {
                   7484: # ----------------------------------------------- There is only one possibility
1.37      www      7485: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7486: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7487: 						    $resid,$thisfn);
1.249     www      7488:                  } elsif (!$donotrecurse) {
1.39      www      7489: # ------------------------------------------ There is more than one possibility
                   7490:                      my $realpossible=0;
1.800     albertel 7491:                      foreach my $id (@possibilities) {
                   7492: 			 my $file=$bighash{'src_'.$id};
1.39      www      7493:                          if (&allowed('bre',$file)) {
1.800     albertel 7494:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7495:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7496: 				$realpossible++;
1.626     albertel 7497:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7498: 						    $resid,$thisfn);
1.39      www      7499:                             }
                   7500: 			 }
1.191     harris41 7501:                      }
1.39      www      7502: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7503:                  } else {
                   7504:                      $syval='';
1.37      www      7505:                  }
                   7506: 	      }
                   7507:               untie(%bighash)
1.481     raeburn  7508:            }
1.31      www      7509:         }
1.62      www      7510:         if ($syval) {
1.620     albertel 7511: 	    return $env{$cache_str}=$syval;
1.62      www      7512:         }
1.31      www      7513:     }
1.949     raeburn  7514:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7515:     return $env{$cache_str}='';
1.31      www      7516: }
                   7517: 
                   7518: # ---------------------------------------------------------- Return random seed
                   7519: 
1.32      www      7520: sub numval {
                   7521:     my $txt=shift;
                   7522:     $txt=~tr/A-J/0-9/;
                   7523:     $txt=~tr/a-j/0-9/;
                   7524:     $txt=~tr/K-T/0-9/;
                   7525:     $txt=~tr/k-t/0-9/;
                   7526:     $txt=~tr/U-Z/0-5/;
                   7527:     $txt=~tr/u-z/0-5/;
                   7528:     $txt=~s/\D//g;
1.564     albertel 7529:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7530:     return int($txt);
1.368     albertel 7531: }
                   7532: 
1.484     albertel 7533: sub numval2 {
                   7534:     my $txt=shift;
                   7535:     $txt=~tr/A-J/0-9/;
                   7536:     $txt=~tr/a-j/0-9/;
                   7537:     $txt=~tr/K-T/0-9/;
                   7538:     $txt=~tr/k-t/0-9/;
                   7539:     $txt=~tr/U-Z/0-5/;
                   7540:     $txt=~tr/u-z/0-5/;
                   7541:     $txt=~s/\D//g;
                   7542:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7543:     my $total;
                   7544:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7545:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7546:     return int($total);
                   7547: }
                   7548: 
1.575     albertel 7549: sub numval3 {
                   7550:     use integer;
                   7551:     my $txt=shift;
                   7552:     $txt=~tr/A-J/0-9/;
                   7553:     $txt=~tr/a-j/0-9/;
                   7554:     $txt=~tr/K-T/0-9/;
                   7555:     $txt=~tr/k-t/0-9/;
                   7556:     $txt=~tr/U-Z/0-5/;
                   7557:     $txt=~tr/u-z/0-5/;
                   7558:     $txt=~s/\D//g;
                   7559:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7560:     my $total;
                   7561:     foreach my $val (@txts) { $total+=$val; }
                   7562:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7563:     return $total;
                   7564: }
                   7565: 
1.675     albertel 7566: sub digest {
                   7567:     my ($data)=@_;
                   7568:     my $digest=&Digest::MD5::md5($data);
                   7569:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7570:     my ($e,$f);
                   7571:     {
                   7572:         use integer;
                   7573:         $e=($a+$b);
                   7574:         $f=($c+$d);
                   7575:         if ($_64bit) {
                   7576:             $e=(($e<<32)>>32);
                   7577:             $f=(($f<<32)>>32);
                   7578:         }
                   7579:     }
                   7580:     if (wantarray) {
                   7581: 	return ($e,$f);
                   7582:     } else {
                   7583: 	my $g;
                   7584: 	{
                   7585: 	    use integer;
                   7586: 	    $g=($e+$f);
                   7587: 	    if ($_64bit) {
                   7588: 		$g=(($g<<32)>>32);
                   7589: 	    }
                   7590: 	}
                   7591: 	return $g;
                   7592:     }
                   7593: }
                   7594: 
1.368     albertel 7595: sub latest_rnd_algorithm_id {
1.675     albertel 7596:     return '64bit5';
1.366     albertel 7597: }
1.32      www      7598: 
1.503     albertel 7599: sub get_rand_alg {
                   7600:     my ($courseid)=@_;
1.790     albertel 7601:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7602:     if ($courseid) {
1.620     albertel 7603: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7604:     }
                   7605:     return &latest_rnd_algorithm_id();
                   7606: }
                   7607: 
1.562     albertel 7608: sub validCODE {
                   7609:     my ($CODE)=@_;
                   7610:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7611:     return 0;
                   7612: }
                   7613: 
1.491     albertel 7614: sub getCODE {
1.620     albertel 7615:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7616:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7617: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7618: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7619: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7620:     }
                   7621:     return undef;
                   7622: }
                   7623: 
1.31      www      7624: sub rndseed {
1.155     albertel 7625:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7626:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7627:     if (!defined($symb)) {
1.366     albertel 7628: 	unless ($symb=$wsymb) { return time; }
                   7629:     }
                   7630:     if (!$courseid) { $courseid=$wcourseid; }
                   7631:     if (!$domain) { $domain=$wdomain; }
                   7632:     if (!$username) { $username=$wusername }
1.503     albertel 7633:     my $which=&get_rand_alg();
1.803     albertel 7634: 
1.491     albertel 7635:     if (defined(&getCODE())) {
1.675     albertel 7636: 	if ($which eq '64bit5') {
                   7637: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7638: 	} elsif ($which eq '64bit4') {
1.575     albertel 7639: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7640: 	} else {
                   7641: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7642: 	}
1.675     albertel 7643:     } elsif ($which eq '64bit5') {
                   7644: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7645:     } elsif ($which eq '64bit4') {
                   7646: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7647:     } elsif ($which eq '64bit3') {
                   7648: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7649:     } elsif ($which eq '64bit2') {
                   7650: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7651:     } elsif ($which eq '64bit') {
                   7652: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7653:     }
                   7654:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7655: }
                   7656: 
                   7657: sub rndseed_32bit {
                   7658:     my ($symb,$courseid,$domain,$username)=@_;
                   7659:     {
                   7660: 	use integer;
                   7661: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7662: 	my $symbseed=numval($symb) << 22;
                   7663: 	my $namechck=unpack("%32C*",$username) << 17;
                   7664: 	my $nameseed=numval($username) << 12;
                   7665: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7666: 	my $courseseed=unpack("%32C*",$courseid);
                   7667: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7668: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7669: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7670: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7671: 	return $num;
                   7672:     }
                   7673: }
                   7674: 
                   7675: sub rndseed_64bit {
                   7676:     my ($symb,$courseid,$domain,$username)=@_;
                   7677:     {
                   7678: 	use integer;
                   7679: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7680: 	my $symbseed=numval($symb) << 10;
                   7681: 	my $namechck=unpack("%32S*",$username);
                   7682: 	
                   7683: 	my $nameseed=numval($username) << 21;
                   7684: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7685: 	my $courseseed=unpack("%32S*",$courseid);
                   7686: 	
                   7687: 	my $num1=$symbchck+$symbseed+$namechck;
                   7688: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7689: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7690: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7691: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7692: 	return "$num1,$num2";
1.155     albertel 7693:     }
1.366     albertel 7694: }
                   7695: 
1.443     albertel 7696: sub rndseed_64bit2 {
                   7697:     my ($symb,$courseid,$domain,$username)=@_;
                   7698:     {
                   7699: 	use integer;
                   7700: 	# strings need to be an even # of cahracters long, it it is odd the
                   7701:         # last characters gets thrown away
                   7702: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7703: 	my $symbseed=numval($symb) << 10;
                   7704: 	my $namechck=unpack("%32S*",$username.' ');
                   7705: 	
                   7706: 	my $nameseed=numval($username) << 21;
1.501     albertel 7707: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7708: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7709: 	
                   7710: 	my $num1=$symbchck+$symbseed+$namechck;
                   7711: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7712: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7713: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7714: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7715: 	return "$num1,$num2";
                   7716:     }
                   7717: }
                   7718: 
                   7719: sub rndseed_64bit3 {
                   7720:     my ($symb,$courseid,$domain,$username)=@_;
                   7721:     {
                   7722: 	use integer;
                   7723: 	# strings need to be an even # of cahracters long, it it is odd the
                   7724:         # last characters gets thrown away
                   7725: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7726: 	my $symbseed=numval2($symb) << 10;
                   7727: 	my $namechck=unpack("%32S*",$username.' ');
                   7728: 	
                   7729: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7730: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7731: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7732: 	
                   7733: 	my $num1=$symbchck+$symbseed+$namechck;
                   7734: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7735: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7736: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7737: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7738: 	
1.503     albertel 7739: 	return "$num1:$num2";
1.443     albertel 7740:     }
                   7741: }
                   7742: 
1.575     albertel 7743: sub rndseed_64bit4 {
                   7744:     my ($symb,$courseid,$domain,$username)=@_;
                   7745:     {
                   7746: 	use integer;
                   7747: 	# strings need to be an even # of cahracters long, it it is odd the
                   7748:         # last characters gets thrown away
                   7749: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7750: 	my $symbseed=numval3($symb) << 10;
                   7751: 	my $namechck=unpack("%32S*",$username.' ');
                   7752: 	
                   7753: 	my $nameseed=numval3($username) << 21;
                   7754: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7755: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7756: 	
                   7757: 	my $num1=$symbchck+$symbseed+$namechck;
                   7758: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7759: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7760: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7761: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7762: 	
                   7763: 	return "$num1:$num2";
                   7764:     }
                   7765: }
                   7766: 
1.675     albertel 7767: sub rndseed_64bit5 {
                   7768:     my ($symb,$courseid,$domain,$username)=@_;
                   7769:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7770:     return "$num1:$num2";
                   7771: }
                   7772: 
1.366     albertel 7773: sub rndseed_CODE_64bit {
                   7774:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7775:     {
1.366     albertel 7776: 	use integer;
1.443     albertel 7777: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7778: 	my $symbseed=numval2($symb);
1.491     albertel 7779: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7780: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7781: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7782: 	my $num1=$symbseed+$CODEchck;
                   7783: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7784: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7785: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7786: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7787: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7788: 	return "$num1:$num2";
1.366     albertel 7789:     }
                   7790: }
                   7791: 
1.575     albertel 7792: sub rndseed_CODE_64bit4 {
                   7793:     my ($symb,$courseid,$domain,$username)=@_;
                   7794:     {
                   7795: 	use integer;
                   7796: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7797: 	my $symbseed=numval3($symb);
                   7798: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7799: 	my $CODEseed=numval3(&getCODE());
                   7800: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7801: 	my $num1=$symbseed+$CODEchck;
                   7802: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7803: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7804: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7805: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7806: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7807: 	return "$num1:$num2";
                   7808:     }
                   7809: }
                   7810: 
1.675     albertel 7811: sub rndseed_CODE_64bit5 {
                   7812:     my ($symb,$courseid,$domain,$username)=@_;
                   7813:     my $code = &getCODE();
                   7814:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7815:     return "$num1:$num2";
                   7816: }
                   7817: 
1.366     albertel 7818: sub setup_random_from_rndseed {
                   7819:     my ($rndseed)=@_;
1.503     albertel 7820:     if ($rndseed =~/([,:])/) {
                   7821: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7822: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7823:     } else {
                   7824: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7825:     }
1.36      albertel 7826: }
                   7827: 
1.474     albertel 7828: sub latest_receipt_algorithm_id {
1.835     albertel 7829:     return 'receipt3';
1.474     albertel 7830: }
                   7831: 
1.480     www      7832: sub recunique {
                   7833:     my $fucourseid=shift;
                   7834:     my $unique;
1.835     albertel 7835:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7836: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7837: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7838:     } else {
                   7839: 	$unique=$perlvar{'lonReceipt'};
                   7840:     }
                   7841:     return unpack("%32C*",$unique);
                   7842: }
                   7843: 
                   7844: sub recprefix {
                   7845:     my $fucourseid=shift;
                   7846:     my $prefix;
1.835     albertel 7847:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7848: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7849: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7850:     } else {
                   7851: 	$prefix=$perlvar{'lonHostID'};
                   7852:     }
                   7853:     return unpack("%32C*",$prefix);
                   7854: }
                   7855: 
1.76      www      7856: sub ireceipt {
1.474     albertel 7857:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7858: 
                   7859:     my $return =&recprefix($fucourseid).'-';
                   7860: 
                   7861:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7862: 	$env{'request.state'} eq 'construct') {
                   7863: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7864: 	return $return;
                   7865:     }
                   7866: 
1.76      www      7867:     my $cuname=unpack("%32C*",$funame);
                   7868:     my $cudom=unpack("%32C*",$fudom);
                   7869:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7870:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7871:     my $cunique=&recunique($fucourseid);
1.474     albertel 7872:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7873:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7874: 
1.790     albertel 7875: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7876: 			       
                   7877: 	$return.= ($cunique%$cuname+
                   7878: 		   $cunique%$cudom+
                   7879: 		   $cusymb%$cuname+
                   7880: 		   $cusymb%$cudom+
                   7881: 		   $cucourseid%$cuname+
                   7882: 		   $cucourseid%$cudom+
                   7883: 		   $cpart%$cuname+
                   7884: 		   $cpart%$cudom);
                   7885:     } else {
                   7886: 	$return.= ($cunique%$cuname+
                   7887: 		   $cunique%$cudom+
                   7888: 		   $cusymb%$cuname+
                   7889: 		   $cusymb%$cudom+
                   7890: 		   $cucourseid%$cuname+
                   7891: 		   $cucourseid%$cudom);
                   7892:     }
                   7893:     return $return;
1.76      www      7894: }
                   7895: 
                   7896: sub receipt {
1.474     albertel 7897:     my ($part)=@_;
1.790     albertel 7898:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7899:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7900: }
1.260     ng       7901: 
1.790     albertel 7902: sub whichuser {
                   7903:     my ($passedsymb)=@_;
                   7904:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7905:     if (defined($env{'form.grade_symb'})) {
                   7906: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7907: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7908: 	if (!$allowed &&
                   7909: 	    exists($env{'request.course.sec'}) &&
                   7910: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7911: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7912: 			      '/'.$env{'request.course.sec'});
                   7913: 	}
                   7914: 	if ($allowed) {
                   7915: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7916: 	    $courseid=$tmp_courseid;
                   7917: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7918: 	    ($name)=&get_env_multiple('form.grade_username');
                   7919: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7920: 	}
                   7921:     }
                   7922:     if (!$passedsymb) {
                   7923: 	$symb=&symbread();
                   7924:     } else {
                   7925: 	$symb=$passedsymb;
                   7926:     }
                   7927:     $courseid=$env{'request.course.id'};
                   7928:     $domain=$env{'user.domain'};
                   7929:     $name=$env{'user.name'};
                   7930:     if ($name eq 'public' && $domain eq 'public') {
                   7931: 	if (!defined($env{'form.username'})) {
                   7932: 	    $env{'form.username'}.=time.rand(10000000);
                   7933: 	}
                   7934: 	$name.=$env{'form.username'};
                   7935:     }
                   7936:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7937: 
                   7938: }
                   7939: 
1.36      albertel 7940: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7941: # returns either the contents of the file or 
                   7942: # -1 if the file doesn't exist
1.481     raeburn  7943: #
                   7944: # if the target is a file that was uploaded via DOCS, 
                   7945: # a check will be made to see if a current copy exists on the local server,
                   7946: # if it does this will be served, otherwise a copy will be retrieved from
                   7947: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7948: # the local server.   
1.472     albertel 7949: 
1.36      albertel 7950: sub getfile {
1.538     albertel 7951:     my ($file) = @_;
1.609     banghart 7952:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7953:     &repcopy($file);
                   7954:     return &readfile($file);
                   7955: }
                   7956: 
                   7957: sub repcopy_userfile {
                   7958:     my ($file)=@_;
1.609     banghart 7959:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7960:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7961:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7962: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7963:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7964:     if (-e "$file") {
1.828     www      7965: # we already have a local copy, check it out
1.538     albertel 7966: 	my @fileinfo = stat($file);
1.828     www      7967: 	my $rtncode;
                   7968: 	my $info;
1.538     albertel 7969: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7970: 	if ($lwpresp ne 'ok') {
1.828     www      7971: # there is no such file anymore, even though we had a local copy
1.482     albertel 7972: 	    if ($rtncode eq '404') {
1.538     albertel 7973: 		unlink($file);
1.482     albertel 7974: 	    }
                   7975: 	    return -1;
                   7976: 	}
                   7977: 	if ($info < $fileinfo[9]) {
1.828     www      7978: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7979: 	    return 'ok';
1.828     www      7980: 	} else {
                   7981: # the file is outdated, get rid of it
                   7982: 	    unlink($file);
1.482     albertel 7983: 	}
1.828     www      7984:     }
                   7985: # one way or the other, at this point, we don't have the file
                   7986: # construct the correct path for the file
                   7987:     my @parts = ($cdom,$cnum); 
                   7988:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7989: 	push @parts, split(/\//,$1);
                   7990:     }
                   7991:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7992:     foreach my $part (@parts) {
                   7993: 	$path .= '/'.$part;
                   7994: 	if (!-e $path) {
                   7995: 	    mkdir($path,0770);
1.482     albertel 7996: 	}
                   7997:     }
1.828     www      7998: # now the path exists for sure
                   7999: # get a user agent
                   8000:     my $ua=new LWP::UserAgent;
                   8001:     my $transferfile=$file.'.in.transfer';
                   8002: # FIXME: this should flock
                   8003:     if (-e $transferfile) { return 'ok'; }
                   8004:     my $request;
                   8005:     $uri=~s/^\///;
1.838     albertel 8006:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8007:     my $response=$ua->request($request,$transferfile);
                   8008: # did it work?
                   8009:     if ($response->is_error()) {
                   8010: 	unlink($transferfile);
                   8011: 	&logthis("Userfile repcopy failed for $uri");
                   8012: 	return -1;
                   8013:     }
                   8014: # worked, rename the transfer file
                   8015:     rename($transferfile,$file);
1.607     raeburn  8016:     return 'ok';
1.481     raeburn  8017: }
                   8018: 
1.517     albertel 8019: sub tokenwrapper {
                   8020:     my $uri=shift;
1.552     albertel 8021:     $uri=~s|^http\://([^/]+)||;
                   8022:     $uri=~s|^/||;
1.620     albertel 8023:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8024:     my $token=$1;
1.552     albertel 8025:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8026:     if ($udom && $uname && $file) {
                   8027: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8028:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8029:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8030:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8031:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8032:     } else {
                   8033:         return '/adm/notfound.html';
                   8034:     }
                   8035: }
                   8036: 
1.828     www      8037: # call with reqtype HEAD: get last modification time
                   8038: # call with reqtype GET: get the file contents
                   8039: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8040: #
1.481     raeburn  8041: sub getuploaded {
                   8042:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8043:     $uri=~s/^\///;
1.838     albertel 8044:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8045:     my $ua=new LWP::UserAgent;
                   8046:     my $request=new HTTP::Request($reqtype,$uri);
                   8047:     my $response=$ua->request($request);
                   8048:     $$rtncode = $response->code;
1.482     albertel 8049:     if (! $response->is_success()) {
                   8050: 	return 'failed';
                   8051:     }      
                   8052:     if ($reqtype eq 'HEAD') {
1.486     www      8053: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8054:     } elsif ($reqtype eq 'GET') {
                   8055: 	$$info = $response->content;
1.472     albertel 8056:     }
1.482     albertel 8057:     return 'ok';
1.36      albertel 8058: }
                   8059: 
1.481     raeburn  8060: sub readfile {
                   8061:     my $file = shift;
                   8062:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8063:     my $fh;
                   8064:     open($fh,"<$file");
                   8065:     my $a='';
1.800     albertel 8066:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8067:     return $a;
                   8068: }
                   8069: 
1.36      albertel 8070: sub filelocation {
1.590     banghart 8071:     my ($dir,$file) = @_;
                   8072:     my $location;
                   8073:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8074: 
                   8075:     if ($file =~ m-^/adm/-) {
                   8076: 	$file=~s-^/adm/wrapper/-/-;
                   8077: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8078:     }
1.882     albertel 8079: 
1.590     banghart 8080:     if ($file=~m:^/~:) { # is a contruction space reference
                   8081:         $location = $file;
                   8082:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8083:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8084: 	# is a correct contruction space reference
                   8085:         $location = $file;
1.609     banghart 8086:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8087:         my ($udom,$uname,$filename)=
1.811     albertel 8088:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8089:         my $home=&homeserver($uname,$udom);
                   8090:         my $is_me=0;
                   8091:         my @ids=&current_machine_ids();
                   8092:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8093:         if ($is_me) {
1.740     www      8094:   	    $location=&propath($udom,$uname).
1.590     banghart 8095:   	      '/userfiles/'.$filename;
                   8096:         } else {
                   8097:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8098:   	      $udom.'/'.$uname.'/'.$filename;
                   8099:         }
1.882     albertel 8100:     } elsif ($file =~ m-^/adm/-) {
                   8101: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8102:     } else {
                   8103:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8104:         $file=~s:^/res/:/:;
                   8105:         if ( !( $file =~ m:^/:) ) {
                   8106:             $location = $dir. '/'.$file;
                   8107:         } else {
                   8108:             $location = '/home/httpd/html/res'.$file;
                   8109:         }
1.59      albertel 8110:     }
1.590     banghart 8111:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8112:     while ($location=~m{/\.\./}) {
                   8113: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8114: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8115: 	} else {
                   8116: 	    $location=~ s{/\.\./}{/}g;
                   8117: 	}
                   8118:     } #remove dir/..
1.590     banghart 8119:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8120:     return $location;
1.46      www      8121: }
1.36      albertel 8122: 
1.46      www      8123: sub hreflocation {
                   8124:     my ($dir,$file)=@_;
1.460     albertel 8125:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8126: 	$file=filelocation($dir,$file);
1.700     albertel 8127:     } elsif ($file=~m-^/adm/-) {
                   8128: 	$file=~s-^/adm/wrapper/-/-;
                   8129: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8130:     }
                   8131:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8132: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8133:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8134: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8135:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8136: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8137: 	    -/uploaded/$1/$2/-x;
1.46      www      8138:     }
1.913     albertel 8139:     if ($file=~ m{^/userfiles/}) {
                   8140: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8141:     }
1.462     albertel 8142:     return $file;
1.465     albertel 8143: }
                   8144: 
                   8145: sub current_machine_domains {
1.853     albertel 8146:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8147: }
                   8148: 
                   8149: sub machine_domains {
                   8150:     my ($hostname) = @_;
1.465     albertel 8151:     my @domains;
1.838     albertel 8152:     my %hostname = &all_hostnames();
1.465     albertel 8153:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8154: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8155: 	if ($hostname eq $name) {
1.844     albertel 8156: 	    push(@domains,&host_domain($id));
1.465     albertel 8157: 	}
                   8158:     }
                   8159:     return @domains;
                   8160: }
                   8161: 
                   8162: sub current_machine_ids {
1.853     albertel 8163:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8164: }
                   8165: 
                   8166: sub machine_ids {
                   8167:     my ($hostname) = @_;
                   8168:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8169:     my @ids;
1.888     albertel 8170:     my %name_to_host = &all_names();
1.889     albertel 8171:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8172: 	return @{ $name_to_host{$hostname} };
                   8173:     }
                   8174:     return;
1.31      www      8175: }
                   8176: 
1.824     raeburn  8177: sub additional_machine_domains {
                   8178:     my @domains;
                   8179:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8180:     while( my $line = <$fh>) {
                   8181:         $line =~ s/\s//g;
                   8182:         push(@domains,$line);
                   8183:     }
                   8184:     return @domains;
                   8185: }
                   8186: 
                   8187: sub default_login_domain {
                   8188:     my $domain = $perlvar{'lonDefDomain'};
                   8189:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8190:     foreach my $posdom (&current_machine_domains(),
                   8191:                         &additional_machine_domains()) {
                   8192:         if (lc($posdom) eq lc($testdomain)) {
                   8193:             $domain=$posdom;
                   8194:             last;
                   8195:         }
                   8196:     }
                   8197:     return $domain;
                   8198: }
                   8199: 
1.31      www      8200: # ------------------------------------------------------------- Declutters URLs
                   8201: 
                   8202: sub declutter {
                   8203:     my $thisfn=shift;
1.569     albertel 8204:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8205:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8206:     $thisfn=~s/^\///;
1.697     albertel 8207:     $thisfn=~s|^adm/wrapper/||;
                   8208:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8209:     $thisfn=~s/^res\///;
1.235     www      8210:     $thisfn=~s/\?.+$//;
1.268     www      8211:     return $thisfn;
                   8212: }
                   8213: 
                   8214: # ------------------------------------------------------------- Clutter up URLs
                   8215: 
                   8216: sub clutter {
                   8217:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8218:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8219: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8220:        $thisfn='/res'.$thisfn; 
                   8221:     }
1.694     albertel 8222:     if ($thisfn !~m|/adm|) {
1.695     albertel 8223: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8224: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8225: 	} else {
                   8226: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8227: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8228: 	    if ($embstyle eq 'ssi'
                   8229: 		|| ($embstyle eq 'hdn')
                   8230: 		|| ($embstyle eq 'rat')
                   8231: 		|| ($embstyle eq 'prv')
                   8232: 		|| ($embstyle eq 'ign')) {
                   8233: 		#do nothing with these
                   8234: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8235: 		|| ($embstyle eq 'emb')
                   8236: 		|| ($embstyle eq 'wrp')) {
                   8237: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8238: 	    } elsif ($embstyle eq 'unk'
                   8239: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8240: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8241: 	    } else {
1.718     www      8242: #		&logthis("Got a blank emb style");
1.695     albertel 8243: 	    }
1.694     albertel 8244: 	}
                   8245:     }
1.31      www      8246:     return $thisfn;
1.12      www      8247: }
                   8248: 
1.787     albertel 8249: sub clutter_with_no_wrapper {
                   8250:     my $uri = &clutter(shift);
                   8251:     if ($uri =~ m-^/adm/-) {
                   8252: 	$uri =~ s-^/adm/wrapper/-/-;
                   8253: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8254:     }
                   8255:     return $uri;
                   8256: }
                   8257: 
1.557     albertel 8258: sub freeze_escape {
                   8259:     my ($value)=@_;
                   8260:     if (ref($value)) {
                   8261: 	$value=&nfreeze($value);
                   8262: 	return '__FROZEN__'.&escape($value);
                   8263:     }
                   8264:     return &escape($value);
                   8265: }
                   8266: 
1.11      www      8267: 
1.557     albertel 8268: sub thaw_unescape {
                   8269:     my ($value)=@_;
                   8270:     if ($value =~ /^__FROZEN__/) {
                   8271: 	substr($value,0,10,undef);
                   8272: 	$value=&unescape($value);
                   8273: 	return &thaw($value);
                   8274:     }
                   8275:     return &unescape($value);
                   8276: }
                   8277: 
1.436     albertel 8278: sub correct_line_ends {
                   8279:     my ($result)=@_;
                   8280:     $$result =~s/\r\n/\n/mg;
                   8281:     $$result =~s/\r/\n/mg;
1.415     albertel 8282: }
1.1       albertel 8283: # ================================================================ Main Program
                   8284: 
1.184     www      8285: sub goodbye {
1.204     albertel 8286:    &logthis("Starting Shut down");
1.443     albertel 8287: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8288:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8289: #converted
1.599     albertel 8290: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8291:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8292: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8293: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8294: #1.1 only
1.870     albertel 8295: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8296: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8297: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8298: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8299:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8300:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8301:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8302:    &flushcourselogs();
                   8303:    &logthis("Shutting down");
                   8304: }
                   8305: 
1.852     albertel 8306: sub get_dns {
1.869     albertel 8307:     my ($url,$func,$ignore_cache) = @_;
                   8308:     if (!$ignore_cache) {
                   8309: 	my ($content,$cached)=
                   8310: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8311: 	if ($cached) {
                   8312: 	    &$func($content);
                   8313: 	    return;
                   8314: 	}
                   8315:     }
                   8316: 
                   8317:     my %alldns;
1.852     albertel 8318:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8319:     foreach my $dns (<$config>) {
                   8320: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8321: 	$alldns{$1} = 1;
                   8322:     }
                   8323:     while (%alldns) {
                   8324: 	my ($dns) = keys(%alldns);
                   8325: 	delete($alldns{$dns});
1.852     albertel 8326: 	my $ua=new LWP::UserAgent;
                   8327: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8328: 	my $response=$ua->request($request);
                   8329: 	next if ($response->is_error());
                   8330: 	my @content = split("\n",$response->content);
1.869     albertel 8331: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8332: 	&$func(\@content);
1.869     albertel 8333: 	return;
1.852     albertel 8334:     }
                   8335:     close($config);
1.871     albertel 8336:     my $which = (split('/',$url))[3];
                   8337:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8338:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8339:     my @content = <$config>;
                   8340:     &$func(\@content);
                   8341:     return;
1.852     albertel 8342: }
1.327     albertel 8343: # ------------------------------------------------------------ Read domain file
                   8344: {
1.852     albertel 8345:     my $loaded;
1.846     albertel 8346:     my %domain;
                   8347: 
1.852     albertel 8348:     sub parse_domain_tab {
                   8349: 	my ($lines) = @_;
                   8350: 	foreach my $line (@$lines) {
                   8351: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8352: 
1.846     albertel 8353: 	    chomp($line);
1.852     albertel 8354: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8355: 	    my %this_domain;
                   8356: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8357: 			       'lang_def', 'city', 'longi', 'lati',
                   8358: 			       'primary') {
                   8359: 		$this_domain{$field} = shift(@elements);
                   8360: 	    }
                   8361: 	    $domain{$name} = \%this_domain;
1.852     albertel 8362: 	}
                   8363:     }
1.864     albertel 8364: 
                   8365:     sub reset_domain_info {
                   8366: 	undef($loaded);
                   8367: 	undef(%domain);
                   8368:     }
                   8369: 
1.852     albertel 8370:     sub load_domain_tab {
1.869     albertel 8371: 	my ($ignore_cache) = @_;
                   8372: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8373: 	my $fh;
                   8374: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8375: 	    my @lines = <$fh>;
                   8376: 	    &parse_domain_tab(\@lines);
1.448     albertel 8377: 	}
1.852     albertel 8378: 	close($fh);
                   8379: 	$loaded = 1;
1.327     albertel 8380:     }
1.846     albertel 8381: 
                   8382:     sub domain {
1.852     albertel 8383: 	&load_domain_tab() if (!$loaded);
                   8384: 
1.846     albertel 8385: 	my ($name,$what) = @_;
                   8386: 	return if ( !exists($domain{$name}) );
                   8387: 
                   8388: 	if (!$what) {
                   8389: 	    return $domain{$name}{'description'};
                   8390: 	}
                   8391: 	return $domain{$name}{$what};
                   8392:     }
1.327     albertel 8393: }
                   8394: 
                   8395: 
1.1       albertel 8396: # ------------------------------------------------------------- Read hosts file
                   8397: {
1.838     albertel 8398:     my %hostname;
1.844     albertel 8399:     my %hostdom;
1.845     albertel 8400:     my %libserv;
1.852     albertel 8401:     my $loaded;
1.888     albertel 8402:     my %name_to_host;
1.852     albertel 8403: 
                   8404:     sub parse_hosts_tab {
                   8405: 	my ($file) = @_;
                   8406: 	foreach my $configline (@$file) {
                   8407: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8408: 	    next if ($configline =~ /^\^/);
                   8409: 	    chomp($configline);
                   8410: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8411: 	    $name=~s/\s//g;
                   8412: 	    if ($id && $domain && $role && $name) {
                   8413: 		$hostname{$id}=$name;
1.888     albertel 8414: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8415: 		$hostdom{$id}=$domain;
                   8416: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8417: 	    }
                   8418: 	}
                   8419:     }
1.864     albertel 8420:     
                   8421:     sub reset_hosts_info {
1.897     albertel 8422: 	&purge_remembered();
1.864     albertel 8423: 	&reset_domain_info();
                   8424: 	&reset_hosts_ip_info();
1.892     albertel 8425: 	undef(%name_to_host);
1.864     albertel 8426: 	undef(%hostname);
                   8427: 	undef(%hostdom);
                   8428: 	undef(%libserv);
                   8429: 	undef($loaded);
                   8430:     }
1.1       albertel 8431: 
1.852     albertel 8432:     sub load_hosts_tab {
1.869     albertel 8433: 	my ($ignore_cache) = @_;
                   8434: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8435: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8436: 	my @config = <$config>;
                   8437: 	&parse_hosts_tab(\@config);
                   8438: 	close($config);
                   8439: 	$loaded=1;
1.1       albertel 8440:     }
1.852     albertel 8441: 
1.838     albertel 8442:     sub hostname {
1.852     albertel 8443: 	&load_hosts_tab() if (!$loaded);
                   8444: 
1.838     albertel 8445: 	my ($lonid) = @_;
                   8446: 	return $hostname{$lonid};
                   8447:     }
1.845     albertel 8448: 
1.838     albertel 8449:     sub all_hostnames {
1.852     albertel 8450: 	&load_hosts_tab() if (!$loaded);
                   8451: 
1.838     albertel 8452: 	return %hostname;
                   8453:     }
1.845     albertel 8454: 
1.888     albertel 8455:     sub all_names {
                   8456: 	&load_hosts_tab() if (!$loaded);
                   8457: 
                   8458: 	return %name_to_host;
                   8459:     }
                   8460: 
1.845     albertel 8461:     sub is_library {
1.852     albertel 8462: 	&load_hosts_tab() if (!$loaded);
                   8463: 
1.845     albertel 8464: 	return exists($libserv{$_[0]});
                   8465:     }
                   8466: 
                   8467:     sub all_library {
1.852     albertel 8468: 	&load_hosts_tab() if (!$loaded);
                   8469: 
1.845     albertel 8470: 	return %libserv;
                   8471:     }
                   8472: 
1.841     albertel 8473:     sub get_servers {
1.852     albertel 8474: 	&load_hosts_tab() if (!$loaded);
                   8475: 
1.841     albertel 8476: 	my ($domain,$type) = @_;
                   8477: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8478: 	                                          : %hostname;
                   8479: 	my %result;
1.842     albertel 8480: 	if (ref($domain) eq 'ARRAY') {
                   8481: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8482: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8483: 		    $result{$host} = $hostname;
                   8484: 		}
                   8485: 	    }
                   8486: 	} else {
                   8487: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8488: 		if ($hostdom{$host} eq $domain) {
                   8489: 		    $result{$host} = $hostname;
                   8490: 		}
1.841     albertel 8491: 	    }
                   8492: 	}
                   8493: 	return %result;
                   8494:     }
1.845     albertel 8495: 
1.844     albertel 8496:     sub host_domain {
1.852     albertel 8497: 	&load_hosts_tab() if (!$loaded);
                   8498: 
1.844     albertel 8499: 	my ($lonid) = @_;
                   8500: 	return $hostdom{$lonid};
                   8501:     }
                   8502: 
1.841     albertel 8503:     sub all_domains {
1.852     albertel 8504: 	&load_hosts_tab() if (!$loaded);
                   8505: 
1.841     albertel 8506: 	my %seen;
                   8507: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8508: 	return @uniq;
                   8509:     }
1.1       albertel 8510: }
                   8511: 
1.847     albertel 8512: { 
                   8513:     my %iphost;
1.856     albertel 8514:     my %name_to_ip;
                   8515:     my %lonid_to_ip;
1.869     albertel 8516: 
1.847     albertel 8517:     sub get_hosts_from_ip {
                   8518: 	my ($ip) = @_;
                   8519: 	my %iphosts = &get_iphost();
                   8520: 	if (ref($iphosts{$ip})) {
                   8521: 	    return @{$iphosts{$ip}};
                   8522: 	}
                   8523: 	return;
1.839     albertel 8524:     }
1.864     albertel 8525:     
                   8526:     sub reset_hosts_ip_info {
                   8527: 	undef(%iphost);
                   8528: 	undef(%name_to_ip);
                   8529: 	undef(%lonid_to_ip);
                   8530:     }
1.856     albertel 8531: 
                   8532:     sub get_host_ip {
                   8533: 	my ($lonid) = @_;
                   8534: 	if (exists($lonid_to_ip{$lonid})) {
                   8535: 	    return $lonid_to_ip{$lonid};
                   8536: 	}
                   8537: 	my $name=&hostname($lonid);
                   8538:    	my $ip = gethostbyname($name);
                   8539: 	return if (!$ip || length($ip) ne 4);
                   8540: 	$ip=inet_ntoa($ip);
                   8541: 	$name_to_ip{$name}   = $ip;
                   8542: 	$lonid_to_ip{$lonid} = $ip;
                   8543: 	return $ip;
                   8544:     }
1.847     albertel 8545:     
                   8546:     sub get_iphost {
1.869     albertel 8547: 	my ($ignore_cache) = @_;
1.894     albertel 8548: 
1.869     albertel 8549: 	if (!$ignore_cache) {
                   8550: 	    if (%iphost) {
                   8551: 		return %iphost;
                   8552: 	    }
                   8553: 	    my ($ip_info,$cached)=
                   8554: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8555: 	    if ($cached) {
                   8556: 		%iphost      = %{$ip_info->[0]};
                   8557: 		%name_to_ip  = %{$ip_info->[1]};
                   8558: 		%lonid_to_ip = %{$ip_info->[2]};
                   8559: 		return %iphost;
                   8560: 	    }
                   8561: 	}
1.894     albertel 8562: 
                   8563: 	# get yesterday's info for fallback
                   8564: 	my %old_name_to_ip;
                   8565: 	my ($ip_info,$cached)=
                   8566: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8567: 	if ($cached) {
                   8568: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8569: 	}
                   8570: 
1.888     albertel 8571: 	my %name_to_host = &all_names();
                   8572: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8573: 	    my $ip;
                   8574: 	    if (!exists($name_to_ip{$name})) {
                   8575: 		$ip = gethostbyname($name);
                   8576: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8577: 		    if (defined($old_name_to_ip{$name})) {
                   8578: 			$ip = $old_name_to_ip{$name};
                   8579: 			&logthis("Can't find $name defaulting to old $ip");
                   8580: 		    } else {
                   8581: 			&logthis("Name $name no IP found");
                   8582: 			next;
                   8583: 		    }
                   8584: 		} else {
                   8585: 		    $ip=inet_ntoa($ip);
1.847     albertel 8586: 		}
                   8587: 		$name_to_ip{$name} = $ip;
                   8588: 	    } else {
                   8589: 		$ip = $name_to_ip{$name};
1.653     albertel 8590: 	    }
1.888     albertel 8591: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8592: 		$lonid_to_ip{$id} = $ip;
                   8593: 	    }
                   8594: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8595: 	}
1.869     albertel 8596: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8597: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8598: 				      48*60*60);
1.869     albertel 8599: 
1.847     albertel 8600: 	return %iphost;
1.598     albertel 8601:     }
                   8602: }
                   8603: 
1.862     albertel 8604: BEGIN {
                   8605: 
                   8606: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8607:     unless ($readit) {
                   8608: {
                   8609:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8610:     %perlvar = (%perlvar,%{$configvars});
                   8611: }
                   8612: 
                   8613: 
1.1       albertel 8614: # ------------------------------------------------------ Read spare server file
                   8615: {
1.448     albertel 8616:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8617: 
                   8618:     while (my $configline=<$config>) {
                   8619:        chomp($configline);
1.284     matthew  8620:        if ($configline) {
1.784     albertel 8621: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8622: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8623: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8624:        }
                   8625:     }
1.448     albertel 8626:     close($config);
1.1       albertel 8627: }
1.11      www      8628: # ------------------------------------------------------------ Read permissions
                   8629: {
1.448     albertel 8630:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8631: 
                   8632:     while (my $configline=<$config>) {
1.448     albertel 8633: 	chomp($configline);
                   8634: 	if ($configline) {
                   8635: 	    my ($role,$perm)=split(/ /,$configline);
                   8636: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8637: 	}
1.11      www      8638:     }
1.448     albertel 8639:     close($config);
1.11      www      8640: }
                   8641: 
                   8642: # -------------------------------------------- Read plain texts for permissions
                   8643: {
1.448     albertel 8644:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8645: 
                   8646:     while (my $configline=<$config>) {
1.448     albertel 8647: 	chomp($configline);
                   8648: 	if ($configline) {
1.742     raeburn  8649: 	    my ($short,@plain)=split(/:/,$configline);
                   8650:             %{$prp{$short}} = ();
                   8651: 	    if (@plain > 0) {
                   8652:                 $prp{$short}{'std'} = $plain[0];
                   8653:                 for (my $i=1; $i<@plain; $i++) {
                   8654:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8655:                 }
                   8656:             }
1.448     albertel 8657: 	}
1.135     www      8658:     }
1.448     albertel 8659:     close($config);
1.135     www      8660: }
                   8661: 
                   8662: # ---------------------------------------------------------- Read package table
                   8663: {
1.448     albertel 8664:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8665: 
                   8666:     while (my $configline=<$config>) {
1.483     albertel 8667: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8668: 	chomp($configline);
                   8669: 	my ($short,$plain)=split(/:/,$configline);
                   8670: 	my ($pack,$name)=split(/\&/,$short);
                   8671: 	if ($plain ne '') {
                   8672: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8673: 	    $packagetab{$short}=$plain; 
                   8674: 	}
1.11      www      8675:     }
1.448     albertel 8676:     close($config);
1.329     matthew  8677: }
                   8678: 
                   8679: # ------------- set up temporary directory
                   8680: {
                   8681:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8682: 
1.11      www      8683: }
                   8684: 
1.794     albertel 8685: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8686: 				'compress_threshold'=> 20_000,
                   8687:  			        });
1.185     www      8688: 
1.281     www      8689: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8690: $dumpcount=0;
1.22      www      8691: 
1.163     harris41 8692: &logtouch();
1.672     albertel 8693: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8694: $readit=1;
1.564     albertel 8695:     {
                   8696: 	use integer;
                   8697: 	my $test=(2**32)+1;
1.568     albertel 8698: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8699: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8700:     }
1.195     www      8701: }
1.1       albertel 8702: }
1.179     www      8703: 
1.1       albertel 8704: 1;
1.191     harris41 8705: __END__
                   8706: 
1.243     albertel 8707: =pod
                   8708: 
1.191     harris41 8709: =head1 NAME
                   8710: 
1.243     albertel 8711: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8712: 
                   8713: =head1 SYNOPSIS
                   8714: 
1.243     albertel 8715: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8716: 
                   8717:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8718: 
1.243     albertel 8719: Common parameters:
                   8720: 
                   8721: =over 4
                   8722: 
                   8723: =item *
                   8724: 
                   8725: $uname : an internal username (if $cname expecting a course Id specifically)
                   8726: 
                   8727: =item *
                   8728: 
                   8729: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8730: 
                   8731: =item *
                   8732: 
                   8733: $symb : a resource instance identifier
                   8734: 
                   8735: =item *
                   8736: 
                   8737: $namespace : the name of a .db file that contains the data needed or
                   8738: being set.
                   8739: 
                   8740: =back
                   8741: 
1.394     bowersj2 8742: =head1 OVERVIEW
1.191     harris41 8743: 
1.394     bowersj2 8744: lonnet provides subroutines which interact with the
                   8745: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8746: about classes, users, and resources.
1.243     albertel 8747: 
                   8748: For many of these objects you can also use this to store data about
                   8749: them or modify them in various ways.
1.191     harris41 8750: 
1.394     bowersj2 8751: =head2 Symbs
1.191     harris41 8752: 
1.394     bowersj2 8753: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8754: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8755: map, the resource number of the resource in the map, and the URL of
                   8756: the resource itself. The latter is somewhat redundant, but might help
                   8757: if maps change.
                   8758: 
                   8759: An example is
                   8760: 
                   8761:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8762: 
                   8763: The respective map entry is
                   8764: 
                   8765:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8766:   title="Problem 2">
                   8767:  </resource>
                   8768: 
                   8769: Symbs are used by the random number generator, as well as to store and
                   8770: restore data specific to a certain instance of for example a problem.
                   8771: 
                   8772: =head2 Storing And Retrieving Data
                   8773: 
                   8774: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8775: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8776: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8777: is is the non-critical message twin of cstore. These functions are for
                   8778: handlers to store a perl hash to a user's permanent data space in an
                   8779: easy manner, and to retrieve it again on another call. It is expected
                   8780: that a handler would use this once at the beginning to retrieve data,
                   8781: and then again once at the end to send only the new data back.
                   8782: 
                   8783: The data is stored in the user's data directory on the user's
                   8784: homeserver under the ID of the course.
                   8785: 
                   8786: The hash that is returned by restore will have all of the previous
                   8787: value for all of the elements of the hash.
                   8788: 
                   8789: Example:
                   8790: 
                   8791:  #creating a hash
                   8792:  my %hash;
                   8793:  $hash{'foo'}='bar';
                   8794: 
                   8795:  #storing it
                   8796:  &Apache::lonnet::cstore(\%hash);
                   8797: 
                   8798:  #changing a value
                   8799:  $hash{'foo'}='notbar';
                   8800: 
                   8801:  #adding a new value
                   8802:  $hash{'bar'}='foo';
                   8803:  &Apache::lonnet::cstore(\%hash);
                   8804: 
                   8805:  #retrieving the hash
                   8806:  my %history=&Apache::lonnet::restore();
                   8807: 
                   8808:  #print the hash
                   8809:  foreach my $key (sort(keys(%history))) {
                   8810:    print("\%history{$key} = $history{$key}");
                   8811:  }
                   8812: 
                   8813: Will print out:
1.191     harris41 8814: 
1.394     bowersj2 8815:  %history{1:foo} = bar
                   8816:  %history{1:keys} = foo:timestamp
                   8817:  %history{1:timestamp} = 990455579
                   8818:  %history{2:bar} = foo
                   8819:  %history{2:foo} = notbar
                   8820:  %history{2:keys} = foo:bar:timestamp
                   8821:  %history{2:timestamp} = 990455580
                   8822:  %history{bar} = foo
                   8823:  %history{foo} = notbar
                   8824:  %history{timestamp} = 990455580
                   8825:  %history{version} = 2
                   8826: 
                   8827: Note that the special hash entries C<keys>, C<version> and
                   8828: C<timestamp> were added to the hash. C<version> will be equal to the
                   8829: total number of versions of the data that have been stored. The
                   8830: C<timestamp> attribute will be the UNIX time the hash was
                   8831: stored. C<keys> is available in every historical section to list which
                   8832: keys were added or changed at a specific historical revision of a
                   8833: hash.
                   8834: 
                   8835: B<Warning>: do not store the hash that restore returns directly. This
                   8836: will cause a mess since it will restore the historical keys as if the
                   8837: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8838: 
1.394     bowersj2 8839: Calling convention:
1.191     harris41 8840: 
1.394     bowersj2 8841:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8842:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8843: 
1.394     bowersj2 8844: For more detailed information, see lonnet specific documentation.
1.191     harris41 8845: 
1.394     bowersj2 8846: =head1 RETURN MESSAGES
1.191     harris41 8847: 
1.394     bowersj2 8848: =over 4
1.191     harris41 8849: 
1.394     bowersj2 8850: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8851: 
1.394     bowersj2 8852: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8853: when the connection is brought back up
1.191     harris41 8854: 
1.394     bowersj2 8855: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8856: for later delivery
1.191     harris41 8857: 
1.394     bowersj2 8858: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8859: 
1.394     bowersj2 8860: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8861: that was requested
1.191     harris41 8862: 
1.243     albertel 8863: =back
1.191     harris41 8864: 
1.243     albertel 8865: =head1 PUBLIC SUBROUTINES
1.191     harris41 8866: 
1.243     albertel 8867: =head2 Session Environment Functions
1.191     harris41 8868: 
1.243     albertel 8869: =over 4
1.191     harris41 8870: 
1.394     bowersj2 8871: =item * 
                   8872: X<appenv()>
1.949     raeburn  8873: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8874: the user envirnoment file, and will be restored for each access this
1.620     albertel 8875: user makes during this session, also modifies the %env for the current
1.949     raeburn  8876: process. Optional rolesarrayref - if defined contains a reference to an array
                   8877: of roles which are exempt from the restriction on modifying user.role entries 
                   8878: in the user's environment.db and in %env.    
1.191     harris41 8879: 
                   8880: =item *
1.394     bowersj2 8881: X<delenv()>
                   8882: B<delenv($regexp)>: removes all items from the session
                   8883: environment file that matches the regular expression in $regexp. The
1.620     albertel 8884: values are also delted from the current processes %env.
1.191     harris41 8885: 
1.795     albertel 8886: =item * get_env_multiple($name) 
                   8887: 
                   8888: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8889: values may be defined and end up as an array ref.
                   8890: 
                   8891: returns an array of values
                   8892: 
1.243     albertel 8893: =back
                   8894: 
                   8895: =head2 User Information
1.191     harris41 8896: 
1.243     albertel 8897: =over 4
1.191     harris41 8898: 
                   8899: =item *
1.394     bowersj2 8900: X<queryauthenticate()>
                   8901: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8902: authentication scheme
                   8903: 
                   8904: =item *
1.394     bowersj2 8905: X<authenticate()>
                   8906: B<authenticate($uname,$upass,$udom)>: try to
                   8907: authenticate user from domain's lib servers (first use the current
                   8908: one). C<$upass> should be the users password.
1.191     harris41 8909: 
                   8910: =item *
1.394     bowersj2 8911: X<homeserver()>
                   8912: B<homeserver($uname,$udom)>: find the server which has
                   8913: the user's directory and files (there must be only one), this caches
                   8914: the answer, and also caches if there is a borken connection.
1.191     harris41 8915: 
                   8916: =item *
1.394     bowersj2 8917: X<idget()>
                   8918: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8919: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8920: username, and only 1 username per ID in a specific domain) (returns
                   8921: hash: id=>name,id=>name)
1.191     harris41 8922: 
                   8923: =item *
1.394     bowersj2 8924: X<idrget()>
                   8925: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8926: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8927: 
                   8928: =item *
1.394     bowersj2 8929: X<idput()>
                   8930: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8931: 
                   8932: =item *
1.394     bowersj2 8933: X<rolesinit()>
                   8934: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8935: 
                   8936: =item *
1.551     albertel 8937: X<getsection()>
                   8938: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8939: course $cname, return section name/number or '' for "not in course"
                   8940: and '-1' for "no section"
                   8941: 
                   8942: =item *
1.394     bowersj2 8943: X<userenvironment()>
                   8944: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8945: passed in @what from the requested user's environment, returns a hash
                   8946: 
1.858     raeburn  8947: =item * 
                   8948: X<userlog_query()>
1.859     albertel 8949: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8950: activity.log file. %filters defines filters applied when parsing the
                   8951: log file. These can be start or end timestamps, or the type of action
                   8952: - log to look for Login or Logout events, check for Checkin or
                   8953: Checkout, role for role selection. The response is in the form
                   8954: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8955: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8956: 
1.243     albertel 8957: =back
                   8958: 
                   8959: =head2 User Roles
                   8960: 
                   8961: =over 4
                   8962: 
                   8963: =item *
                   8964: 
1.810     raeburn  8965: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8966:  F: full access
                   8967:  U,I,K: authentication modes (cxx only)
                   8968:  '': forbidden
                   8969:  1: user needs to choose course
                   8970:  2: browse allowed
1.766     albertel 8971:  A: passphrase authentication needed
1.243     albertel 8972: 
                   8973: =item *
                   8974: 
                   8975: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8976: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8977: and course level
                   8978: 
                   8979: =item *
                   8980: 
                   8981: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8982: explanation of a user role term
                   8983: 
1.832     raeburn  8984: =item *
                   8985: 
1.935     raeburn  8986: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8987: All arguments are optional. Returns a hash of a roles, either for
                   8988: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8989: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8990: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   8991: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   8992: For each key, value is set to colon-separated start and end times for
                   8993: the role.  If no username and domain are specified, will default to
1.934     raeburn  8994: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  8995: of role statuses (active, future or previous), roles 
                   8996: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8997: to restrict the list of roles reported. If no array ref is 
                   8998: provided for types, will default to return only active roles.
1.834     albertel 8999: 
1.243     albertel 9000: =back
                   9001: 
                   9002: =head2 User Modification
                   9003: 
                   9004: =over 4
                   9005: 
                   9006: =item *
                   9007: 
                   9008: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   9009: user for the level given by URL.  Optional start and end dates (leave empty
                   9010: string or zero for "no date")
1.191     harris41 9011: 
                   9012: =item *
                   9013: 
1.243     albertel 9014: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9015: change a users, password, possible return values are: ok,
                   9016: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9017: refused
1.191     harris41 9018: 
                   9019: =item *
                   9020: 
1.243     albertel 9021: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9022: 
                   9023: =item *
                   9024: 
1.243     albertel 9025: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9026: modify user
1.191     harris41 9027: 
                   9028: =item *
                   9029: 
1.286     matthew  9030: modifystudent
                   9031: 
                   9032: modify a students enrollment and identification information.
                   9033: The course id is resolved based on the current users environment.  
                   9034: This means the envoking user must be a course coordinator or otherwise
                   9035: associated with a course.
                   9036: 
1.297     matthew  9037: This call is essentially a wrapper for lonnet::modifyuser and
                   9038: lonnet::modify_student_enrollment
1.286     matthew  9039: 
                   9040: Inputs: 
                   9041: 
                   9042: =over 4
                   9043: 
                   9044: =item B<$udom> Students loncapa domain
                   9045: 
                   9046: =item B<$uname> Students loncapa login name
                   9047: 
                   9048: =item B<$uid> Students id/student number
                   9049: 
                   9050: =item B<$umode> Students authentication mode
                   9051: 
                   9052: =item B<$upass> Students password
                   9053: 
                   9054: =item B<$first> Students first name
                   9055: 
                   9056: =item B<$middle> Students middle name
                   9057: 
                   9058: =item B<$last> Students last name
                   9059: 
                   9060: =item B<$gene> Students generation
                   9061: 
                   9062: =item B<$usec> Students section in course
                   9063: 
                   9064: =item B<$end> Unix time of the roles expiration
                   9065: 
                   9066: =item B<$start> Unix time of the roles start date
                   9067: 
                   9068: =item B<$forceid> If defined, allow $uid to be changed
                   9069: 
                   9070: =item B<$desiredhome> server to use as home server for student
                   9071: 
                   9072: =back
1.297     matthew  9073: 
                   9074: =item *
                   9075: 
                   9076: modify_student_enrollment
                   9077: 
                   9078: Change a students enrollment status in a class.  The environment variable
                   9079: 'role.request.course' must be defined for this function to proceed.
                   9080: 
                   9081: Inputs:
                   9082: 
                   9083: =over 4
                   9084: 
                   9085: =item $udom, students domain
                   9086: 
                   9087: =item $uname, students name
                   9088: 
                   9089: =item $uid, students user id
                   9090: 
                   9091: =item $first, students first name
                   9092: 
                   9093: =item $middle
                   9094: 
                   9095: =item $last
                   9096: 
                   9097: =item $gene
                   9098: 
                   9099: =item $usec
                   9100: 
                   9101: =item $end
                   9102: 
                   9103: =item $start
                   9104: 
                   9105: =back
                   9106: 
1.191     harris41 9107: 
                   9108: =item *
                   9109: 
1.243     albertel 9110: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9111: custom role; give a custom role to a user for the level given by URL.  Specify
                   9112: name and domain of role author, and role name
1.191     harris41 9113: 
                   9114: =item *
                   9115: 
1.243     albertel 9116: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9117: 
                   9118: =item *
                   9119: 
1.243     albertel 9120: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9121: 
                   9122: =back
                   9123: 
                   9124: =head2 Course Infomation
                   9125: 
                   9126: =over 4
1.191     harris41 9127: 
                   9128: =item *
                   9129: 
1.631     albertel 9130: coursedescription($courseid) : returns a hash of information about the
                   9131: specified course id, including all environment settings for the
                   9132: course, the description of the course will be in the hash under the
                   9133: key 'description'
1.191     harris41 9134: 
                   9135: =item *
                   9136: 
1.624     albertel 9137: resdata($name,$domain,$type,@which) : request for current parameter
                   9138: setting for a specific $type, where $type is either 'course' or 'user',
                   9139: @what should be a list of parameters to ask about. This routine caches
                   9140: answers for 5 minutes.
1.243     albertel 9141: 
1.877     foxr     9142: =item *
                   9143: 
                   9144: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9145: data base, returning a hash that is keyed by the resource name and has
                   9146: values that are the resource value.  I believe that the timestamps and
                   9147: versions are also returned.
                   9148: 
                   9149: 
1.243     albertel 9150: =back
                   9151: 
                   9152: =head2 Course Modification
                   9153: 
                   9154: =over 4
1.191     harris41 9155: 
                   9156: =item *
                   9157: 
1.243     albertel 9158: writecoursepref($courseid,%prefs) : write preferences (environment
                   9159: database) for a course
1.191     harris41 9160: 
                   9161: =item *
                   9162: 
1.243     albertel 9163: createcourse($udom,$description,$url) : make/modify course
                   9164: 
                   9165: =back
                   9166: 
                   9167: =head2 Resource Subroutines
                   9168: 
                   9169: =over 4
1.191     harris41 9170: 
                   9171: =item *
                   9172: 
1.243     albertel 9173: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9174: 
                   9175: =item *
                   9176: 
1.243     albertel 9177: repcopy($filename) : subscribes to the requested file, and attempts to
                   9178: replicate from the owning library server, Might return
1.607     raeburn  9179: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9180: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9181: resource. Expects the local filesystem pathname
                   9182: (/home/httpd/html/res/....)
                   9183: 
                   9184: =back
                   9185: 
                   9186: =head2 Resource Information
                   9187: 
                   9188: =over 4
1.191     harris41 9189: 
                   9190: =item *
                   9191: 
1.243     albertel 9192: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9193: a vairety of different possible values, $varname should be a request
                   9194: string, and the other parameters can be used to specify who and what
                   9195: one is asking about.
                   9196: 
                   9197: Possible values for $varname are environment.lastname (or other item
                   9198: from the envirnment hash), user.name (or someother aspect about the
                   9199: user), resource.0.maxtries (or some other part and parameter of a
                   9200: resource)
1.204     albertel 9201: 
                   9202: =item *
                   9203: 
1.243     albertel 9204: directcondval($number) : get current value of a condition; reads from a state
                   9205: string
1.204     albertel 9206: 
                   9207: =item *
                   9208: 
1.243     albertel 9209: condval($condidx) : value of condition index based on state
1.204     albertel 9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9214: resource's metadata, $what should be either a specific key, or either
                   9215: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9216: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9217: 
                   9218: this function automatically caches all requests
1.191     harris41 9219: 
                   9220: =item *
                   9221: 
1.243     albertel 9222: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9223: network of library servers; returns file handle of where SQL and regex results
                   9224: will be stored for query
1.191     harris41 9225: 
                   9226: =item *
                   9227: 
1.243     albertel 9228: symbread($filename) : return symbolic list entry (filename argument optional);
                   9229: returns the data handle
1.191     harris41 9230: 
                   9231: =item *
                   9232: 
1.243     albertel 9233: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9234: a possible symb for the URL in $thisfn, and if is an encryypted
                   9235: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9236: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9237: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9238: 
1.191     harris41 9239: 
                   9240: =item *
                   9241: 
1.243     albertel 9242: symbclean($symb) : removes versions numbers from a symb, returns the
                   9243: cleaned symb
1.191     harris41 9244: 
                   9245: =item *
                   9246: 
1.243     albertel 9247: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9248: course map, user must be in a course for it to work.
1.191     harris41 9249: 
                   9250: =item *
                   9251: 
1.243     albertel 9252: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9253: 
                   9254: =item *
                   9255: 
1.243     albertel 9256: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9257: a random seed, all arguments are optional, if they aren't sent it uses the
                   9258: environment to derive them. Note: if symb isn't sent and it can't get one
                   9259: from &symbread it will use the current time as its return value
1.191     harris41 9260: 
                   9261: =item *
                   9262: 
1.243     albertel 9263: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9264: unfakeable, receipt
1.191     harris41 9265: 
                   9266: =item *
                   9267: 
1.620     albertel 9268: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9269: 
                   9270: =item *
                   9271: 
1.243     albertel 9272: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9273: 
                   9274: =item *
                   9275: 
1.243     albertel 9276: 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 9277: 
                   9278: =item *
                   9279: 
1.243     albertel 9280: 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 9281: 
                   9282: =item *
                   9283: 
1.243     albertel 9284: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9285: 
                   9286: =item *
                   9287: 
1.243     albertel 9288: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9289: forcing spreadsheet to reevaluate the resource scores next time.
                   9290: 
                   9291: =back
                   9292: 
                   9293: =head2 Storing/Retreiving Data
                   9294: 
                   9295: =over 4
1.191     harris41 9296: 
                   9297: =item *
                   9298: 
1.243     albertel 9299: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9300: for this url; hashref needs to be given and should be a \%hashname; the
                   9301: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9302: be derived from the env
1.191     harris41 9303: 
                   9304: =item *
                   9305: 
1.243     albertel 9306: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9307: uses critical subroutine
1.191     harris41 9308: 
                   9309: =item *
                   9310: 
1.243     albertel 9311: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9312: all args are optional
1.191     harris41 9313: 
                   9314: =item *
                   9315: 
1.717     albertel 9316: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9317: dumps the complete (or key matching regexp) namespace into a hash
                   9318: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9319: normally &store()ed into
                   9320: 
                   9321: $range should be either an integer '100' (give me the first 100
                   9322:                                            matching records)
                   9323:               or be  two integers sperated by a - with no spaces
                   9324:                  '30-50' (give me the 30th through the 50th matching
                   9325:                           records)
                   9326: 
                   9327: 
                   9328: =item *
                   9329: 
                   9330: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9331: replaces a &store() version of data with a replacement set of data
                   9332: for a particular resource in a namespace passed in the $storehash hash 
                   9333: reference
                   9334: 
                   9335: =item *
                   9336: 
1.243     albertel 9337: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9338: works very similar to store/cstore, but all data is stored in a
                   9339: temporary location and can be reset using tmpreset, $storehash should
                   9340: be a hash reference, returns nothing on success
1.191     harris41 9341: 
                   9342: =item *
                   9343: 
1.243     albertel 9344: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9345: similar to restore, but all data is stored in a temporary location and
                   9346: can be reset using tmpreset. Returns a hash of values on success,
                   9347: error string otherwise.
1.191     harris41 9348: 
                   9349: =item *
                   9350: 
1.243     albertel 9351: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9352: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9353: 
                   9354: =item *
                   9355: 
1.243     albertel 9356: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9357: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9358: 
                   9359: =item *
                   9360: 
1.243     albertel 9361: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9362: namesp ($udom and $uname are optional)
1.191     harris41 9363: 
                   9364: =item *
                   9365: 
1.702     albertel 9366: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9367: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9368: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9369: 
1.702     albertel 9370: $range should be either an integer '100' (give me the first 100
                   9371:                                            matching records)
                   9372:               or be  two integers sperated by a - with no spaces
                   9373:                  '30-50' (give me the 30th through the 50th matching
                   9374:                           records)
1.449     matthew  9375: =item *
                   9376: 
                   9377: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9378: $store can be a scalar, an array reference, or if the amount to be 
                   9379: incremented is > 1, a hash reference.
                   9380: 
                   9381: ($udom and $uname are optional)
1.191     harris41 9382: 
                   9383: =item *
                   9384: 
1.243     albertel 9385: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9386: ($udom and $uname are optional)
1.191     harris41 9387: 
                   9388: =item *
                   9389: 
1.243     albertel 9390: cput($namespace,$storehash,$udom,$uname) : critical put
                   9391: ($udom and $uname are optional)
1.191     harris41 9392: 
                   9393: =item *
                   9394: 
1.748     albertel 9395: newput($namespace,$storehash,$udom,$uname) :
                   9396: 
                   9397: Attempts to store the items in the $storehash, but only if they don't
                   9398: currently exist, if this succeeds you can be certain that you have 
                   9399: successfully created a new key value pair in the $namespace db.
                   9400: 
                   9401: 
                   9402: Args:
                   9403:  $namespace: name of database to store values to
                   9404:  $storehash: hashref to store to the db
                   9405:  $udom: (optional) domain of user containing the db
                   9406:  $uname: (optional) name of user caontaining the db
                   9407: 
                   9408: Returns:
                   9409:  'ok' -> succeeded in storing all keys of $storehash
                   9410:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9411:                         least <key> already existed in the db (other
                   9412:                         requested keys may also already exist)
                   9413:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9414:  'con_lost' -> unable to contact request server
                   9415:  'refused' -> action was not allowed by remote machine
                   9416: 
                   9417: 
                   9418: =item *
                   9419: 
1.243     albertel 9420: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9421: reference filled in from namesp (encrypts the return communication)
                   9422: ($udom and $uname are optional)
1.191     harris41 9423: 
                   9424: =item *
                   9425: 
1.243     albertel 9426: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9427: critical subroutine
                   9428: 
1.806     raeburn  9429: =item *
                   9430: 
1.860     raeburn  9431: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9432: array reference filled in from namespace found in domain level on either
                   9433: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9434: 
                   9435: =item *
                   9436: 
1.860     raeburn  9437: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9438: domain level either on specified domain server ($uhome) or primary domain 
                   9439: server ($udom and $uhome are optional)
1.806     raeburn  9440: 
1.943     raeburn  9441: =item * 
                   9442: 
                   9443: get_domain_defaults($target_domain) : returns hash with defaults for
                   9444: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9445: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9446: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9447: Values are retrieved from cache (if current), or from domain's configuration.db
                   9448: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9449: or lonTabs/domain.tab. 
                   9450: 
                   9451: %domdefaults = &get_auth_defaults($target_domain);
                   9452: 
1.243     albertel 9453: =back
                   9454: 
                   9455: =head2 Network Status Functions
                   9456: 
                   9457: =over 4
1.191     harris41 9458: 
                   9459: =item *
                   9460: 
                   9461: dirlist($uri) : return directory list based on URI
                   9462: 
                   9463: =item *
                   9464: 
1.243     albertel 9465: spareserver() : find server with least workload from spare.tab
                   9466: 
                   9467: =back
                   9468: 
                   9469: =head2 Apache Request
                   9470: 
                   9471: =over 4
1.191     harris41 9472: 
                   9473: =item *
                   9474: 
1.243     albertel 9475: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9476: localhost, posts hash
                   9477: 
                   9478: =back
                   9479: 
                   9480: =head2 Data to String to Data
                   9481: 
                   9482: =over 4
1.191     harris41 9483: 
                   9484: =item *
                   9485: 
1.243     albertel 9486: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9487: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9488: 
                   9489: =item *
                   9490: 
1.243     albertel 9491: hashref2str($hashref) : convert a hashref into a string complete with
                   9492: escaping and '=' and '&' separators, supports elements that are
                   9493: arrayrefs and hashrefs
1.191     harris41 9494: 
                   9495: =item *
                   9496: 
1.243     albertel 9497: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9498: with escaping and '&' separators, supports elements that are arrayrefs
                   9499: and hashrefs
1.191     harris41 9500: 
                   9501: =item *
                   9502: 
1.243     albertel 9503: str2hash($string) : convert string to hash using unescaping and
                   9504: splitting on '=' and '&', supports elements that are arrayrefs and
                   9505: hashrefs
1.191     harris41 9506: 
                   9507: =item *
                   9508: 
1.243     albertel 9509: str2array($string) : convert string to hash using unescaping and
                   9510: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9511: 
                   9512: =back
                   9513: 
                   9514: =head2 Logging Routines
                   9515: 
                   9516: =over 4
                   9517: 
                   9518: These routines allow one to make log messages in the lonnet.log and
                   9519: lonnet.perm logfiles.
1.191     harris41 9520: 
                   9521: =item *
                   9522: 
1.243     albertel 9523: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9524: 
                   9525: =item *
                   9526: 
1.243     albertel 9527: logthis() : append message to the normal lonnet.log file, it gets
                   9528: preiodically rolled over and deleted.
1.191     harris41 9529: 
                   9530: =item *
                   9531: 
1.243     albertel 9532: logperm() : append a permanent message to lonnet.perm.log, this log
                   9533: file never gets deleted by any automated portion of the system, only
                   9534: messages of critical importance should go in here.
                   9535: 
                   9536: =back
                   9537: 
                   9538: =head2 General File Helper Routines
                   9539: 
                   9540: =over 4
1.191     harris41 9541: 
                   9542: =item *
                   9543: 
1.481     raeburn  9544: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9545: (a) files in /uploaded
                   9546:   (i) If a local copy of the file exists - 
                   9547:       compares modification date of local copy with last-modified date for 
                   9548:       definitive version stored on home server for course. If local copy is 
                   9549:       stale, requests a new version from the home server and stores it. 
                   9550:       If the original has been removed from the home server, then local copy 
                   9551:       is unlinked.
                   9552:   (ii) If local copy does not exist -
                   9553:       requests the file from the home server and stores it. 
                   9554:   
                   9555:   If $caller is 'uploadrep':  
                   9556:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9557:     for request for files originally uploaded via DOCS. 
                   9558:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9559:   
                   9560:   Otherwise:
                   9561:      This indicates a call from the content generation phase of the request.
                   9562:      -  returns the entire contents of the file or -1.
                   9563:      
                   9564: (b) files in /res
                   9565:    - returns the entire contents of a file or -1; 
                   9566:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9567: 
1.712     albertel 9568: 
                   9569: =item *
                   9570: 
                   9571: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9572:                   reference
                   9573: 
                   9574: returns either a stat() list of data about the file or an empty list
                   9575: if the file doesn't exist or couldn't find out about it (connection
                   9576: problems or user unknown)
                   9577: 
1.191     harris41 9578: =item *
                   9579: 
1.243     albertel 9580: filelocation($dir,$file) : returns file system location of a file
                   9581: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9582: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9583: and a file of ../bob will become /a/bob)
1.191     harris41 9584: 
                   9585: =item *
                   9586: 
                   9587: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9588: filelocation except for hrefs
                   9589: 
                   9590: =item *
                   9591: 
                   9592: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9593: 
1.243     albertel 9594: =back
                   9595: 
1.608     albertel 9596: =head2 Usererfile file routines (/uploaded*)
                   9597: 
                   9598: =over 4
                   9599: 
                   9600: =item *
                   9601: 
                   9602: userfileupload(): main rotine for putting a file in a user or course's
                   9603:                   filespace, arguments are,
                   9604: 
1.620     albertel 9605:  formname - required - this is the name of the element in $env where the
1.608     albertel 9606:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9607:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9608:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9609:  coursedoc - if true, store the file in the course of the active role
                   9610:              of the current user
                   9611:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9612:          if undefined, it will be placed in "unknown"
                   9613: 
                   9614:  (This routine calls clean_filename() to remove any dangerous
                   9615:  characters from the filename, and then calls finuserfileupload() to
                   9616:  complete the transaction)
                   9617: 
                   9618:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9619:  and /adm/notfound.html if unsuccessful
                   9620: 
                   9621: =item *
                   9622: 
                   9623: clean_filename(): routine for cleaing a filename up for storage in
                   9624:                  userfile space, argument is:
                   9625: 
                   9626:  filename - proposed filename
                   9627: 
                   9628: returns: the new clean filename
                   9629: 
                   9630: =item *
                   9631: 
                   9632: finishuserfileupload(): routine that creaes and sends the file to
                   9633: userspace, probably shouldn't be called directly
                   9634: 
                   9635:   docuname: username or courseid of destination for the file
                   9636:   docudom: domain of user/course of destination for the file
                   9637:   formname: same as for userfileupload()
                   9638:   fname: filename (inculding subdirectories) for the file
                   9639: 
                   9640:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9641:  and /adm/notfound.html if unsuccessful
                   9642: 
                   9643: =item *
                   9644: 
                   9645: renameuserfile(): renames an existing userfile to a new name
                   9646: 
                   9647:   Args:
                   9648:    docuname: username or courseid of destination for the file
                   9649:    docudom: domain of user/course of destination for the file
                   9650:    old: current file name (including any subdirs under userfiles)
                   9651:    new: desired file name (including any subdirs under userfiles)
                   9652: 
                   9653: =item *
                   9654: 
                   9655: mkdiruserfile(): creates a directory is a userfiles dir
                   9656: 
                   9657:   Args:
                   9658:    docuname: username or courseid of destination for the file
                   9659:    docudom: domain of user/course of destination for the file
                   9660:    dir: dir to create (including any subdirs under userfiles)
                   9661: 
                   9662: =item *
                   9663: 
                   9664: removeuserfile(): removes a file that exists in userfiles
                   9665: 
                   9666:   Args:
                   9667:    docuname: username or courseid of destination for the file
                   9668:    docudom: domain of user/course of destination for the file
                   9669:    fname: filname to delete (including any subdirs under userfiles)
                   9670: 
                   9671: =item *
                   9672: 
                   9673: removeuploadedurl(): convience function for removeuserfile()
                   9674: 
                   9675:   Args:
                   9676:    url:  a full /uploaded/... url to delete
                   9677: 
1.747     albertel 9678: =item * 
                   9679: 
                   9680: get_portfile_permissions():
                   9681:   Args:
                   9682:     domain: domain of user or course contain the portfolio files
                   9683:     user: name of user or num of course contain the portfolio files
                   9684:   Returns:
                   9685:     hashref of a dump of the proper file_permissions.db
                   9686:    
                   9687: 
                   9688: =item * 
                   9689: 
                   9690: get_access_controls():
                   9691: 
                   9692: Args:
                   9693:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9694:   group: (optional) the group you want the files associated with
                   9695:   file: (optional) the file you want access info on
                   9696: 
                   9697: Returns:
1.749     raeburn  9698:     a hash (keys are file names) of hashes containing
                   9699:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9700:         values are XML containing access control settings (see below) 
1.747     albertel 9701: 
                   9702: Internal notes:
                   9703: 
1.749     raeburn  9704:  access controls are stored in file_permissions.db as key=value pairs.
                   9705:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9706:         where scope -> public,guest,course,group,domains or users.
                   9707:               end -> UNIX time for end of access (0 -> no end date)
                   9708:               start -> UNIX time for start of access
                   9709: 
                   9710:     value -> XML description of access control
                   9711:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9712:             <start></start>
                   9713:             <end></end>
                   9714: 
                   9715:             <password></password>  for scope type = guest
                   9716: 
                   9717:             <domain></domain>     for scope type = course or group
                   9718:             <number></number>
                   9719:             <roles id="">
                   9720:              <role></role>
                   9721:              <access></access>
                   9722:              <section></section>
                   9723:              <group></group>
                   9724:             </roles>
                   9725: 
                   9726:             <dom></dom>         for scope type = domains
                   9727: 
                   9728:             <users>             for scope type = users
                   9729:              <user>
                   9730:               <uname></uname>
                   9731:               <udom></udom>
                   9732:              </user>
                   9733:             </users>
                   9734:            </scope> 
                   9735:               
                   9736:  Access data is also aggregated for each file in an additional key=value pair:
                   9737:  key -> path to file/file_name\0accesscontrol 
                   9738:  value -> reference to hash
                   9739:           hash contains key = value pairs
                   9740:           where key = uniqueID:scope_end_start
                   9741:                 value = UNIX time record was last updated
                   9742: 
                   9743:           Used to improve speed of look-ups of access controls for each file.  
                   9744:  
                   9745:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9746: 
                   9747: modify_access_controls():
                   9748: 
                   9749: Modifies access controls for a portfolio file
                   9750: Args
                   9751: 1. file name
                   9752: 2. reference to hash of required changes,
                   9753: 3. domain
                   9754: 4. username
                   9755:   where domain,username are the domain of the portfolio owner 
                   9756:   (either a user or a course) 
                   9757: 
                   9758: Returns:
                   9759: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9760: 2. result of deletions ('ok' or 'error', with error message).
                   9761: 3. reference to hash of any new or updated access controls.
                   9762: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9763:    key = integer (inbound ID)
                   9764:    value = uniqueID  
1.747     albertel 9765: 
1.608     albertel 9766: =back
                   9767: 
1.243     albertel 9768: =head2 HTTP Helper Routines
                   9769: 
                   9770: =over 4
                   9771: 
1.191     harris41 9772: =item *
                   9773: 
                   9774: escape() : unpack non-word characters into CGI-compatible hex codes
                   9775: 
                   9776: =item *
                   9777: 
                   9778: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9779: 
1.243     albertel 9780: =back
                   9781: 
                   9782: =head1 PRIVATE SUBROUTINES
                   9783: 
                   9784: =head2 Underlying communication routines (Shouldn't call)
                   9785: 
                   9786: =over 4
                   9787: 
                   9788: =item *
                   9789: 
                   9790: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9791: 
                   9792: =item *
                   9793: 
                   9794: reply() : uses subreply to send a message to remote machine, logs all failures
                   9795: 
                   9796: =item *
                   9797: 
                   9798: critical() : passes a critical message to another server; if cannot
                   9799: get through then place message in connection buffer directory and
                   9800: returns con_delayed, if incapable of saving message, returns
                   9801: con_failed
                   9802: 
                   9803: =item *
                   9804: 
                   9805: reconlonc() : tries to reconnect lonc client processes.
                   9806: 
                   9807: =back
                   9808: 
                   9809: =head2 Resource Access Logging
                   9810: 
                   9811: =over 4
                   9812: 
                   9813: =item *
                   9814: 
                   9815: flushcourselogs() : flush (save) buffer logs and access logs
                   9816: 
                   9817: =item *
                   9818: 
                   9819: courselog($what) : save message for course in hash
                   9820: 
                   9821: =item *
                   9822: 
                   9823: courseacclog($what) : save message for course using &courselog().  Perform
                   9824: special processing for specific resource types (problems, exams, quizzes, etc).
                   9825: 
1.191     harris41 9826: =item *
                   9827: 
                   9828: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9829: as a PerlChildExitHandler
1.243     albertel 9830: 
                   9831: =back
                   9832: 
                   9833: =head2 Other
                   9834: 
                   9835: =over 4
                   9836: 
                   9837: =item *
                   9838: 
                   9839: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9840: 
                   9841: =back
                   9842: 
                   9843: =cut
1.877     foxr     9844: 

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