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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.953   ! www         4: # $Id: lonnet.pm,v 1.952 2008/03/24 05:23:19 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.953   ! www      1696:     my $output='';
        !          1697:     my $response;
        !          1698:     if ($filelink=~/^http\:/) {
        !          1699:        $output=&externalssi($filelink);
        !          1700:     } else {
        !          1701:        ($output,$response)=&ssi($filelink,%form);
        !          1702:     }
1.778     albertel 1703:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1704:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1705:     $output=~s/\<\/body\s*\>.*?$//si;
1.953   ! www      1706:     if (wantarray) {
        !          1707:         return ($output, $response);
        !          1708:     } else {
        !          1709:         return $output;
        !          1710:     }
1.8       www      1711: }
                   1712: 
1.15      www      1713: # --------------------------------------------------------- Server Side Include
                   1714: 
1.782     albertel 1715: sub absolute_url {
                   1716:     my ($host_name) = @_;
                   1717:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1718:     if ($host_name eq '') {
                   1719: 	$host_name = $ENV{'SERVER_NAME'};
                   1720:     }
                   1721:     return $protocol.$host_name;
                   1722: }
                   1723: 
1.942     foxr     1724: #
                   1725: #   Server side include.
                   1726: # Parameters:
                   1727: #  fn     Possibly encrypted resource name/id.
                   1728: #  form   Hash that describes how the rendering should be done
                   1729: #         and other things.
1.944     foxr     1730: # Returns:
1.950     raeburn  1731: #   Scalar context: The content of the response.
                   1732: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1733: #     
1.15      www      1734: sub ssi {
                   1735: 
1.944     foxr     1736:     my ($fn,%form)=@_;
1.15      www      1737:     my $ua=new LWP::UserAgent;
1.23      www      1738:     my $request;
1.711     albertel 1739: 
                   1740:     $form{'no_update_last_known'}=1;
1.895     albertel 1741:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1742:     if (%form) {
1.782     albertel 1743:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1744:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1745:     } else {
1.782     albertel 1746:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1747:     }
                   1748: 
1.15      www      1749:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1750:     my $response=$ua->request($request);
                   1751: 
1.944     foxr     1752:     if (wantarray) {
                   1753: 	return ($response->content, $response);
                   1754:     } else {
                   1755: 	return $response->content;
1.942     foxr     1756:     }
1.324     www      1757: }
                   1758: 
                   1759: sub externalssi {
                   1760:     my ($url)=@_;
                   1761:     my $ua=new LWP::UserAgent;
                   1762:     my $request=new HTTP::Request('GET',$url);
                   1763:     my $response=$ua->request($request);
1.15      www      1764:     return $response->content;
                   1765: }
1.254     www      1766: 
1.492     albertel 1767: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1768: 
                   1769: sub allowuploaded {
                   1770:     my ($srcurl,$url)=@_;
                   1771:     $url=&clutter(&declutter($url));
                   1772:     my $dir=$url;
                   1773:     $dir=~s/\/[^\/]+$//;
                   1774:     my %httpref=();
                   1775:     my $httpurl=&hreflocation('',$url);
                   1776:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1777:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1778: }
1.477     raeburn  1779: 
1.478     albertel 1780: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1781: # input: action, courseID, current domain, intended
1.637     raeburn  1782: #        path to file, source of file, instruction to parse file for objects,
                   1783: #        ref to hash for embedded objects,
                   1784: #        ref to hash for codebase of java objects.
                   1785: #
1.485     raeburn  1786: # output: url to file (if action was uploaddoc), 
                   1787: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1788: #
1.478     albertel 1789: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1790: # course.
1.477     raeburn  1791: #
1.478     albertel 1792: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1793: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1794: #          course's home server.
1.477     raeburn  1795: #
1.478     albertel 1796: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1797: #          be copied from $source (current location) to 
                   1798: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1799: #         and will then be copied to
                   1800: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1801: #         course's home server.
1.485     raeburn  1802: #
1.481     raeburn  1803: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1804: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1805: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1806: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1807: #         in course's home server.
1.637     raeburn  1808: #
1.477     raeburn  1809: 
                   1810: sub process_coursefile {
1.638     albertel 1811:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1812:     my $fetchresult;
1.638     albertel 1813:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1814:     if ($action eq 'propagate') {
1.638     albertel 1815:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1816: 			     $home);
1.481     raeburn  1817:     } else {
1.477     raeburn  1818:         my $fpath = '';
                   1819:         my $fname = $file;
1.478     albertel 1820:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1821:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1822:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1823:         if ($action eq 'copy') {
                   1824:             if ($source eq '') {
                   1825:                 $fetchresult = 'no source file';
                   1826:                 return $fetchresult;
                   1827:             } else {
                   1828:                 my $destination = $filepath.'/'.$fname;
                   1829:                 rename($source,$destination);
                   1830:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1831:                                  $home);
1.481     raeburn  1832:             }
                   1833:         } elsif ($action eq 'uploaddoc') {
                   1834:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1835:             print $fh $env{'form.'.$source};
1.481     raeburn  1836:             close($fh);
1.637     raeburn  1837:             if ($parser eq 'parse') {
                   1838:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1839:                 unless ($parse_result eq 'ok') {
                   1840:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1841:                 }
                   1842:             }
1.477     raeburn  1843:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1844:                                  $home);
1.481     raeburn  1845:             if ($fetchresult eq 'ok') {
                   1846:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1847:             } else {
                   1848:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1849:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1850:                 return '/adm/notfound.html';
                   1851:             }
1.477     raeburn  1852:         }
                   1853:     }
1.485     raeburn  1854:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1855:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1856:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1857:     }
                   1858:     return $fetchresult;
                   1859: }
                   1860: 
1.637     raeburn  1861: sub build_filepath {
                   1862:     my ($fpath) = @_;
                   1863:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1864:     unless ($fpath eq '') {
                   1865:         my @parts=split('/',$fpath);
                   1866:         foreach my $part (@parts) {
                   1867:             $filepath.= '/'.$part;
                   1868:             if ((-e $filepath)!=1) {
                   1869:                 mkdir($filepath,0777);
                   1870:             }
                   1871:         }
                   1872:     }
                   1873:     return $filepath;
                   1874: }
                   1875: 
                   1876: sub store_edited_file {
1.638     albertel 1877:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1878:     my $file = $primary_url;
                   1879:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1880:     my $fpath = '';
                   1881:     my $fname = $file;
                   1882:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1883:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1884:     my $filepath = &build_filepath($fpath);
                   1885:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1886:     print $fh $content;
                   1887:     close($fh);
1.638     albertel 1888:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1889:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1890: 			  $home);
1.637     raeburn  1891:     if ($$fetchresult eq 'ok') {
                   1892:         return '/uploaded/'.$fpath.'/'.$fname;
                   1893:     } else {
1.638     albertel 1894:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1895: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1896:         return '/adm/notfound.html';
                   1897:     }
                   1898: }
                   1899: 
1.531     albertel 1900: sub clean_filename {
1.831     albertel 1901:     my ($fname,$args)=@_;
1.315     www      1902: # Replace Windows backslashes by forward slashes
1.257     www      1903:     $fname=~s/\\/\//g;
1.831     albertel 1904:     if (!$args->{'keep_path'}) {
                   1905:         # Get rid of everything but the actual filename
                   1906: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1907:     }
1.315     www      1908: # Replace spaces by underscores
                   1909:     $fname=~s/\s+/\_/g;
                   1910: # Replace all other weird characters by nothing
1.831     albertel 1911:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1912: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1913: # numbers
                   1914:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1915:     return $fname;
                   1916: }
                   1917: 
1.608     albertel 1918: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1919: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1920: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1921: #        $coursedoc - if true up to the current course
                   1922: #                     if false
                   1923: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1924: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1925: #        $allfiles - reference to hash for embedded objects
                   1926: #        $codebase - reference to hash for codebase of java objects
                   1927: #        $desuname - username for permanent storage of uploaded file
                   1928: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1929: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1930: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1931: # 
1.686     albertel 1932: # output: url of file in userspace, or error: <message> 
                   1933: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1934: 
                   1935: 
1.531     albertel 1936: sub userfileupload {
1.860     raeburn  1937:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1938:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1939:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1940:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1941:     $fname=&clean_filename($fname);
1.315     www      1942: # See if there is anything left
1.257     www      1943:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1944:     chop($env{'form.'.$formname});
1.523     raeburn  1945:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1946:         my $now = time;
                   1947:         my $filepath = 'tmp/helprequests/'.$now;
                   1948:         my @parts=split(/\//,$filepath);
                   1949:         my $fullpath = $perlvar{'lonDaemons'};
                   1950:         for (my $i=0;$i<@parts;$i++) {
                   1951:             $fullpath .= '/'.$parts[$i];
                   1952:             if ((-e $fullpath)!=1) {
                   1953:                 mkdir($fullpath,0777);
                   1954:             }
                   1955:         }
                   1956:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1957:         print $fh $env{'form.'.$formname};
1.523     raeburn  1958:         close($fh);
1.741     raeburn  1959:         return $fullpath.'/'.$fname;
                   1960:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1961:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1962:                        '_'.$env{'user.domain'}.'/pending';
                   1963:         my @parts=split(/\//,$filepath);
                   1964:         my $fullpath = $perlvar{'lonDaemons'};
                   1965:         for (my $i=0;$i<@parts;$i++) {
                   1966:             $fullpath .= '/'.$parts[$i];
                   1967:             if ((-e $fullpath)!=1) {
                   1968:                 mkdir($fullpath,0777);
                   1969:             }
                   1970:         }
                   1971:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1972:         print $fh $env{'form.'.$formname};
                   1973:         close($fh);
                   1974:         return $fullpath.'/'.$fname;
1.523     raeburn  1975:     }
1.719     banghart 1976:     
1.258     www      1977: # Create the directory if not present
1.493     albertel 1978:     $fname="$subdir/$fname";
1.259     www      1979:     if ($coursedoc) {
1.638     albertel 1980: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1981: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1982:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1983:             return &finishuserfileupload($docuname,$docudom,
                   1984: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1985: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1986:         } else {
1.620     albertel 1987:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1988:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1989: 				       $fname,$formname,$parser,
                   1990: 				       $allfiles,$codebase);
1.481     raeburn  1991:         }
1.719     banghart 1992:     } elsif (defined($destuname)) {
                   1993:         my $docuname=$destuname;
                   1994:         my $docudom=$destudom;
1.860     raeburn  1995: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1996: 				     $parser,$allfiles,$codebase,
                   1997:                                      $thumbwidth,$thumbheight);
1.719     banghart 1998:         
1.259     www      1999:     } else {
1.638     albertel 2000:         my $docuname=$env{'user.name'};
                   2001:         my $docudom=$env{'user.domain'};
1.714     raeburn  2002:         if (exists($env{'form.group'})) {
                   2003:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2004:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2005:         }
1.860     raeburn  2006: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2007: 				     $parser,$allfiles,$codebase,
                   2008:                                      $thumbwidth,$thumbheight);
1.259     www      2009:     }
1.271     www      2010: }
                   2011: 
                   2012: sub finishuserfileupload {
1.860     raeburn  2013:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2014:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2015:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2016:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2017:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2018:     $file=$fname;
                   2019:     if ($fname=~m|/|) {
                   2020:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2021: 	$path.=$fnamepath.'/';
                   2022:     }
1.259     www      2023:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2024:     my $count;
                   2025:     for ($count=4;$count<=$#parts;$count++) {
                   2026:         $filepath.="/$parts[$count]";
                   2027:         if ((-e $filepath)!=1) {
                   2028: 	    mkdir($filepath,0777);
                   2029:         }
                   2030:     }
                   2031: # Save the file
                   2032:     {
1.701     albertel 2033: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2034: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2035: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2036: 	    return '/adm/notfound.html';
                   2037: 	}
                   2038: 	if (!print FH ($env{'form.'.$formname})) {
                   2039: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2040: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2041: 	    return '/adm/notfound.html';
                   2042: 	}
1.570     albertel 2043: 	close(FH);
1.258     www      2044:     }
1.637     raeburn  2045:     if ($parser eq 'parse') {
1.638     albertel 2046:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2047: 						   $codebase);
1.637     raeburn  2048:         unless ($parse_result eq 'ok') {
1.638     albertel 2049:             &logthis('Failed to parse '.$filepath.$file.
                   2050: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2051:         }
                   2052:     }
1.860     raeburn  2053:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2054:         my $input = $filepath.'/'.$file;
                   2055:         my $output = $filepath.'/'.'tn-'.$file;
                   2056:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2057:         system("convert -sample $thumbsize $input $output");
                   2058:         if (-e $filepath.'/'.'tn-'.$file) {
                   2059:             $fetchthumb  = 1; 
                   2060:         }
                   2061:     }
1.858     raeburn  2062:  
1.259     www      2063: # Notify homeserver to grep it
                   2064: #
1.638     albertel 2065:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2066:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2067:     if ($fetchresult eq 'ok') {
1.860     raeburn  2068:         if ($fetchthumb) {
                   2069:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2070:             if ($thumbresult ne 'ok') {
                   2071:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2072:                          $docuhome.': '.$thumbresult);
                   2073:             }
                   2074:         }
1.259     www      2075: #
1.258     www      2076: # Return the URL to it
1.494     albertel 2077:         return '/uploaded/'.$path.$file;
1.263     www      2078:     } else {
1.494     albertel 2079:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2080: 		 ': '.$fetchresult);
1.263     www      2081:         return '/adm/notfound.html';
1.858     raeburn  2082:     }
1.493     albertel 2083: }
                   2084: 
1.637     raeburn  2085: sub extract_embedded_items {
1.648     raeburn  2086:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2087:     my @state = ();
                   2088:     my %javafiles = (
                   2089:                       codebase => '',
                   2090:                       code => '',
                   2091:                       archive => ''
                   2092:                     );
                   2093:     my %mediafiles = (
                   2094:                       src => '',
                   2095:                       movie => '',
                   2096:                      );
1.648     raeburn  2097:     my $p;
                   2098:     if ($content) {
                   2099:         $p = HTML::LCParser->new($content);
                   2100:     } else {
                   2101:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2102:     }
1.641     albertel 2103:     while (my $t=$p->get_token()) {
1.640     albertel 2104: 	if ($t->[0] eq 'S') {
                   2105: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2106: 	    push(@state, $tagname);
1.648     raeburn  2107:             if (lc($tagname) eq 'allow') {
                   2108:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2109:             }
1.640     albertel 2110: 	    if (lc($tagname) eq 'img') {
                   2111: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2112: 	    }
1.886     albertel 2113: 	    if (lc($tagname) eq 'a') {
                   2114: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2115: 	    }
1.645     raeburn  2116:             if (lc($tagname) eq 'script') {
                   2117:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2118:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2119:                 } else {
                   2120:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2121:                 }
                   2122:             }
                   2123:             if (lc($tagname) eq 'link') {
                   2124:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2125:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2126:                 }
                   2127:             }
1.640     albertel 2128: 	    if (lc($tagname) eq 'object' ||
                   2129: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2130: 		foreach my $item (keys(%javafiles)) {
                   2131: 		    $javafiles{$item} = '';
                   2132: 		}
                   2133: 	    }
                   2134: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2135: 		my $name = lc($attr->{'name'});
                   2136: 		foreach my $item (keys(%javafiles)) {
                   2137: 		    if ($name eq $item) {
                   2138: 			$javafiles{$item} = $attr->{'value'};
                   2139: 			last;
                   2140: 		    }
                   2141: 		}
                   2142: 		foreach my $item (keys(%mediafiles)) {
                   2143: 		    if ($name eq $item) {
                   2144: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2145: 			last;
                   2146: 		    }
                   2147: 		}
                   2148: 	    }
                   2149: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2150: 		foreach my $item (keys(%javafiles)) {
                   2151: 		    if ($attr->{$item}) {
                   2152: 			$javafiles{$item} = $attr->{$item};
                   2153: 			last;
                   2154: 		    }
                   2155: 		}
                   2156: 		foreach my $item (keys(%mediafiles)) {
                   2157: 		    if ($attr->{$item}) {
                   2158: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2159: 			last;
                   2160: 		    }
                   2161: 		}
                   2162: 	    }
                   2163: 	} elsif ($t->[0] eq 'E') {
                   2164: 	    my ($tagname) = ($t->[1]);
                   2165: 	    if ($javafiles{'codebase'} ne '') {
                   2166: 		$javafiles{'codebase'} .= '/';
                   2167: 	    }  
                   2168: 	    if (lc($tagname) eq 'applet' ||
                   2169: 		lc($tagname) eq 'object' ||
                   2170: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2171: 		) {
                   2172: 		foreach my $item (keys(%javafiles)) {
                   2173: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2174: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2175: 			&add_filetype($allfiles,$file,$item);
                   2176: 		    }
                   2177: 		}
                   2178: 	    } 
                   2179: 	    pop @state;
                   2180: 	}
                   2181:     }
1.637     raeburn  2182:     return 'ok';
                   2183: }
                   2184: 
1.639     albertel 2185: sub add_filetype {
                   2186:     my ($allfiles,$file,$type)=@_;
                   2187:     if (exists($allfiles->{$file})) {
                   2188: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2189: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2190: 	}
                   2191:     } else {
                   2192: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2193:     }
                   2194: }
                   2195: 
1.493     albertel 2196: sub removeuploadedurl {
                   2197:     my ($url)=@_;
                   2198:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2199:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2200: }
                   2201: 
                   2202: sub removeuserfile {
                   2203:     my ($docuname,$docudom,$fname)=@_;
                   2204:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2205:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2206:     if ($result eq 'ok') {
                   2207:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2208:             my $metafile = $fname.'.meta';
                   2209:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2210: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2212:             my $sqlresult = 
1.823     albertel 2213:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2214:                                         'portfolio_metadata',$group,
                   2215:                                         'delete');
1.798     raeburn  2216:         }
                   2217:     }
                   2218:     return $result;
1.257     www      2219: }
1.15      www      2220: 
1.530     albertel 2221: sub mkdiruserfile {
                   2222:     my ($docuname,$docudom,$dir)=@_;
                   2223:     my $home=&homeserver($docuname,$docudom);
                   2224:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2225: }
                   2226: 
1.531     albertel 2227: sub renameuserfile {
                   2228:     my ($docuname,$docudom,$old,$new)=@_;
                   2229:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2230:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2231:                         &escape("$old").':'.&escape("$new"),$home);
                   2232:     if ($result eq 'ok') {
                   2233:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2234:             my $oldmeta = $old.'.meta';
                   2235:             my $newmeta = $new.'.meta';
                   2236:             my $metaresult = 
                   2237:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2238: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2239:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2240:             my $sqlresult = 
1.823     albertel 2241:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2242:                                         'portfolio_metadata',$group,
                   2243:                                         'delete');
1.798     raeburn  2244:         }
                   2245:     }
                   2246:     return $result;
1.531     albertel 2247: }
                   2248: 
1.14      www      2249: # ------------------------------------------------------------------------- Log
                   2250: 
                   2251: sub log {
                   2252:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2253:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2254: }
                   2255: 
                   2256: # ------------------------------------------------------------------ Course Log
1.352     www      2257: #
                   2258: # This routine flushes several buffers of non-mission-critical nature
                   2259: #
1.157     www      2260: 
                   2261: sub flushcourselogs {
1.352     www      2262:     &logthis('Flushing log buffers');
                   2263: #
                   2264: # course logs
                   2265: # This is a log of all transactions in a course, which can be used
                   2266: # for data mining purposes
                   2267: #
                   2268: # It also collects the courseid database, which lists last transaction
                   2269: # times and course titles for all courseids
                   2270: #
                   2271:     my %courseidbuffer=();
1.921     raeburn  2272:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2273:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2274: 		          &escape($courselogs{$crsid}),
                   2275: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2276: 	    delete $courselogs{$crsid};
                   2277:         } else {
                   2278:             &logthis('Failed to flush log buffer for '.$crsid);
                   2279:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2280:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2281:                         " exceeded maximum size, deleting.</font>");
                   2282:                delete $courselogs{$crsid};
                   2283:             }
1.352     www      2284:         }
1.920     raeburn  2285:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2286:             'description' => $coursedescrbuf{$crsid},
                   2287:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2288:             'type'        => $coursetypebuf{$crsid},
                   2289:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2290:         };
1.191     harris41 2291:     }
1.352     www      2292: #
                   2293: # Write course id database (reverse lookup) to homeserver of courses 
                   2294: # Is used in pickcourse
                   2295: #
1.840     albertel 2296:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2297:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2298:                                     $courseidbuffer{$crs_home},
                   2299:                                     $crs_home,'timeonly');
1.352     www      2300:     }
                   2301: #
                   2302: # File accesses
                   2303: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2304: #
1.449     matthew  2305:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2306:         if ($entry =~ /___count$/) {
                   2307:             my ($dom,$name);
1.807     albertel 2308:             ($dom,$name,undef)=
1.811     albertel 2309: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2310:             if (! defined($dom) || $dom eq '' || 
                   2311:                 ! defined($name) || $name eq '') {
1.620     albertel 2312:                 my $cid = $env{'request.course.id'};
                   2313:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2314:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2315:             }
1.450     matthew  2316:             my $value = $accesshash{$entry};
                   2317:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2318:             my %temphash=($url => $value);
1.449     matthew  2319:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2320:             if ($result eq 'ok') {
                   2321:                 delete $accesshash{$entry};
                   2322:             } elsif ($result eq 'unknown_cmd') {
                   2323:                 # Target server has old code running on it.
1.450     matthew  2324:                 my %temphash=($entry => $value);
1.449     matthew  2325:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2326:                     delete $accesshash{$entry};
                   2327:                 }
                   2328:             }
                   2329:         } else {
1.811     albertel 2330:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2331:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2332:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2333:                 delete $accesshash{$entry};
                   2334:             }
1.185     www      2335:         }
1.191     harris41 2336:     }
1.352     www      2337: #
                   2338: # Roles
                   2339: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2340: #
1.800     albertel 2341:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2342:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2343: 	    split(/\:/,$entry);
                   2344:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2345:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2346:                 $rudom,$runame) eq 'ok') {
                   2347: 	    delete $userrolehash{$entry};
                   2348:         }
                   2349:     }
1.662     raeburn  2350: #
                   2351: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2352: #
                   2353:     my %domrolebuffer = ();
                   2354:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2355:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2356:         if ($domrolebuffer{$rudom}) {
                   2357:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2358:                       '='.&escape($domainrolehash{$entry});
                   2359:         } else {
                   2360:             $domrolebuffer{$rudom}.=&escape($entry).
                   2361:                       '='.&escape($domainrolehash{$entry});
                   2362:         }
                   2363:         delete $domainrolehash{$entry};
                   2364:     }
                   2365:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2366: 	my %servers = &get_servers($dom,'library');
                   2367: 	foreach my $tryserver (keys(%servers)) {
                   2368: 	    unless (&reply('domroleput:'.$dom.':'.
                   2369: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2370: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2371: 	    }
1.662     raeburn  2372:         }
                   2373:     }
1.186     www      2374:     $dumpcount++;
1.157     www      2375: }
                   2376: 
                   2377: sub courselog {
                   2378:     my $what=shift;
1.158     www      2379:     $what=time.':'.$what;
1.620     albertel 2380:     unless ($env{'request.course.id'}) { return ''; }
                   2381:     $coursedombuf{$env{'request.course.id'}}=
                   2382:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2383:     $coursenumbuf{$env{'request.course.id'}}=
                   2384:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2385:     $coursehombuf{$env{'request.course.id'}}=
                   2386:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2387:     $coursedescrbuf{$env{'request.course.id'}}=
                   2388:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2389:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2390:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2391:     $courseownerbuf{$env{'request.course.id'}}=
                   2392:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2393:     $coursetypebuf{$env{'request.course.id'}}=
                   2394:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2395:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2396: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2397:     } else {
1.620     albertel 2398: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2399:     }
1.620     albertel 2400:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2401: 	&flushcourselogs();
                   2402:     }
1.158     www      2403: }
                   2404: 
                   2405: sub courseacclog {
                   2406:     my $fnsymb=shift;
1.620     albertel 2407:     unless ($env{'request.course.id'}) { return ''; }
                   2408:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2409:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2410:         $what.=':POST';
1.583     matthew  2411:         # FIXME: Probably ought to escape things....
1.800     albertel 2412: 	foreach my $key (keys(%env)) {
                   2413:             if ($key=~/^form\.(.*)/) {
                   2414: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2415:             }
1.191     harris41 2416:         }
1.583     matthew  2417:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2418:         # FIXME: We should not be depending on a form parameter that someone
                   2419:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2420:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2421:             $what.= ':POST';
                   2422:             # FIXME: Probably ought to escape things....
                   2423:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2424:                                  'crsdiscuss') {
1.620     albertel 2425:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2426:             }
                   2427:         }
1.158     www      2428:     }
                   2429:     &courselog($what);
1.149     www      2430: }
                   2431: 
1.185     www      2432: sub countacc {
                   2433:     my $url=&declutter(shift);
1.458     matthew  2434:     return if (! defined($url) || $url eq '');
1.620     albertel 2435:     unless ($env{'request.course.id'}) { return ''; }
                   2436:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2437:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2438:     $accesshash{$key}++;
1.185     www      2439: }
1.349     www      2440: 
1.361     www      2441: sub linklog {
                   2442:     my ($from,$to)=@_;
                   2443:     $from=&declutter($from);
                   2444:     $to=&declutter($to);
                   2445:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2446:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2447: }
                   2448:   
1.349     www      2449: sub userrolelog {
                   2450:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2451:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2452:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2453:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2454:         ($trole=~/^ta/)) {
1.350     www      2455:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2456:        $userrolehash
                   2457:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2458:                     =$tend.':'.$tstart;
1.662     raeburn  2459:     }
1.898     albertel 2460:     if (($env{'request.role'} =~ /dc\./) &&
                   2461: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2462: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2463: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2464:        $userrolehash
                   2465:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2466:                     =$tend.':'.$tstart;
                   2467:     }
1.662     raeburn  2468:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2469:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2470:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2471:         ($trole=~/^sc/)) {
                   2472:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2473:        $domainrolehash
                   2474:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2475:                     = $tend.':'.$tstart;
                   2476:     }
1.351     www      2477: }
                   2478: 
                   2479: sub get_course_adv_roles {
1.948     raeburn  2480:     my ($cid,$codes) = @_;
1.620     albertel 2481:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2482:     my %coursehash=&coursedescription($cid);
1.470     www      2483:     my %nothide=();
1.800     albertel 2484:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2485:         if ($user !~ /:/) {
                   2486: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2487:         } else {
                   2488:             $nothide{$user}=1;
                   2489:         }
1.470     www      2490:     }
1.351     www      2491:     my %returnhash=();
                   2492:     my %dumphash=
                   2493:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2494:     my $now=time;
1.800     albertel 2495:     foreach my $entry (keys %dumphash) {
                   2496: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2497:         if (($tstart) && ($tstart<0)) { next; }
                   2498:         if (($tend) && ($tend<$now)) { next; }
                   2499:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2500:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2501: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2502: 	if ((&privileged($username,$domain)) && 
                   2503: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2504: 	if ($role eq 'cr') { next; }
1.948     raeburn  2505:         if ($codes) {
                   2506:             if ($section) { $role .= ':'.$section; }
                   2507:             if ($returnhash{$role}) {
                   2508:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2509:             } else {
                   2510:                 $returnhash{$role}=$username.':'.$domain;
                   2511:             }
1.351     www      2512:         } else {
1.948     raeburn  2513:             my $key=&plaintext($role);
                   2514:             if ($section) { $key.=' (Section '.$section.')'; }
                   2515:             if ($returnhash{$key}) {
                   2516: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2517:             } else {
                   2518:                 $returnhash{$key}=$username.':'.$domain;
                   2519:             }
1.351     www      2520:         }
1.948     raeburn  2521:     }
1.400     www      2522:     return %returnhash;
                   2523: }
                   2524: 
                   2525: sub get_my_roles {
1.937     raeburn  2526:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2527:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2528:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2529:     my (%dumphash,%nothide);
1.858     raeburn  2530:     if ($context eq 'userroles') { 
                   2531:         %dumphash = &dump('roles',$udom,$uname);
                   2532:     } else {
                   2533:         %dumphash=
1.400     www      2534:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2535:         if ($hidepriv) {
                   2536:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2537:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2538:                 if ($user !~ /:/) {
                   2539:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2540:                 } else {
                   2541:                     $nothide{$user} = 1;
                   2542:                 }
                   2543:             }
                   2544:         }
1.858     raeburn  2545:     }
1.400     www      2546:     my %returnhash=();
                   2547:     my $now=time;
1.800     albertel 2548:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2549:         my ($role,$tend,$tstart);
                   2550:         if ($context eq 'userroles') {
                   2551: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2552:         } else {
                   2553:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2554:         }
1.400     www      2555:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2556:         my $status = 'active';
1.939     raeburn  2557:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2558:             $status = 'previous';
                   2559:         } 
                   2560:         if (($tstart) && ($now<$tstart)) {
                   2561:             $status = 'future';
                   2562:         }
                   2563:         if (ref($types) eq 'ARRAY') {
                   2564:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2565:                 next;
                   2566:             } 
                   2567:         } else {
                   2568:             if ($status ne 'active') {
                   2569:                 next;
                   2570:             }
                   2571:         }
1.867     raeburn  2572:         my ($rolecode,$username,$domain,$section,$area);
                   2573:         if ($context eq 'userroles') {
                   2574:             ($area,$rolecode) = split(/_/,$entry);
                   2575:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2576:         } else {
                   2577:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2578:         }
1.832     raeburn  2579:         if (ref($roledoms) eq 'ARRAY') {
                   2580:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2581:                 next;
                   2582:             }
                   2583:         }
                   2584:         if (ref($roles) eq 'ARRAY') {
                   2585:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2586:                 if ($role =~ /^cr\//) {
                   2587:                     if (!grep(/^cr$/,@{$roles})) {
                   2588:                         next;
                   2589:                     }
                   2590:                 } else {
                   2591:                     next;
                   2592:                 }
1.832     raeburn  2593:             }
1.867     raeburn  2594:         }
1.937     raeburn  2595:         if ($hidepriv) {
                   2596:             if ((&privileged($username,$domain)) &&
                   2597:                 (!$nothide{$username.':'.$domain})) { 
                   2598:                 next;
                   2599:             }
                   2600:         }
1.933     raeburn  2601:         if ($withsec) {
                   2602:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2603:                 $tstart.':'.$tend;
                   2604:         } else {
                   2605:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2606:         }
1.832     raeburn  2607:     }
1.373     www      2608:     return %returnhash;
1.399     www      2609: }
                   2610: 
                   2611: # ----------------------------------------------------- Frontpage Announcements
                   2612: #
                   2613: #
                   2614: 
                   2615: sub postannounce {
                   2616:     my ($server,$text)=@_;
1.844     albertel 2617:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2618:     unless ($text=~/\w/) { $text=''; }
                   2619:     return &reply('setannounce:'.&escape($text),$server);
                   2620: }
                   2621: 
                   2622: sub getannounce {
1.448     albertel 2623: 
                   2624:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2625: 	my $announcement='';
1.800     albertel 2626: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2627: 	close($fh);
1.399     www      2628: 	if ($announcement=~/\w/) { 
                   2629: 	    return 
                   2630:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2631:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2632: 	} else {
                   2633: 	    return '';
                   2634: 	}
                   2635:     } else {
                   2636: 	return '';
                   2637:     }
1.351     www      2638: }
1.353     www      2639: 
                   2640: # ---------------------------------------------------------- Course ID routines
                   2641: # Deal with domain's nohist_courseid.db files
                   2642: #
                   2643: 
                   2644: sub courseidput {
1.921     raeburn  2645:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2646:     my $outcome;
                   2647:     if ($caller eq 'timeonly') {
                   2648:         my $cids = '';
                   2649:         foreach my $item (keys(%$storehash)) {
                   2650:             $cids.=&escape($item).'&';
                   2651:         }
                   2652:         $cids=~s/\&$//;
                   2653:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2654:                           $coursehome);       
                   2655:     } else {
                   2656:         my $items = '';
                   2657:         foreach my $item (keys(%$storehash)) {
                   2658:             $items.= &escape($item).'='.
                   2659:                      &freeze_escape($$storehash{$item}).'&';
                   2660:         }
                   2661:         $items=~s/\&$//;
                   2662:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2663:                           $coursehome);
1.918     raeburn  2664:     }
                   2665:     if ($outcome eq 'unknown_cmd') {
                   2666:         my $what;
                   2667:         foreach my $cid (keys(%$storehash)) {
                   2668:             $what .= &escape($cid).'=';
1.921     raeburn  2669:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2670:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2671:             }
                   2672:             $what =~ s/\:$/&/;
                   2673:         }
                   2674:         $what =~ s/\&$//;  
                   2675:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2676:     } else {
                   2677:         return $outcome;
                   2678:     }
1.353     www      2679: }
                   2680: 
                   2681: sub courseiddump {
1.921     raeburn  2682:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2683:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
                   2684:         $selfenrollonly)=@_;
1.918     raeburn  2685:     my $as_hash = 1;
                   2686:     my %returnhash;
                   2687:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2688:     my %libserv = &all_library();
                   2689:     foreach my $tryserver (keys(%libserv)) {
                   2690:         if ( (  $hostidflag == 1 
                   2691: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2692: 	     || (!defined($hostidflag)) ) {
                   2693: 
1.918     raeburn  2694: 	    if (($domfilter eq '') ||
                   2695: 		(&host_domain($tryserver) eq $domfilter)) {
                   2696:                 my $rep = 
                   2697:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2698:                          $sincefilter.':'.&escape($descfilter).':'.
                   2699:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2700:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2701:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   2702:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2703:                 my @pairs=split(/\&/,$rep);
                   2704:                 foreach my $item (@pairs) {
                   2705:                     my ($key,$value)=split(/\=/,$item,2);
                   2706:                     $key = &unescape($key);
                   2707:                     next if ($key =~ /^error: 2 /);
                   2708:                     my $result = &thaw_unescape($value);
                   2709:                     if (ref($result) eq 'HASH') {
                   2710:                         $returnhash{$key}=$result;
                   2711:                     } else {
1.921     raeburn  2712:                         my @responses = split(/:/,$value);
                   2713:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2714:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2715:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2716:                         }
                   2717:                     } 
1.353     www      2718:                 }
                   2719:             }
                   2720:         }
                   2721:     }
                   2722:     return %returnhash;
                   2723: }
                   2724: 
1.658     raeburn  2725: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2726: 
                   2727: sub dcmailput {
1.685     raeburn  2728:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2729:     my $status = &Apache::lonnet::critical(
1.740     www      2730:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2731:        &escape($message),$server);
1.662     raeburn  2732:     return $status;
                   2733: }
                   2734: 
1.658     raeburn  2735: sub dcmaildump {
                   2736:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2737:     my %returnhash=();
1.846     albertel 2738: 
                   2739:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2740:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2741:                                                          &escape($enddate).':';
                   2742: 	my @esc_senders=map { &escape($_)} @$senders;
                   2743: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2744: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2745:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2746:             if (($key) && ($value)) {
                   2747:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2748:             }
                   2749:         }
                   2750:     }
                   2751:     return %returnhash;
                   2752: }
1.662     raeburn  2753: # ---------------------------------------------------------- Domain roles
                   2754: 
                   2755: sub get_domain_roles {
                   2756:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2757:     if (undef($startdate) || $startdate eq '') {
                   2758:         $startdate = '.';
                   2759:     }
                   2760:     if (undef($enddate) || $enddate eq '') {
                   2761:         $enddate = '.';
                   2762:     }
1.922     raeburn  2763:     my $rolelist;
                   2764:     if (ref($roles) eq 'ARRAY') {
                   2765:         $rolelist = join(':',@{$roles});
                   2766:     }
1.662     raeburn  2767:     my %personnel = ();
1.841     albertel 2768: 
                   2769:     my %servers = &get_servers($dom,'library');
                   2770:     foreach my $tryserver (keys(%servers)) {
                   2771: 	%{$personnel{$tryserver}}=();
                   2772: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2773: 					    &escape($startdate).':'.
                   2774: 					    &escape($enddate).':'.
                   2775: 					    &escape($rolelist), $tryserver))) {
                   2776: 	    my ($key,$value) = split(/\=/,$line,2);
                   2777: 	    if (($key) && ($value)) {
                   2778: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2779: 	    }
                   2780: 	}
1.662     raeburn  2781:     }
                   2782:     return %personnel;
                   2783: }
1.658     raeburn  2784: 
1.149     www      2785: # ----------------------------------------------------------- Check out an item
                   2786: 
1.504     albertel 2787: sub get_first_access {
                   2788:     my ($type,$argsymb)=@_;
1.790     albertel 2789:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2790:     if ($argsymb) { $symb=$argsymb; }
                   2791:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2792:     if ($type eq 'course') {
                   2793: 	$res='course';
                   2794:     } elsif ($type eq 'map') {
1.588     albertel 2795: 	$res=&symbread($map);
                   2796:     } else {
                   2797: 	$res=$symb;
                   2798:     }
                   2799:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2800:     return $times{"$courseid\0$res"};
1.504     albertel 2801: }
                   2802: 
                   2803: sub set_first_access {
                   2804:     my ($type)=@_;
1.790     albertel 2805:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2806:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2807:     if ($type eq 'course') {
                   2808: 	$res='course';
                   2809:     } elsif ($type eq 'map') {
1.588     albertel 2810: 	$res=&symbread($map);
                   2811:     } else {
                   2812: 	$res=$symb;
                   2813:     }
                   2814:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2815:     if (!$firstaccess) {
1.588     albertel 2816: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2817:     }
                   2818:     return 'already_set';
1.504     albertel 2819: }
                   2820: 
1.149     www      2821: sub checkout {
                   2822:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2823:     my $now=time;
                   2824:     my $lonhost=$perlvar{'lonHostID'};
                   2825:     my $infostr=&escape(
1.234     www      2826:                  'CHECKOUTTOKEN&'.
1.149     www      2827:                  $tuname.'&'.
                   2828:                  $tudom.'&'.
                   2829:                  $tcrsid.'&'.
                   2830:                  $symb.'&'.
                   2831: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2832:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2833:     if ($token=~/^error\:/) { 
1.672     albertel 2834:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2835:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2836:                  "</font>");
                   2837:         return ''; 
                   2838:     }
                   2839: 
1.149     www      2840:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2841:     $token=~tr/a-z/A-Z/;
                   2842: 
1.153     www      2843:     my %infohash=('resource.0.outtoken' => $token,
                   2844:                   'resource.0.checkouttime' => $now,
                   2845:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2846: 
                   2847:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2848:        return '';
1.151     www      2849:     } else {
1.672     albertel 2850:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2851:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2852:                  "</font>");
1.149     www      2853:     }    
                   2854: 
                   2855:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2856:                          &escape('Checkout '.$infostr.' - '.
                   2857:                                                  $token)) ne 'ok') {
                   2858: 	return '';
1.151     www      2859:     } else {
1.672     albertel 2860:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2861:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2862:                  "</font>");
1.149     www      2863:     }
1.151     www      2864:     return $token;
1.149     www      2865: }
                   2866: 
                   2867: # ------------------------------------------------------------ Check in an item
                   2868: 
                   2869: sub checkin {
                   2870:     my $token=shift;
1.150     www      2871:     my $now=time;
                   2872:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2873:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2874:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2875:     $dtoken=~s/\W/\_/g;
1.234     www      2876:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2877:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2878: 
1.154     www      2879:     unless (($tuname) && ($tudom)) {
                   2880:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2881:         return '';
                   2882:     }
                   2883:     
                   2884:     unless (&allowed('mgr',$tcrsid)) {
                   2885:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2886:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2887:         return '';
                   2888:     }
                   2889: 
1.153     www      2890:     my %infohash=('resource.0.intoken' => $token,
                   2891:                   'resource.0.checkintime' => $now,
                   2892:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2893: 
                   2894:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2895:        return '';
                   2896:     }    
                   2897: 
                   2898:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2899:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2900: 	return '';
                   2901:     }
                   2902: 
                   2903:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2904: }
                   2905: 
                   2906: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2907: 
                   2908: sub expirespread {
                   2909:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2910:     my $cid=$env{'request.course.id'}; 
1.110     www      2911:     if ($cid) {
                   2912:        my $now=time;
                   2913:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2914:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2915:                             $env{'course.'.$cid.'.num'}.
1.110     www      2916: 	        	    ':nohist_expirationdates:'.
                   2917:                             &escape($key).'='.$now,
1.620     albertel 2918:                             $env{'course.'.$cid.'.home'})
1.110     www      2919:     }
                   2920:     return 'ok';
1.14      www      2921: }
                   2922: 
1.109     www      2923: # ----------------------------------------------------- Devalidate Spreadsheets
                   2924: 
                   2925: sub devalidate {
1.325     www      2926:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2927:     my $cid=$env{'request.course.id'}; 
1.109     www      2928:     if ($cid) {
1.391     matthew  2929:         # delete the stored spreadsheets for
                   2930:         # - the student level sheet of this user in course's homespace
                   2931:         # - the assessment level sheet for this resource 
                   2932:         #   for this user in user's homespace
1.553     albertel 2933: 	# - current conditional state info
1.325     www      2934: 	my $key=$uname.':'.$udom.':';
1.109     www      2935:         my $status=
1.299     matthew  2936: 	    &del('nohist_calculatedsheets',
1.391     matthew  2937: 		 [$key.'studentcalc:'],
1.620     albertel 2938: 		 $env{'course.'.$cid.'.domain'},
                   2939: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2940: 		.' '.
                   2941: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2942: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2943:         unless ($status eq 'ok ok') {
                   2944:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2945:                     $uname.' at '.$udom.' for '.
1.109     www      2946: 		    $symb.': '.$status);
1.133     albertel 2947:         }
1.553     albertel 2948: 	&delenv('user.state.'.$cid);
1.109     www      2949:     }
                   2950: }
                   2951: 
1.265     albertel 2952: sub get_scalar {
                   2953:     my ($string,$end) = @_;
                   2954:     my $value;
                   2955:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2956: 	$value = $1;
                   2957:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2958: 	$value = $1;
                   2959:     }
                   2960:     return &unescape($value);
                   2961: }
                   2962: 
                   2963: sub array2str {
                   2964:   my (@array) = @_;
                   2965:   my $result=&arrayref2str(\@array);
                   2966:   $result=~s/^__ARRAY_REF__//;
                   2967:   $result=~s/__END_ARRAY_REF__$//;
                   2968:   return $result;
                   2969: }
                   2970: 
1.204     albertel 2971: sub arrayref2str {
                   2972:   my ($arrayref) = @_;
1.265     albertel 2973:   my $result='__ARRAY_REF__';
1.204     albertel 2974:   foreach my $elem (@$arrayref) {
1.265     albertel 2975:     if(ref($elem) eq 'ARRAY') {
                   2976:       $result.=&arrayref2str($elem).'&';
                   2977:     } elsif(ref($elem) eq 'HASH') {
                   2978:       $result.=&hashref2str($elem).'&';
                   2979:     } elsif(ref($elem)) {
                   2980:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2981:     } else {
                   2982:       $result.=&escape($elem).'&';
                   2983:     }
                   2984:   }
                   2985:   $result=~s/\&$//;
1.265     albertel 2986:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2987:   return $result;
                   2988: }
                   2989: 
1.168     albertel 2990: sub hash2str {
1.204     albertel 2991:   my (%hash) = @_;
                   2992:   my $result=&hashref2str(\%hash);
1.265     albertel 2993:   $result=~s/^__HASH_REF__//;
                   2994:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2995:   return $result;
                   2996: }
                   2997: 
                   2998: sub hashref2str {
                   2999:   my ($hashref)=@_;
1.265     albertel 3000:   my $result='__HASH_REF__';
1.800     albertel 3001:   foreach my $key (sort(keys(%$hashref))) {
                   3002:     if (ref($key) eq 'ARRAY') {
                   3003:       $result.=&arrayref2str($key).'=';
                   3004:     } elsif (ref($key) eq 'HASH') {
                   3005:       $result.=&hashref2str($key).'=';
                   3006:     } elsif (ref($key)) {
1.265     albertel 3007:       $result.='=';
1.800     albertel 3008:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3009:     } else {
1.800     albertel 3010: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3011:     }
                   3012: 
1.800     albertel 3013:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3014:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3015:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3016:       $result.=&hashref2str($hashref->{$key}).'&';
                   3017:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3018:        $result.='&';
1.800     albertel 3019:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3020:     } else {
1.800     albertel 3021:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3022:     }
                   3023:   }
1.168     albertel 3024:   $result=~s/\&$//;
1.265     albertel 3025:   $result .= '__END_HASH_REF__';
1.168     albertel 3026:   return $result;
                   3027: }
                   3028: 
                   3029: sub str2hash {
1.265     albertel 3030:     my ($string)=@_;
                   3031:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3032:     return %$hash;
                   3033: }
                   3034: 
                   3035: sub str2hashref {
1.168     albertel 3036:   my ($string) = @_;
1.265     albertel 3037: 
                   3038:   my %hash;
                   3039: 
                   3040:   if($string !~ /^__HASH_REF__/) {
                   3041:       if (! ($string eq '' || !defined($string))) {
                   3042: 	  $hash{'error'}='Not hash reference';
                   3043:       }
                   3044:       return (\%hash, $string);
                   3045:   }
                   3046: 
                   3047:   $string =~ s/^__HASH_REF__//;
                   3048: 
                   3049:   while($string !~ /^__END_HASH_REF__/) {
                   3050:       #key
                   3051:       my $key='';
                   3052:       if($string =~ /^__HASH_REF__/) {
                   3053:           ($key, $string)=&str2hashref($string);
                   3054:           if(defined($key->{'error'})) {
                   3055:               $hash{'error'}='Bad data';
                   3056:               return (\%hash, $string);
                   3057:           }
                   3058:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3059:           ($key, $string)=&str2arrayref($string);
                   3060:           if($key->[0] eq 'Array reference error') {
                   3061:               $hash{'error'}='Bad data';
                   3062:               return (\%hash, $string);
                   3063:           }
                   3064:       } else {
                   3065:           $string =~ s/^(.*?)=//;
1.267     albertel 3066: 	  $key=&unescape($1);
1.265     albertel 3067:       }
                   3068:       $string =~ s/^=//;
                   3069: 
                   3070:       #value
                   3071:       my $value='';
                   3072:       if($string =~ /^__HASH_REF__/) {
                   3073:           ($value, $string)=&str2hashref($string);
                   3074:           if(defined($value->{'error'})) {
                   3075:               $hash{'error'}='Bad data';
                   3076:               return (\%hash, $string);
                   3077:           }
                   3078:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3079:           ($value, $string)=&str2arrayref($string);
                   3080:           if($value->[0] eq 'Array reference error') {
                   3081:               $hash{'error'}='Bad data';
                   3082:               return (\%hash, $string);
                   3083:           }
                   3084:       } else {
                   3085: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3086:       }
                   3087:       $string =~ s/^&//;
                   3088: 
                   3089:       $hash{$key}=$value;
1.204     albertel 3090:   }
1.265     albertel 3091: 
                   3092:   $string =~ s/^__END_HASH_REF__//;
                   3093: 
                   3094:   return (\%hash, $string);
1.204     albertel 3095: }
                   3096: 
                   3097: sub str2array {
1.265     albertel 3098:     my ($string)=@_;
                   3099:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3100:     return @$array;
                   3101: }
                   3102: 
                   3103: sub str2arrayref {
1.204     albertel 3104:   my ($string) = @_;
1.265     albertel 3105:   my @array;
                   3106: 
                   3107:   if($string !~ /^__ARRAY_REF__/) {
                   3108:       if (! ($string eq '' || !defined($string))) {
                   3109: 	  $array[0]='Array reference error';
                   3110:       }
                   3111:       return (\@array, $string);
                   3112:   }
                   3113: 
                   3114:   $string =~ s/^__ARRAY_REF__//;
                   3115: 
                   3116:   while($string !~ /^__END_ARRAY_REF__/) {
                   3117:       my $value='';
                   3118:       if($string =~ /^__HASH_REF__/) {
                   3119:           ($value, $string)=&str2hashref($string);
                   3120:           if(defined($value->{'error'})) {
                   3121:               $array[0] ='Array reference error';
                   3122:               return (\@array, $string);
                   3123:           }
                   3124:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3125:           ($value, $string)=&str2arrayref($string);
                   3126:           if($value->[0] eq 'Array reference error') {
                   3127:               $array[0] ='Array reference error';
                   3128:               return (\@array, $string);
                   3129:           }
                   3130:       } else {
                   3131: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3132:       }
                   3133:       $string =~ s/^&//;
                   3134: 
                   3135:       push(@array, $value);
1.191     harris41 3136:   }
1.265     albertel 3137: 
                   3138:   $string =~ s/^__END_ARRAY_REF__//;
                   3139: 
                   3140:   return (\@array, $string);
1.168     albertel 3141: }
                   3142: 
1.167     albertel 3143: # -------------------------------------------------------------------Temp Store
                   3144: 
1.168     albertel 3145: sub tmpreset {
                   3146:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3147:   if (!$symb) {
                   3148:     $symb=&symbread();
1.620     albertel 3149:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3150:   }
                   3151:   $symb=escape($symb);
                   3152: 
1.620     albertel 3153:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3154:   $namespace=~s/\//\_/g;
                   3155:   $namespace=~s/\W//g;
                   3156: 
1.620     albertel 3157:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3158:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3159:   if ($domain eq 'public' && $stuname eq 'public') {
                   3160:       $stuname=$ENV{'REMOTE_ADDR'};
                   3161:   }
1.168     albertel 3162:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3163:   my %hash;
                   3164:   if (tie(%hash,'GDBM_File',
                   3165: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3166: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3167:     foreach my $key (keys %hash) {
1.180     albertel 3168:       if ($key=~ /:$symb/) {
1.168     albertel 3169: 	delete($hash{$key});
                   3170:       }
                   3171:     }
                   3172:   }
                   3173: }
                   3174: 
1.167     albertel 3175: sub tmpstore {
1.168     albertel 3176:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3177: 
                   3178:   if (!$symb) {
                   3179:     $symb=&symbread();
1.620     albertel 3180:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3181:   }
                   3182:   $symb=escape($symb);
                   3183: 
                   3184:   if (!$namespace) {
                   3185:     # I don't think we would ever want to store this for a course.
                   3186:     # it seems this will only be used if we don't have a course.
1.620     albertel 3187:     #$namespace=$env{'request.course.id'};
1.168     albertel 3188:     #if (!$namespace) {
1.620     albertel 3189:       $namespace=$env{'request.state'};
1.168     albertel 3190:     #}
                   3191:   }
                   3192:   $namespace=~s/\//\_/g;
                   3193:   $namespace=~s/\W//g;
1.620     albertel 3194:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3195:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3196:   if ($domain eq 'public' && $stuname eq 'public') {
                   3197:       $stuname=$ENV{'REMOTE_ADDR'};
                   3198:   }
1.168     albertel 3199:   my $now=time;
                   3200:   my %hash;
                   3201:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3202:   if (tie(%hash,'GDBM_File',
                   3203: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3204: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3205:     $hash{"version:$symb"}++;
                   3206:     my $version=$hash{"version:$symb"};
                   3207:     my $allkeys=''; 
                   3208:     foreach my $key (keys(%$storehash)) {
                   3209:       $allkeys.=$key.':';
1.591     albertel 3210:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3211:     }
                   3212:     $hash{"$version:$symb:timestamp"}=$now;
                   3213:     $allkeys.='timestamp';
                   3214:     $hash{"$version:keys:$symb"}=$allkeys;
                   3215:     if (untie(%hash)) {
                   3216:       return 'ok';
                   3217:     } else {
                   3218:       return "error:$!";
                   3219:     }
                   3220:   } else {
                   3221:     return "error:$!";
                   3222:   }
                   3223: }
1.167     albertel 3224: 
1.168     albertel 3225: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3226: 
1.168     albertel 3227: sub tmprestore {
                   3228:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3229: 
1.168     albertel 3230:   if (!$symb) {
                   3231:     $symb=&symbread();
1.620     albertel 3232:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3233:   }
                   3234:   $symb=escape($symb);
                   3235: 
1.620     albertel 3236:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3237: 
1.620     albertel 3238:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3239:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3240:   if ($domain eq 'public' && $stuname eq 'public') {
                   3241:       $stuname=$ENV{'REMOTE_ADDR'};
                   3242:   }
1.168     albertel 3243:   my %returnhash;
                   3244:   $namespace=~s/\//\_/g;
                   3245:   $namespace=~s/\W//g;
                   3246:   my %hash;
                   3247:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3248:   if (tie(%hash,'GDBM_File',
                   3249: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3250: 	  &GDBM_READER(),0640)) {
1.168     albertel 3251:     my $version=$hash{"version:$symb"};
                   3252:     $returnhash{'version'}=$version;
                   3253:     my $scope;
                   3254:     for ($scope=1;$scope<=$version;$scope++) {
                   3255:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3256:       my @keys=split(/:/,$vkeys);
                   3257:       my $key;
                   3258:       $returnhash{"$scope:keys"}=$vkeys;
                   3259:       foreach $key (@keys) {
1.591     albertel 3260: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3261: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3262:       }
                   3263:     }
1.168     albertel 3264:     if (!(untie(%hash))) {
                   3265:       return "error:$!";
                   3266:     }
                   3267:   } else {
                   3268:     return "error:$!";
                   3269:   }
                   3270:   return %returnhash;
1.167     albertel 3271: }
                   3272: 
1.9       www      3273: # ----------------------------------------------------------------------- Store
                   3274: 
                   3275: sub store {
1.124     www      3276:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3277:     my $home='';
                   3278: 
1.168     albertel 3279:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3280: 
1.213     www      3281:     $symb=&symbclean($symb);
1.122     albertel 3282:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3283: 
1.620     albertel 3284:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3285:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3286: 
                   3287:     &devalidate($symb,$stuname,$domain);
1.109     www      3288: 
                   3289:     $symb=escape($symb);
1.187     www      3290:     if (!$namespace) { 
1.620     albertel 3291:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3292:           return ''; 
                   3293:        } 
                   3294:     }
1.620     albertel 3295:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3296: 
                   3297:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3298:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3299: 
1.12      www      3300:     my $namevalue='';
1.800     albertel 3301:     foreach my $key (keys(%$storehash)) {
                   3302:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3303:     }
1.12      www      3304:     $namevalue=~s/\&$//;
1.187     www      3305:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3306:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3307: }
                   3308: 
1.47      www      3309: # -------------------------------------------------------------- Critical Store
                   3310: 
                   3311: sub cstore {
1.124     www      3312:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3313:     my $home='';
                   3314: 
1.168     albertel 3315:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3316: 
1.213     www      3317:     $symb=&symbclean($symb);
1.122     albertel 3318:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3319: 
1.620     albertel 3320:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3321:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3322: 
                   3323:     &devalidate($symb,$stuname,$domain);
1.109     www      3324: 
                   3325:     $symb=escape($symb);
1.187     www      3326:     if (!$namespace) { 
1.620     albertel 3327:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3328:           return ''; 
                   3329:        } 
                   3330:     }
1.620     albertel 3331:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3332: 
                   3333:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3334:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3335: 
1.47      www      3336:     my $namevalue='';
1.800     albertel 3337:     foreach my $key (keys(%$storehash)) {
                   3338:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3339:     }
1.47      www      3340:     $namevalue=~s/\&$//;
1.187     www      3341:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3342:     return critical
                   3343:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3344: }
                   3345: 
1.9       www      3346: # --------------------------------------------------------------------- Restore
                   3347: 
                   3348: sub restore {
1.124     www      3349:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3350:     my $home='';
                   3351: 
1.168     albertel 3352:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3353: 
1.122     albertel 3354:     if (!$symb) {
                   3355:       unless ($symb=escape(&symbread())) { return ''; }
                   3356:     } else {
1.213     www      3357:       $symb=&escape(&symbclean($symb));
1.122     albertel 3358:     }
1.188     www      3359:     if (!$namespace) { 
1.620     albertel 3360:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3361:           return ''; 
                   3362:        } 
                   3363:     }
1.620     albertel 3364:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3365:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3366:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3367:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3368: 
1.12      www      3369:     my %returnhash=();
1.800     albertel 3370:     foreach my $line (split(/\&/,$answer)) {
                   3371: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3372:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3373:     }
1.75      www      3374:     my $version;
                   3375:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3376:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3377:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3378:        }
1.75      www      3379:     }
1.13      www      3380:     return %returnhash;
1.34      www      3381: }
                   3382: 
                   3383: # ---------------------------------------------------------- Course Description
                   3384: 
                   3385: sub coursedescription {
1.731     albertel 3386:     my ($courseid,$args)=@_;
1.34      www      3387:     $courseid=~s/^\///;
1.49      www      3388:     $courseid=~s/\_/\//g;
1.34      www      3389:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3390:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3391:     my $normalid=$cdomain.'_'.$cnum;
                   3392:     # need to always cache even if we get errors otherwise we keep 
                   3393:     # trying and trying and trying to get the course description.
                   3394:     my %envhash=();
                   3395:     my %returnhash=();
1.731     albertel 3396:     
                   3397:     my $expiretime=600;
                   3398:     if ($env{'request.course.id'} eq $normalid) {
                   3399: 	$expiretime=120;
                   3400:     }
                   3401: 
                   3402:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3403:     if (!$args->{'freshen_cache'}
                   3404: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3405: 	foreach my $key (keys(%env)) {
                   3406: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3407: 	    my ($setting) = $1;
                   3408: 	    $returnhash{$setting} = $env{$key};
                   3409: 	}
                   3410: 	return %returnhash;
                   3411:     }
                   3412: 
                   3413:     # get the data agin
                   3414:     if (!$args->{'one_time'}) {
                   3415: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3416:     }
1.811     albertel 3417: 
1.34      www      3418:     if ($chome ne 'no_host') {
1.302     albertel 3419:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3420:        if (!exists($returnhash{'con_lost'})) {
                   3421:            $returnhash{'home'}= $chome;
                   3422: 	   $returnhash{'domain'} = $cdomain;
                   3423: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3424:            if (!defined($returnhash{'type'})) {
                   3425:                $returnhash{'type'} = 'Course';
                   3426:            }
1.130     albertel 3427:            while (my ($name,$value) = each %returnhash) {
1.53      www      3428:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3429:            }
1.270     www      3430:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3431:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3432: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3433:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3434:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3435:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3436:        }
                   3437:     }
1.731     albertel 3438:     if (!$args->{'one_time'}) {
1.949     raeburn  3439: 	&appenv(\%envhash);
1.731     albertel 3440:     }
1.302     albertel 3441:     return %returnhash;
1.461     www      3442: }
                   3443: 
                   3444: # -------------------------------------------------See if a user is privileged
                   3445: 
                   3446: sub privileged {
                   3447:     my ($username,$domain)=@_;
                   3448:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3449: 			&homeserver($username,$domain));
                   3450:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3451:     my $now=time;
                   3452:     if ($rolesdump ne '') {
1.800     albertel 3453:         foreach my $entry (split(/&/,$rolesdump)) {
                   3454: 	    if ($entry!~/^rolesdef_/) {
                   3455: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3456: 		$area=~s/\_\w\w$//;
                   3457: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3458: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3459: 		    my $active=1;
                   3460: 		    if ($tend) {
                   3461: 			if ($tend<$now) { $active=0; }
                   3462: 		    }
                   3463: 		    if ($tstart) {
                   3464: 			if ($tstart>$now) { $active=0; }
                   3465: 		    }
                   3466: 		    if ($active) { return 1; }
                   3467: 		}
                   3468: 	    }
                   3469: 	}
                   3470:     }
                   3471:     return 0;
1.9       www      3472: }
1.1       albertel 3473: 
1.103     harris41 3474: # -------------------------------------------------------- Get user privileges
1.11      www      3475: 
                   3476: sub rolesinit {
                   3477:     my ($domain,$username,$authhost)=@_;
                   3478:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3479:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3480:     my %allroles=();
1.678     raeburn  3481:     my %allgroups=();   
1.11      www      3482:     my $now=time;
1.743     albertel 3483:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3484:     my $group_privs;
1.11      www      3485: 
                   3486:     if ($rolesdump ne '') {
1.800     albertel 3487:         foreach my $entry (split(/&/,$rolesdump)) {
                   3488: 	  if ($entry!~/^rolesdef_/) {
                   3489:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3490: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3491:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3492: 	    if ($role=~/^cr/) { 
1.807     albertel 3493: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3494: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3495: 		    ($tend,$tstart)=split('_',$trest);
                   3496: 		} else {
                   3497: 		    $trole=$role;
                   3498: 		}
1.678     raeburn  3499:             } elsif ($role =~ m|^gr/|) {
                   3500:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3501:                 ($trole,$group_privs) = split(/\//,$trole);
                   3502:                 $group_privs = &unescape($group_privs);
1.587     albertel 3503: 	    } else {
                   3504: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3505: 	    }
1.743     albertel 3506: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3507: 					 $username);
                   3508: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3509:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3510:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3511:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3512: 		my $spec=$trole.'.'.$area;
                   3513: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3514: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3515:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3516:                 } elsif ($trole eq 'gr') {
                   3517:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3518: 		} else {
1.567     raeburn  3519:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3520: 		}
1.12      www      3521:             }
1.662     raeburn  3522:           }
1.191     harris41 3523:         }
1.743     albertel 3524:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3525:         $userroles{'user.adv'}    = $adv;
                   3526: 	$userroles{'user.author'} = $author;
1.620     albertel 3527:         $env{'user.adv'}=$adv;
1.11      www      3528:     }
1.743     albertel 3529:     return \%userroles;  
1.11      www      3530: }
                   3531: 
1.567     raeburn  3532: sub set_arearole {
                   3533:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3534: # log the associated role with the area
                   3535:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3536:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3537: }
                   3538: 
                   3539: sub custom_roleprivs {
                   3540:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3541:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3542:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3543:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3544:         my ($rdummy,$roledef)=
                   3545:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3546:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3547:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3548:             if (defined($syspriv)) {
                   3549:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3550:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3551:             }
                   3552:             if ($tdomain ne '') {
                   3553:                 if (defined($dompriv)) {
                   3554:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3555:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3556:                 }
                   3557:                 if (($trest ne '') && (defined($coursepriv))) {
                   3558:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3559:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3560:                 }
                   3561:             }
                   3562:         }
                   3563:     }
                   3564: }
                   3565: 
1.678     raeburn  3566: sub group_roleprivs {
                   3567:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3568:     my $access = 1;
                   3569:     my $now = time;
                   3570:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3571:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3572:     if ($access) {
1.811     albertel 3573:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3574:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3575:     }
                   3576: }
1.567     raeburn  3577: 
                   3578: sub standard_roleprivs {
                   3579:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3580:     if (defined($pr{$trole.':s'})) {
                   3581:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3582:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3583:     }
                   3584:     if ($tdomain ne '') {
                   3585:         if (defined($pr{$trole.':d'})) {
                   3586:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3587:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3588:         }
                   3589:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3590:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3591:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3592:         }
                   3593:     }
                   3594: }
                   3595: 
                   3596: sub set_userprivs {
1.678     raeburn  3597:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3598:     my $author=0;
                   3599:     my $adv=0;
1.678     raeburn  3600:     my %grouproles = ();
                   3601:     if (keys(%{$allgroups}) > 0) {
                   3602:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3603:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3604:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3605:                 $trole = $1;
                   3606:                 $area = $2;
1.681     raeburn  3607:                 $sec = $3;
                   3608:                 $extendedarea = $area.$sec;
                   3609:                 if (exists($$allgroups{$area})) {
                   3610:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3611:                         my $spec = $trole.'.'.$extendedarea;
                   3612:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3613:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3614:                     }
                   3615:                 }
                   3616:             }
                   3617:         }
                   3618:     }
1.800     albertel 3619:     foreach my $group (keys(%grouproles)) {
                   3620:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3621:     }
1.800     albertel 3622:     foreach my $role (keys(%{$allroles})) {
                   3623:         my %thesepriv;
1.941     raeburn  3624:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3625:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3626:             if ($item ne '') {
                   3627:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3628:                 if ($restrictions eq '') {
                   3629:                     $thesepriv{$privilege}='F';
                   3630:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3631:                     $thesepriv{$privilege}.=$restrictions;
                   3632:                 }
                   3633:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3634:             }
                   3635:         }
                   3636:         my $thesestr='';
1.800     albertel 3637:         foreach my $priv (keys(%thesepriv)) {
                   3638: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3639: 	}
                   3640:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3641:     }
                   3642:     return ($author,$adv);
                   3643: }
                   3644: 
1.12      www      3645: # --------------------------------------------------------------- get interface
                   3646: 
                   3647: sub get {
1.131     albertel 3648:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3649:    my $items='';
1.800     albertel 3650:    foreach my $item (@$storearr) {
                   3651:        $items.=&escape($item).'&';
1.191     harris41 3652:    }
1.12      www      3653:    $items=~s/\&$//;
1.620     albertel 3654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3655:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3656:    my $uhome=&homeserver($uname,$udomain);
                   3657: 
1.133     albertel 3658:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3659:    my @pairs=split(/\&/,$rep);
1.273     albertel 3660:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3661:      return @pairs;
                   3662:    }
1.15      www      3663:    my %returnhash=();
1.42      www      3664:    my $i=0;
1.800     albertel 3665:    foreach my $item (@$storearr) {
                   3666:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3667:       $i++;
1.191     harris41 3668:    }
1.15      www      3669:    return %returnhash;
1.27      www      3670: }
                   3671: 
                   3672: # --------------------------------------------------------------- del interface
                   3673: 
                   3674: sub del {
1.133     albertel 3675:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3676:    my $items='';
1.800     albertel 3677:    foreach my $item (@$storearr) {
                   3678:        $items.=&escape($item).'&';
1.191     harris41 3679:    }
1.27      www      3680:    $items=~s/\&$//;
1.620     albertel 3681:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3682:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3683:    my $uhome=&homeserver($uname,$udomain);
                   3684: 
                   3685:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3686: }
                   3687: 
                   3688: # -------------------------------------------------------------- dump interface
                   3689: 
                   3690: sub dump {
1.755     albertel 3691:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3692:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3693:     if (!$uname) { $uname=$env{'user.name'}; }
                   3694:     my $uhome=&homeserver($uname,$udomain);
                   3695:     if ($regexp) {
                   3696: 	$regexp=&escape($regexp);
                   3697:     } else {
                   3698: 	$regexp='.';
                   3699:     }
                   3700:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3701:     my @pairs=split(/\&/,$rep);
                   3702:     my %returnhash=();
                   3703:     foreach my $item (@pairs) {
                   3704: 	my ($key,$value)=split(/=/,$item,2);
                   3705: 	$key = &unescape($key);
                   3706: 	next if ($key =~ /^error: 2 /);
                   3707: 	$returnhash{$key}=&thaw_unescape($value);
                   3708:     }
                   3709:     return %returnhash;
1.407     www      3710: }
                   3711: 
1.717     albertel 3712: # --------------------------------------------------------- dumpstore interface
                   3713: 
                   3714: sub dumpstore {
                   3715:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3716:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3717:    if (!$uname) { $uname=$env{'user.name'}; }
                   3718:    my $uhome=&homeserver($uname,$udomain);
                   3719:    if ($regexp) {
                   3720:        $regexp=&escape($regexp);
                   3721:    } else {
                   3722:        $regexp='.';
                   3723:    }
                   3724:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3725:    my @pairs=split(/\&/,$rep);
                   3726:    my %returnhash=();
                   3727:    foreach my $item (@pairs) {
                   3728:        my ($key,$value)=split(/=/,$item,2);
                   3729:        next if ($key =~ /^error: 2 /);
                   3730:        $returnhash{$key}=&thaw_unescape($value);
                   3731:    }
                   3732:    return %returnhash;
1.717     albertel 3733: }
                   3734: 
1.407     www      3735: # -------------------------------------------------------------- keys interface
                   3736: 
                   3737: sub getkeys {
                   3738:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3740:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3741:    my $uhome=&homeserver($uname,$udomain);
                   3742:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3743:    my @keyarray=();
1.800     albertel 3744:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3745:       next if ($key =~ /^error: 2 /);
1.800     albertel 3746:       push(@keyarray,&unescape($key));
1.407     www      3747:    }
                   3748:    return @keyarray;
1.318     matthew  3749: }
                   3750: 
1.319     matthew  3751: # --------------------------------------------------------------- currentdump
                   3752: sub currentdump {
1.328     matthew  3753:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3754:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3755:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3756:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3757:    my $uhome = &homeserver($sname,$sdom);
                   3758:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3759:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3760:    #
1.318     matthew  3761:    my %returnhash=();
1.319     matthew  3762:    #
                   3763:    if ($rep eq "unknown_cmd") { 
                   3764:        # an old lond will not know currentdump
                   3765:        # Do a dump and make it look like a currentdump
1.822     albertel 3766:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3767:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3768:        my %hash = @tmp;
                   3769:        @tmp=();
1.424     matthew  3770:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3771:    } else {
                   3772:        my @pairs=split(/\&/,$rep);
1.800     albertel 3773:        foreach my $pair (@pairs) {
                   3774:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3775:            my ($symb,$param) = split(/:/,$key);
                   3776:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3777:                                                         &thaw_unescape($value);
1.319     matthew  3778:        }
1.191     harris41 3779:    }
1.12      www      3780:    return %returnhash;
1.424     matthew  3781: }
                   3782: 
                   3783: sub convert_dump_to_currentdump{
                   3784:     my %hash = %{shift()};
                   3785:     my %returnhash;
                   3786:     # Code ripped from lond, essentially.  The only difference
                   3787:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3788:     # we might run in to problems with parameter names =~ /^v\./
                   3789:     while (my ($key,$value) = each(%hash)) {
                   3790:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3791: 	$symb  = &unescape($symb);
                   3792: 	$param = &unescape($param);
1.424     matthew  3793:         next if ($v eq 'version' || $symb eq 'keys');
                   3794:         next if (exists($returnhash{$symb}) &&
                   3795:                  exists($returnhash{$symb}->{$param}) &&
                   3796:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3797:         $returnhash{$symb}->{$param}=$value;
                   3798:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3799:     }
                   3800:     #
                   3801:     # Remove all of the keys in the hashes which keep track of
                   3802:     # the version of the parameter.
                   3803:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3804:         # use a foreach because we are going to delete from the hash.
                   3805:         foreach my $key (keys(%$param_hash)) {
                   3806:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3807:         }
                   3808:     }
                   3809:     return \%returnhash;
1.12      www      3810: }
                   3811: 
1.627     albertel 3812: # ------------------------------------------------------ critical inc interface
                   3813: 
                   3814: sub cinc {
                   3815:     return &inc(@_,'critical');
                   3816: }
                   3817: 
1.449     matthew  3818: # --------------------------------------------------------------- inc interface
                   3819: 
                   3820: sub inc {
1.627     albertel 3821:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3822:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3823:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3824:     my $uhome=&homeserver($uname,$udomain);
                   3825:     my $items='';
                   3826:     if (! ref($store)) {
                   3827:         # got a single value, so use that instead
                   3828:         $items = &escape($store).'=&';
                   3829:     } elsif (ref($store) eq 'SCALAR') {
                   3830:         $items = &escape($$store).'=&';        
                   3831:     } elsif (ref($store) eq 'ARRAY') {
                   3832:         $items = join('=&',map {&escape($_);} @{$store});
                   3833:     } elsif (ref($store) eq 'HASH') {
                   3834:         while (my($key,$value) = each(%{$store})) {
                   3835:             $items.= &escape($key).'='.&escape($value).'&';
                   3836:         }
                   3837:     }
                   3838:     $items=~s/\&$//;
1.627     albertel 3839:     if ($critical) {
                   3840: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3841:     } else {
                   3842: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3843:     }
1.449     matthew  3844: }
                   3845: 
1.12      www      3846: # --------------------------------------------------------------- put interface
                   3847: 
                   3848: sub put {
1.134     albertel 3849:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3851:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3852:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3853:    my $items='';
1.800     albertel 3854:    foreach my $item (keys(%$storehash)) {
                   3855:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3856:    }
1.12      www      3857:    $items=~s/\&$//;
1.134     albertel 3858:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3859: }
                   3860: 
1.631     albertel 3861: # ------------------------------------------------------------ newput interface
                   3862: 
                   3863: sub newput {
                   3864:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3865:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3866:    if (!$uname) { $uname=$env{'user.name'}; }
                   3867:    my $uhome=&homeserver($uname,$udomain);
                   3868:    my $items='';
                   3869:    foreach my $key (keys(%$storehash)) {
                   3870:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3871:    }
                   3872:    $items=~s/\&$//;
                   3873:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3874: }
                   3875: 
                   3876: # ---------------------------------------------------------  putstore interface
                   3877: 
1.524     raeburn  3878: sub putstore {
1.715     albertel 3879:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3881:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3882:    my $uhome=&homeserver($uname,$udomain);
                   3883:    my $items='';
1.715     albertel 3884:    foreach my $key (keys(%$storehash)) {
                   3885:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3886:    }
1.715     albertel 3887:    $items=~s/\&$//;
1.716     albertel 3888:    my $esc_symb=&escape($symb);
                   3889:    my $esc_v=&escape($version);
1.715     albertel 3890:    my $reply =
1.716     albertel 3891:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3892: 	      $uhome);
                   3893:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3894:        # gfall back to way things use to be done
1.715     albertel 3895:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3896: 			    $uname);
1.524     raeburn  3897:    }
1.715     albertel 3898:    return $reply;
                   3899: }
                   3900: 
                   3901: sub old_putstore {
1.716     albertel 3902:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3904:     if (!$uname) { $uname=$env{'user.name'}; }
                   3905:     my $uhome=&homeserver($uname,$udomain);
                   3906:     my %newstorehash;
1.800     albertel 3907:     foreach my $item (keys(%$storehash)) {
                   3908: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3909: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3910:     }
                   3911:     my $items='';
                   3912:     my %allitems = ();
1.800     albertel 3913:     foreach my $item (keys(%newstorehash)) {
                   3914: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3915: 	    my $key = $1.':keys:'.$2;
                   3916: 	    $allitems{$key} .= $3.':';
                   3917: 	}
1.800     albertel 3918: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3919:     }
1.800     albertel 3920:     foreach my $item (keys(%allitems)) {
                   3921: 	$allitems{$item} =~ s/\:$//;
                   3922: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3923:     }
                   3924:     $items=~s/\&$//;
                   3925:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3926: }
                   3927: 
1.47      www      3928: # ------------------------------------------------------ critical put interface
                   3929: 
                   3930: sub cput {
1.134     albertel 3931:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3932:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3933:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3934:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3935:    my $items='';
1.800     albertel 3936:    foreach my $item (keys(%$storehash)) {
                   3937:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3938:    }
1.47      www      3939:    $items=~s/\&$//;
1.134     albertel 3940:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3941: }
                   3942: 
                   3943: # -------------------------------------------------------------- eget interface
                   3944: 
                   3945: sub eget {
1.133     albertel 3946:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3947:    my $items='';
1.800     albertel 3948:    foreach my $item (@$storearr) {
                   3949:        $items.=&escape($item).'&';
1.191     harris41 3950:    }
1.12      www      3951:    $items=~s/\&$//;
1.620     albertel 3952:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3953:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3954:    my $uhome=&homeserver($uname,$udomain);
                   3955:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3956:    my @pairs=split(/\&/,$rep);
                   3957:    my %returnhash=();
1.42      www      3958:    my $i=0;
1.800     albertel 3959:    foreach my $item (@$storearr) {
                   3960:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3961:       $i++;
1.191     harris41 3962:    }
1.12      www      3963:    return %returnhash;
                   3964: }
                   3965: 
1.667     albertel 3966: # ------------------------------------------------------------ tmpput interface
                   3967: sub tmpput {
1.802     raeburn  3968:     my ($storehash,$server,$context)=@_;
1.667     albertel 3969:     my $items='';
1.800     albertel 3970:     foreach my $item (keys(%$storehash)) {
                   3971: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3972:     }
                   3973:     $items=~s/\&$//;
1.802     raeburn  3974:     if (defined($context)) {
                   3975:         $items .= ':'.&escape($context);
                   3976:     }
1.667     albertel 3977:     return &reply("tmpput:$items",$server);
                   3978: }
                   3979: 
                   3980: # ------------------------------------------------------------ tmpget interface
                   3981: sub tmpget {
1.688     albertel 3982:     my ($token,$server)=@_;
                   3983:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3984:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3985:     my %returnhash;
                   3986:     foreach my $item (split(/\&/,$rep)) {
                   3987: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  3988:         next if ($key =~ /^error: 2 /);
1.667     albertel 3989: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3990:     }
                   3991:     return %returnhash;
                   3992: }
                   3993: 
1.688     albertel 3994: # ------------------------------------------------------------ tmpget interface
                   3995: sub tmpdel {
                   3996:     my ($token,$server)=@_;
                   3997:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3998:     return &reply("tmpdel:$token",$server);
                   3999: }
                   4000: 
1.765     albertel 4001: # -------------------------------------------------- portfolio access checking
                   4002: 
                   4003: sub portfolio_access {
1.766     albertel 4004:     my ($requrl) = @_;
1.765     albertel 4005:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4006:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4007:     if ($result) {
                   4008:         my %setters;
                   4009:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4010:             my ($startblock,$endblock) =
                   4011:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4012:             if ($startblock && $endblock) {
                   4013:                 return 'B';
                   4014:             }
                   4015:         } else {
                   4016:             my ($startblock,$endblock) =
                   4017:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4018:             if ($startblock && $endblock) {
                   4019:                 return 'B';
                   4020:             }
                   4021:         }
                   4022:     }
1.765     albertel 4023:     if ($result eq 'ok') {
1.766     albertel 4024:        return 'F';
1.765     albertel 4025:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4026:        return 'A';
1.765     albertel 4027:     }
1.766     albertel 4028:     return '';
1.765     albertel 4029: }
                   4030: 
                   4031: sub get_portfolio_access {
1.767     albertel 4032:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4033: 
                   4034:     if (!ref($access_hash)) {
                   4035: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4036: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4037: 						   $file_name);
                   4038: 	$access_hash = $access_controls{$file_name};
                   4039:     }
                   4040: 
1.765     albertel 4041:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4042:     my $now = time;
                   4043:     if (ref($access_hash) eq 'HASH') {
                   4044:         foreach my $key (keys(%{$access_hash})) {
                   4045:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4046:             if ($start > $now) {
                   4047:                 next;
                   4048:             }
                   4049:             if ($end && $end<$now) {
                   4050:                 next;
                   4051:             }
                   4052:             if ($scope eq 'public') {
                   4053:                 $public = $key;
                   4054:                 last;
                   4055:             } elsif ($scope eq 'guest') {
                   4056:                 $guest = $key;
                   4057:             } elsif ($scope eq 'domains') {
                   4058:                 push(@domains,$key);
                   4059:             } elsif ($scope eq 'users') {
                   4060:                 push(@users,$key);
                   4061:             } elsif ($scope eq 'course') {
                   4062:                 push(@courses,$key);
                   4063:             } elsif ($scope eq 'group') {
                   4064:                 push(@groups,$key);
                   4065:             }
                   4066:         }
                   4067:         if ($public) {
                   4068:             return 'ok';
                   4069:         }
                   4070:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4071:             if ($guest) {
                   4072:                 return $guest;
                   4073:             }
                   4074:         } else {
                   4075:             if (@domains > 0) {
                   4076:                 foreach my $domkey (@domains) {
                   4077:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4078:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4079:                             return 'ok';
                   4080:                         }
                   4081:                     }
                   4082:                 }
                   4083:             }
                   4084:             if (@users > 0) {
                   4085:                 foreach my $userkey (@users) {
1.865     raeburn  4086:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4087:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4088:                             if (ref($item) eq 'HASH') {
                   4089:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4090:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4091:                                     return 'ok';
                   4092:                                 }
                   4093:                             }
                   4094:                         }
                   4095:                     } 
1.765     albertel 4096:                 }
                   4097:             }
                   4098:             my %roleshash;
                   4099:             my @courses_and_groups = @courses;
                   4100:             push(@courses_and_groups,@groups); 
                   4101:             if (@courses_and_groups > 0) {
                   4102:                 my (%allgroups,%allroles); 
                   4103:                 my ($start,$end,$role,$sec,$group);
                   4104:                 foreach my $envkey (%env) {
1.811     albertel 4105:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4106:                         my $cid = $2.'_'.$3; 
                   4107:                         if ($1 eq 'gr') {
                   4108:                             $group = $4;
                   4109:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4110:                         } else {
                   4111:                             if ($4 eq '') {
                   4112:                                 $sec = 'none';
                   4113:                             } else {
                   4114:                                 $sec = $4;
                   4115:                             }
                   4116:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4117:                         }
1.811     albertel 4118:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4119:                         my $cid = $2.'_'.$3;
                   4120:                         if ($4 eq '') {
                   4121:                             $sec = 'none';
                   4122:                         } else {
                   4123:                             $sec = $4;
                   4124:                         }
                   4125:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4126:                     }
                   4127:                 }
                   4128:                 if (keys(%allroles) == 0) {
                   4129:                     return;
                   4130:                 }
                   4131:                 foreach my $key (@courses_and_groups) {
                   4132:                     my %content = %{$$access_hash{$key}};
                   4133:                     my $cnum = $content{'number'};
                   4134:                     my $cdom = $content{'domain'};
                   4135:                     my $cid = $cdom.'_'.$cnum;
                   4136:                     if (!exists($allroles{$cid})) {
                   4137:                         next;
                   4138:                     }    
                   4139:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4140:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4141:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4142:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4143:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4144:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4145:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4146:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4147:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4148:                                         if (grep/^all$/,@sections) {
                   4149:                                             return 'ok';
                   4150:                                         } else {
                   4151:                                             if (grep/^$sec$/,@sections) {
                   4152:                                                 return 'ok';
                   4153:                                             }
                   4154:                                         }
                   4155:                                     }
                   4156:                                 }
                   4157:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4158:                                     if (grep/^none$/,@groups) {
                   4159:                                         return 'ok';
                   4160:                                     }
                   4161:                                 } else {
                   4162:                                     if (grep/^all$/,@groups) {
                   4163:                                         return 'ok';
                   4164:                                     } 
                   4165:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4166:                                         if (grep/^$group$/,@groups) {
                   4167:                                             return 'ok';
                   4168:                                         }
                   4169:                                     }
                   4170:                                 } 
                   4171:                             }
                   4172:                         }
                   4173:                     }
                   4174:                 }
                   4175:             }
                   4176:             if ($guest) {
                   4177:                 return $guest;
                   4178:             }
                   4179:         }
                   4180:     }
                   4181:     return;
                   4182: }
                   4183: 
                   4184: sub course_group_datechecker {
                   4185:     my ($dates,$now,$status) = @_;
                   4186:     my ($start,$end) = split(/\./,$dates);
                   4187:     if (!$start && !$end) {
                   4188:         return 'ok';
                   4189:     }
                   4190:     if (grep/^active$/,@{$status}) {
                   4191:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4192:             return 'ok';
                   4193:         }
                   4194:     }
                   4195:     if (grep/^previous$/,@{$status}) {
                   4196:         if ($end > $now ) {
                   4197:             return 'ok';
                   4198:         }
                   4199:     }
                   4200:     if (grep/^future$/,@{$status}) {
                   4201:         if ($start > $now) {
                   4202:             return 'ok';
                   4203:         }
                   4204:     }
                   4205:     return; 
                   4206: }
                   4207: 
                   4208: sub parse_portfolio_url {
                   4209:     my ($url) = @_;
                   4210: 
                   4211:     my ($type,$udom,$unum,$group,$file_name);
                   4212:     
1.823     albertel 4213:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4214: 	$type = 1;
                   4215:         $udom = $1;
                   4216:         $unum = $2;
                   4217:         $file_name = $3;
1.823     albertel 4218:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4219: 	$type = 2;
                   4220:         $udom = $1;
                   4221:         $unum = $2;
                   4222:         $group = $3;
                   4223:         $file_name = $3.'/'.$4;
                   4224:     }
                   4225:     if (wantarray) {
                   4226: 	return ($type,$udom,$unum,$file_name,$group);
                   4227:     }
                   4228:     return $type;
                   4229: }
                   4230: 
                   4231: sub is_portfolio_url {
                   4232:     my ($url) = @_;
                   4233:     return scalar(&parse_portfolio_url($url));
                   4234: }
                   4235: 
1.798     raeburn  4236: sub is_portfolio_file {
                   4237:     my ($file) = @_;
1.820     raeburn  4238:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4239:         return 1;
                   4240:     }
                   4241:     return;
                   4242: }
                   4243: 
                   4244: 
1.341     www      4245: # ---------------------------------------------- Custom access rule evaluation
                   4246: 
                   4247: sub customaccess {
                   4248:     my ($priv,$uri)=@_;
1.807     albertel 4249:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4250:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4251:     $udom = &LONCAPA::clean_domain($udom);
                   4252:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4253:     my $access=0;
1.800     albertel 4254:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4255: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4256: 	if ($type eq 'user') {
                   4257: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4258: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4259: 		if ($tdom) {
                   4260: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4261: 		}
1.896     albertel 4262: 		if ($tuname) {
                   4263: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4264: 		}
                   4265: 		$access=($effect eq 'allow');
                   4266: 		last;
                   4267: 	    }
                   4268: 	} else {
                   4269: 	    if ($role) {
                   4270: 		if ($role ne $urole) { next; }
                   4271: 	    }
                   4272: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4273: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4274: 		if ($tdom) {
                   4275: 		    if ($tdom ne $udom) { next; }
                   4276: 		}
                   4277: 		if ($tcrs) {
                   4278: 		    if ($tcrs ne $ucrs) { next; }
                   4279: 		}
                   4280: 		if ($tsec) {
                   4281: 		    if ($tsec ne $usec) { next; }
                   4282: 		}
                   4283: 		$access=($effect eq 'allow');
                   4284: 		last;
                   4285: 	    }
                   4286: 	    if ($realm eq '' && $role eq '') {
                   4287: 		$access=($effect eq 'allow');
                   4288: 	    }
1.402     bowersj2 4289: 	}
1.341     www      4290:     }
                   4291:     return $access;
                   4292: }
                   4293: 
1.103     harris41 4294: # ------------------------------------------------- Check for a user privilege
1.12      www      4295: 
                   4296: sub allowed {
1.810     raeburn  4297:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4298:     my $ver_orguri=$uri;
1.439     www      4299:     $uri=&deversion($uri);
1.152     www      4300:     my $orguri=$uri;
1.52      www      4301:     $uri=&declutter($uri);
1.809     raeburn  4302: 
1.810     raeburn  4303:     if ($priv eq 'evb') {
                   4304: # Evade communication block restrictions for specified role in a course
                   4305:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4306:             return $1;
                   4307:         } else {
                   4308:             return;
                   4309:         }
                   4310:     }
                   4311: 
1.620     albertel 4312:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4313: # Free bre access to adm and meta resources
1.775     albertel 4314:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4315: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4316: 	&& ($priv eq 'bre')) {
1.14      www      4317: 	return 'F';
1.159     www      4318:     }
                   4319: 
1.545     banghart 4320: # Free bre access to user's own portfolio contents
1.714     raeburn  4321:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4322:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4323: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4324:         my %setters;
                   4325:         my ($startblock,$endblock) = 
                   4326:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4327:         if ($startblock && $endblock) {
                   4328:             return 'B';
                   4329:         } else {
                   4330:             return 'F';
                   4331:         }
1.545     banghart 4332:     }
                   4333: 
1.762     raeburn  4334: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4335:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4336:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4337:         if (exists($env{'request.course.id'})) {
                   4338:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4339:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4340:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4341:                 my $courseprivid=$env{'request.course.id'};
                   4342:                 $courseprivid=~s/\_/\//;
                   4343:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4344:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4345:                     return $1; 
1.762     raeburn  4346:                 } else {
                   4347:                     if ($env{'request.course.sec'}) {
                   4348:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4349:                     }
                   4350:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4351:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4352:                         return $2;
                   4353:                     }
1.714     raeburn  4354:                 }
                   4355:             }
                   4356:         }
                   4357:     }
                   4358: 
1.159     www      4359: # Free bre to public access
                   4360: 
                   4361:     if ($priv eq 'bre') {
1.238     www      4362:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4363: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4364:            return 'F'; 
                   4365:         }
1.238     www      4366:         if ($copyright eq 'priv') {
                   4367:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4368: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4369: 		return '';
                   4370:             }
                   4371:         }
                   4372:         if ($copyright eq 'domain') {
                   4373:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4374: 	    unless (($env{'user.domain'} eq $1) ||
                   4375:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4376: 		return '';
                   4377:             }
1.262     matthew  4378:         }
1.620     albertel 4379:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4380:             # Library role, so allow browsing of resources in this domain.
                   4381:             return 'F';
1.238     www      4382:         }
1.341     www      4383:         if ($copyright eq 'custom') {
                   4384: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4385:         }
1.14      www      4386:     }
1.264     matthew  4387:     # Domain coordinator is trying to create a course
1.620     albertel 4388:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4389:         # uri is the requested domain in this case.
                   4390:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4391:         # a role of dc for the domain in question.
1.620     albertel 4392:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4393:     }
1.29      www      4394: 
1.52      www      4395:     my $thisallowed='';
                   4396:     my $statecond=0;
                   4397:     my $courseprivid='';
                   4398: 
                   4399: # Course
                   4400: 
1.620     albertel 4401:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4402:        $thisallowed.=$1;
                   4403:     }
1.29      www      4404: 
1.52      www      4405: # Domain
                   4406: 
1.620     albertel 4407:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4408:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4409:        $thisallowed.=$1;
                   4410:     }
1.52      www      4411: 
                   4412: # Course: uri itself is a course
1.66      www      4413:     my $courseuri=$uri;
                   4414:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4415:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4416: 
1.620     albertel 4417:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4418:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4419:        $thisallowed.=$1;
                   4420:     }
1.29      www      4421: 
1.665     albertel 4422: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4423: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4424:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4425: 	$thisallowed='';
1.671     raeburn  4426:         my ($match)=&is_on_map($uri);
                   4427:         if ($match) {
                   4428:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4429:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4430:                 $thisallowed.=$1;
                   4431:             }
                   4432:         } else {
1.705     albertel 4433:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4434:             if ($refuri) {
                   4435:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4436:                     $thisallowed='F';
1.671     raeburn  4437:                 } else {
                   4438:                     $refuri=&declutter($refuri);
                   4439:                     my ($match) = &is_on_map($refuri);
                   4440:                     if ($match) {
                   4441:                         $thisallowed='F';
                   4442:                     }
1.669     raeburn  4443:                 }
1.671     raeburn  4444:             }
                   4445:         }
1.314     www      4446:     }
1.492     albertel 4447: 
1.766     albertel 4448:     if ($priv eq 'bre'
                   4449: 	&& $thisallowed ne 'F' 
                   4450: 	&& $thisallowed ne '2'
                   4451: 	&& &is_portfolio_url($uri)) {
                   4452: 	$thisallowed = &portfolio_access($uri);
                   4453:     }
                   4454:     
1.52      www      4455: # Full access at system, domain or course-wide level? Exit.
1.29      www      4456: 
                   4457:     if ($thisallowed=~/F/) {
                   4458: 	return 'F';
                   4459:     }
                   4460: 
1.52      www      4461: # If this is generating or modifying users, exit with special codes
1.29      www      4462: 
1.643     www      4463:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4464: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4465: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4466: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4467: 	    unless ($auname) { return $thisallowed; }
                   4468: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4469: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4470: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4471: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4472: 	}
1.52      www      4473: 	return $thisallowed;
                   4474:     }
                   4475: #
1.103     harris41 4476: # Gathered so far: system, domain and course wide privileges
1.52      www      4477: #
                   4478: # Course: See if uri or referer is an individual resource that is part of 
                   4479: # the course
                   4480: 
1.620     albertel 4481:     if ($env{'request.course.id'}) {
1.232     www      4482: 
1.620     albertel 4483:        $courseprivid=$env{'request.course.id'};
                   4484:        if ($env{'request.course.sec'}) {
                   4485:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4486:        }
                   4487:        $courseprivid=~s/\_/\//;
                   4488:        my $checkreferer=1;
1.232     www      4489:        my ($match,$cond)=&is_on_map($uri);
                   4490:        if ($match) {
                   4491:            $statecond=$cond;
1.620     albertel 4492:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4493:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4494:                $thisallowed.=$1;
                   4495:                $checkreferer=0;
                   4496:            }
1.29      www      4497:        }
1.83      www      4498:        
1.148     www      4499:        if ($checkreferer) {
1.620     albertel 4500: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4501:             unless ($refuri) {
1.800     albertel 4502:                 foreach my $key (keys(%env)) {
                   4503: 		    if ($key=~/^httpref\..*\*/) {
                   4504: 			my $pattern=$key;
1.156     www      4505:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4506:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4507:                         $pattern=~s/\//\\\//g;
1.152     www      4508:                         if ($orguri=~/$pattern/) {
1.800     albertel 4509: 			    $refuri=$env{$key};
1.148     www      4510:                         }
                   4511:                     }
1.191     harris41 4512:                 }
1.148     www      4513:             }
1.232     www      4514: 
1.148     www      4515:          if ($refuri) { 
1.152     www      4516: 	  $refuri=&declutter($refuri);
1.232     www      4517:           my ($match,$cond)=&is_on_map($refuri);
                   4518:             if ($match) {
                   4519:               my $refstatecond=$cond;
1.620     albertel 4520:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4521:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4522:                   $thisallowed.=$1;
1.53      www      4523:                   $uri=$refuri;
                   4524:                   $statecond=$refstatecond;
1.52      www      4525:               }
                   4526:           }
1.148     www      4527:         }
1.29      www      4528:        }
1.52      www      4529:    }
1.29      www      4530: 
1.52      www      4531: #
1.103     harris41 4532: # Gathered now: all privileges that could apply, and condition number
1.52      www      4533: # 
                   4534: #
                   4535: # Full or no access?
                   4536: #
1.29      www      4537: 
1.52      www      4538:     if ($thisallowed=~/F/) {
                   4539: 	return 'F';
                   4540:     }
1.29      www      4541: 
1.52      www      4542:     unless ($thisallowed) {
                   4543:         return '';
                   4544:     }
1.29      www      4545: 
1.52      www      4546: # Restrictions exist, deal with them
                   4547: #
                   4548: #   C:according to course preferences
                   4549: #   R:according to resource settings
                   4550: #   L:unless locked
                   4551: #   X:according to user session state
                   4552: #
                   4553: 
                   4554: # Possibly locked functionality, check all courses
1.54      www      4555: # Locks might take effect only after 10 minutes cache expiration for other
                   4556: # courses, and 2 minutes for current course
1.52      www      4557: 
                   4558:     my $envkey;
                   4559:     if ($thisallowed=~/L/) {
1.620     albertel 4560:         foreach $envkey (keys %env) {
1.54      www      4561:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4562:                my $courseid=$2;
                   4563:                my $roleid=$1.'.'.$2;
1.92      www      4564:                $courseid=~s/^\///;
1.54      www      4565:                my $expiretime=600;
1.620     albertel 4566:                if ($env{'request.role'} eq $roleid) {
1.54      www      4567: 		  $expiretime=120;
                   4568:                }
                   4569: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4570:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4571:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4572: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4573:                }
1.620     albertel 4574:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4575:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4576: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4577:                        &log($env{'user.domain'},$env{'user.name'},
                   4578:                             $env{'user.home'},
1.57      www      4579:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4580:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4581:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4582: 		       return '';
                   4583:                    }
                   4584:                }
1.620     albertel 4585:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4586:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4587: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4588:                        &log($env{'user.domain'},$env{'user.name'},
                   4589:                             $env{'user.home'},
1.57      www      4590:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4591:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4592:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4593: 		       return '';
                   4594:                    }
                   4595:                }
                   4596: 	   }
1.29      www      4597:        }
1.52      www      4598:     }
                   4599:    
                   4600: #
                   4601: # Rest of the restrictions depend on selected course
                   4602: #
                   4603: 
1.620     albertel 4604:     unless ($env{'request.course.id'}) {
1.766     albertel 4605: 	if ($thisallowed eq 'A') {
                   4606: 	    return 'A';
1.814     raeburn  4607:         } elsif ($thisallowed eq 'B') {
                   4608:             return 'B';
1.766     albertel 4609: 	} else {
                   4610: 	    return '1';
                   4611: 	}
1.52      www      4612:     }
1.29      www      4613: 
1.52      www      4614: #
                   4615: # Now user is definitely in a course
                   4616: #
1.53      www      4617: 
                   4618: 
                   4619: # Course preferences
                   4620: 
                   4621:    if ($thisallowed=~/C/) {
1.620     albertel 4622:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4623:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4624:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4625: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4626: 	   if ($priv ne 'pch') { 
                   4627: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4628: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4629: 			$env{'request.course.id'});
                   4630: 	   }
1.237     www      4631:            return '';
                   4632:        }
                   4633: 
1.620     albertel 4634:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4635: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4636: 	   if ($priv ne 'pch') { 
                   4637: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4638: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4639: 			$env{'request.course.id'});
                   4640: 	   }
1.54      www      4641:            return '';
                   4642:        }
1.53      www      4643:    }
                   4644: 
                   4645: # Resource preferences
                   4646: 
                   4647:    if ($thisallowed=~/R/) {
1.620     albertel 4648:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4649:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4650: 	   if ($priv ne 'pch') { 
                   4651: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4652: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4653: 	   }
                   4654: 	   return '';
1.54      www      4655:        }
1.53      www      4656:    }
1.30      www      4657: 
1.246     www      4658: # Restricted by state or randomout?
1.30      www      4659: 
1.52      www      4660:    if ($thisallowed=~/X/) {
1.620     albertel 4661:       if ($env{'acc.randomout'}) {
1.579     albertel 4662: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4663:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4664:             return ''; 
                   4665:          }
1.247     www      4666:       }
                   4667:       if (&condval($statecond)) {
1.52      www      4668: 	 return '2';
                   4669:       } else {
                   4670:          return '';
                   4671:       }
                   4672:    }
1.30      www      4673: 
1.766     albertel 4674:     if ($thisallowed eq 'A') {
                   4675: 	return 'A';
1.814     raeburn  4676:     } elsif ($thisallowed eq 'B') {
                   4677:         return 'B';
1.766     albertel 4678:     }
1.52      www      4679:    return 'F';
1.232     www      4680: }
                   4681: 
1.710     albertel 4682: sub split_uri_for_cond {
                   4683:     my $uri=&deversion(&declutter(shift));
                   4684:     my @uriparts=split(/\//,$uri);
                   4685:     my $filename=pop(@uriparts);
                   4686:     my $pathname=join('/',@uriparts);
                   4687:     return ($pathname,$filename);
                   4688: }
1.232     www      4689: # --------------------------------------------------- Is a resource on the map?
                   4690: 
                   4691: sub is_on_map {
1.710     albertel 4692:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4693:     #Trying to find the conditional for the file
1.620     albertel 4694:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4695: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4696:     if ($match) {
1.289     bowersj2 4697: 	return (1,$1);
                   4698:     } else {
1.434     www      4699: 	return (0,0);
1.289     bowersj2 4700:     }
1.12      www      4701: }
                   4702: 
1.427     www      4703: # --------------------------------------------------------- Get symb from alias
                   4704: 
                   4705: sub get_symb_from_alias {
                   4706:     my $symb=shift;
                   4707:     my ($map,$resid,$url)=&decode_symb($symb);
                   4708: # Already is a symb
                   4709:     if ($url) { return $symb; }
                   4710: # Must be an alias
                   4711:     my $aliassymb='';
                   4712:     my %bighash;
1.620     albertel 4713:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4714:                             &GDBM_READER(),0640)) {
                   4715:         my $rid=$bighash{'mapalias_'.$symb};
                   4716: 	if ($rid) {
                   4717: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4718: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4719: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4720: 	}
                   4721:         untie %bighash;
                   4722:     }
                   4723:     return $aliassymb;
                   4724: }
                   4725: 
1.12      www      4726: # ----------------------------------------------------------------- Define Role
                   4727: 
                   4728: sub definerole {
                   4729:   if (allowed('mcr','/')) {
                   4730:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4731:     foreach my $role (split(':',$sysrole)) {
                   4732: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4733:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4734:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4735: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4736:                return "refused:s:$crole&$cqual"; 
                   4737:             }
                   4738:         }
1.191     harris41 4739:     }
1.800     albertel 4740:     foreach my $role (split(':',$domrole)) {
                   4741: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4742:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4743:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4744: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4745:                return "refused:d:$crole&$cqual"; 
                   4746:             }
                   4747:         }
1.191     harris41 4748:     }
1.800     albertel 4749:     foreach my $role (split(':',$courole)) {
                   4750: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4751:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4752:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4753: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4754:                return "refused:c:$crole&$cqual"; 
                   4755:             }
                   4756:         }
1.191     harris41 4757:     }
1.620     albertel 4758:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4759:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4760: 	        "rolesdef_$rolename=".
                   4761:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4762:     return reply($command,$env{'user.home'});
1.12      www      4763:   } else {
                   4764:     return 'refused';
                   4765:   }
1.105     harris41 4766: }
                   4767: 
                   4768: # ---------------- Make a metadata query against the network of library servers
                   4769: 
                   4770: sub metadata_query {
1.244     matthew  4771:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4772:     my %rhash;
1.845     albertel 4773:     my %libserv = &all_library();
1.244     matthew  4774:     my @server_list = (defined($server_array) ? @$server_array
                   4775:                                               : keys(%libserv) );
                   4776:     for my $server (@server_list) {
1.118     harris41 4777: 	unless ($custom or $customshow) {
                   4778: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4779: 	    $rhash{$server}=$reply;
                   4780: 	}
                   4781: 	else {
                   4782: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4783: 			     &escape($custom).':'.&escape($customshow),
                   4784: 			     $server);
                   4785: 	    $rhash{$server}=$reply;
                   4786: 	}
1.112     harris41 4787:     }
1.118     harris41 4788:     return \%rhash;
1.240     www      4789: }
                   4790: 
                   4791: # ----------------------------------------- Send log queries and wait for reply
                   4792: 
                   4793: sub log_query {
                   4794:     my ($uname,$udom,$query,%filters)=@_;
                   4795:     my $uhome=&homeserver($uname,$udom);
                   4796:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4797:     my $uhost=&hostname($uhome);
1.800     albertel 4798:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4799:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4800:                        $uhome);
1.479     albertel 4801:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4802:     return get_query_reply($queryid);
                   4803: }
                   4804: 
1.818     raeburn  4805: # -------------------------- Update MySQL table for portfolio file
                   4806: 
                   4807: sub update_portfolio_table {
1.821     raeburn  4808:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4809:     my $homeserver = &homeserver($uname,$udom);
                   4810:     my $queryid=
1.821     raeburn  4811:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4812:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4813:     my $reply = &get_query_reply($queryid);
                   4814:     return $reply;
                   4815: }
                   4816: 
1.899     raeburn  4817: # -------------------------- Update MySQL allusers table
                   4818: 
                   4819: sub update_allusers_table {
                   4820:     my ($uname,$udom,$names) = @_;
                   4821:     my $homeserver = &homeserver($uname,$udom);
                   4822:     my $queryid=
                   4823:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4824:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4825:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4826:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4827:                'generation='.&escape($names->{'generation'}).'%%'.
                   4828:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4829:                'id='.&escape($names->{'id'}),$homeserver);
                   4830:     my $reply = &get_query_reply($queryid);
                   4831:     return $reply;
                   4832: }
                   4833: 
1.508     raeburn  4834: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4835: 
                   4836: sub fetch_enrollment_query {
1.511     raeburn  4837:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4838:     my $homeserver;
1.547     raeburn  4839:     my $maxtries = 1;
1.508     raeburn  4840:     if ($context eq 'automated') {
                   4841:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4842:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4843:     } else {
                   4844:         $homeserver = &homeserver($cnum,$dom);
                   4845:     }
1.838     albertel 4846:     my $host=&hostname($homeserver);
1.506     raeburn  4847:     my $cmd = '';
1.800     albertel 4848:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4849:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4850:     }
                   4851:     $cmd =~ s/%%$//;
                   4852:     $cmd = &escape($cmd);
                   4853:     my $query = 'fetchenrollment';
1.620     albertel 4854:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4855:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4856:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4857:         return 'error: '.$queryid;
                   4858:     }
1.506     raeburn  4859:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4860:     my $tries = 1;
                   4861:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4862:         $reply = &get_query_reply($queryid);
                   4863:         $tries ++;
                   4864:     }
1.526     raeburn  4865:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4866:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4867:     } else {
1.901     albertel 4868:         my @responses = split(/:/,$reply);
1.515     raeburn  4869:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4870:             foreach my $line (@responses) {
                   4871:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4872:                 $$replyref{$key} = $value;
                   4873:             }
                   4874:         } else {
1.506     raeburn  4875:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4876:             foreach my $line (@responses) {
                   4877:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4878:                 $$replyref{$key} = $value;
                   4879:                 if ($value > 0) {
1.800     albertel 4880:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4881:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4882:                         my $destname = $pathname.'/'.$filename;
                   4883:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4884:                         if ($xml_classlist =~ /^error/) {
                   4885:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4886:                         } else {
1.506     raeburn  4887:                             if ( open(FILE,">$destname") ) {
                   4888:                                 print FILE &unescape($xml_classlist);
                   4889:                                 close(FILE);
1.526     raeburn  4890:                             } else {
                   4891:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4892:                             }
                   4893:                         }
                   4894:                     }
                   4895:                 }
                   4896:             }
                   4897:         }
                   4898:         return 'ok';
                   4899:     }
                   4900:     return 'error';
                   4901: }
                   4902: 
1.242     www      4903: sub get_query_reply {
                   4904:     my $queryid=shift;
1.240     www      4905:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4906:     my $reply='';
                   4907:     for (1..100) {
                   4908: 	sleep 2;
                   4909:         if (-e $replyfile.'.end') {
1.448     albertel 4910: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4911: 		$reply = join('',<$fh>);
                   4912: 		close($fh);
1.240     www      4913: 	   } else { return 'error: reply_file_error'; }
1.242     www      4914:            return &unescape($reply);
                   4915: 	}
1.240     www      4916:     }
1.242     www      4917:     return 'timeout:'.$queryid;
1.240     www      4918: }
                   4919: 
                   4920: sub courselog_query {
1.241     www      4921: #
                   4922: # possible filters:
                   4923: # url: url or symb
                   4924: # username
                   4925: # domain
                   4926: # action: view, submit, grade
                   4927: # start: timestamp
                   4928: # end: timestamp
                   4929: #
1.240     www      4930:     my (%filters)=@_;
1.620     albertel 4931:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4932:     if ($filters{'url'}) {
                   4933: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4934:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4935:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4936:     }
1.620     albertel 4937:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4938:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4939:     return &log_query($cname,$cdom,'courselog',%filters);
                   4940: }
                   4941: 
                   4942: sub userlog_query {
1.858     raeburn  4943: #
                   4944: # possible filters:
                   4945: # action: log check role
                   4946: # start: timestamp
                   4947: # end: timestamp
                   4948: #
1.240     www      4949:     my ($uname,$udom,%filters)=@_;
                   4950:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4951: }
                   4952: 
1.506     raeburn  4953: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4954: 
                   4955: sub auto_run {
1.508     raeburn  4956:     my ($cnum,$cdom) = @_;
1.876     raeburn  4957:     my $response = 0;
                   4958:     my $settings;
                   4959:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4960:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4961:         $settings = $domconfig{'autoenroll'};
                   4962:         if ($settings->{'run'} eq '1') {
                   4963:             $response = 1;
                   4964:         }
                   4965:     } else {
1.934     raeburn  4966:         my $homeserver;
                   4967:         if (&is_course($cdom,$cnum)) {
                   4968:             $homeserver = &homeserver($cnum,$cdom);
                   4969:         } else {
                   4970:             $homeserver = &domain($cdom,'primary');
                   4971:         }
                   4972:         if ($homeserver ne 'no_host') {
                   4973:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4974:         }
1.876     raeburn  4975:     }
1.506     raeburn  4976:     return $response;
                   4977: }
1.776     albertel 4978: 
1.506     raeburn  4979: sub auto_get_sections {
1.508     raeburn  4980:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4981:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4982:     my @secs = ();
1.511     raeburn  4983:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4984:     unless ($response eq 'refused') {
1.901     albertel 4985:         @secs = split(/:/,$response);
1.506     raeburn  4986:     }
                   4987:     return @secs;
                   4988: }
1.776     albertel 4989: 
1.506     raeburn  4990: sub auto_new_course {
1.508     raeburn  4991:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4992:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4993:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4994:     return $response;
                   4995: }
1.776     albertel 4996: 
1.506     raeburn  4997: sub auto_validate_courseID {
1.508     raeburn  4998:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4999:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5000:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5001:     return $response;
                   5002: }
1.776     albertel 5003: 
1.506     raeburn  5004: sub auto_create_password {
1.873     raeburn  5005:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5006:     my ($homeserver,$response);
1.506     raeburn  5007:     my $create_passwd = 0;
                   5008:     my $authchk = '';
1.873     raeburn  5009:     if ($udom =~ /^$match_domain$/) {
                   5010:         $homeserver = &domain($udom,'primary');
                   5011:     }
                   5012:     if ($homeserver eq '') {
                   5013:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5014:             $homeserver = &homeserver($cnum,$cdom);
                   5015:         }
                   5016:     }
                   5017:     if ($homeserver eq '') {
                   5018:         $authchk = 'nodomain';
1.506     raeburn  5019:     } else {
1.873     raeburn  5020:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5021:         if ($response eq 'refused') {
                   5022:             $authchk = 'refused';
                   5023:         } else {
1.901     albertel 5024:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5025:         }
1.506     raeburn  5026:     }
                   5027:     return ($authparam,$create_passwd,$authchk);
                   5028: }
                   5029: 
1.706     raeburn  5030: sub auto_photo_permission {
                   5031:     my ($cnum,$cdom,$students) = @_;
                   5032:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5033:     my ($outcome,$perm_reqd,$conditions) = 
                   5034: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5035:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5036: 	return (undef,undef);
                   5037:     }
1.706     raeburn  5038:     return ($outcome,$perm_reqd,$conditions);
                   5039: }
                   5040: 
                   5041: sub auto_checkphotos {
                   5042:     my ($uname,$udom,$pid) = @_;
                   5043:     my $homeserver = &homeserver($uname,$udom);
                   5044:     my ($result,$resulttype);
                   5045:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5046: 				   &escape($uname).':'.&escape($pid),
                   5047: 				   $homeserver));
1.709     albertel 5048:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5049: 	return (undef,undef);
                   5050:     }
1.706     raeburn  5051:     if ($outcome) {
                   5052:         ($result,$resulttype) = split(/:/,$outcome);
                   5053:     } 
                   5054:     return ($result,$resulttype);
                   5055: }
                   5056: 
                   5057: sub auto_photochoice {
                   5058:     my ($cnum,$cdom) = @_;
                   5059:     my $homeserver = &homeserver($cnum,$cdom);
                   5060:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5061: 						       &escape($cdom),
                   5062: 						       $homeserver)));
1.709     albertel 5063:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5064: 	return (undef,undef);
                   5065:     }
1.706     raeburn  5066:     return ($update,$comment);
                   5067: }
                   5068: 
                   5069: sub auto_photoupdate {
                   5070:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5071:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5072:     my $host=&hostname($homeserver);
1.706     raeburn  5073:     my $cmd = '';
                   5074:     my $maxtries = 1;
1.800     albertel 5075:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5076:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5077:     }
                   5078:     $cmd =~ s/%%$//;
                   5079:     $cmd = &escape($cmd);
                   5080:     my $query = 'institutionalphotos';
                   5081:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5082:     unless ($queryid=~/^\Q$host\E\_/) {
                   5083:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5084:         return 'error: '.$queryid;
                   5085:     }
                   5086:     my $reply = &get_query_reply($queryid);
                   5087:     my $tries = 1;
                   5088:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5089:         $reply = &get_query_reply($queryid);
                   5090:         $tries ++;
                   5091:     }
                   5092:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5093:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5094:     } else {
                   5095:         my @responses = split(/:/,$reply);
                   5096:         my $outcome = shift(@responses); 
                   5097:         foreach my $item (@responses) {
                   5098:             my ($key,$value) = split(/=/,$item);
                   5099:             $$photo{$key} = $value;
                   5100:         }
                   5101:         return $outcome;
                   5102:     }
                   5103:     return 'error';
                   5104: }
                   5105: 
1.521     raeburn  5106: sub auto_instcode_format {
1.793     albertel 5107:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5108: 	$cat_order) = @_;
1.521     raeburn  5109:     my $courses = '';
1.772     raeburn  5110:     my @homeservers;
1.521     raeburn  5111:     if ($caller eq 'global') {
1.841     albertel 5112: 	my %servers = &get_servers($codedom,'library');
                   5113: 	foreach my $tryserver (keys(%servers)) {
                   5114: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5115: 		push(@homeservers,$tryserver);
                   5116: 	    }
1.584     raeburn  5117:         }
1.521     raeburn  5118:     } else {
1.772     raeburn  5119:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5120:     }
1.793     albertel 5121:     foreach my $code (keys(%{$instcodes})) {
                   5122:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5123:     }
                   5124:     chop($courses);
1.772     raeburn  5125:     my $ok_response = 0;
                   5126:     my $response;
                   5127:     while (@homeservers > 0 && $ok_response == 0) {
                   5128:         my $server = shift(@homeservers); 
                   5129:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5130:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5131:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5132: 		split(/:/,$response);
1.772     raeburn  5133:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5134:             push(@{$codetitles},&str2array($codetitles_str));
                   5135:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5136:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5137:             $ok_response = 1;
                   5138:         }
                   5139:     }
                   5140:     if ($ok_response) {
1.521     raeburn  5141:         return 'ok';
1.772     raeburn  5142:     } else {
                   5143:         return $response;
1.521     raeburn  5144:     }
                   5145: }
                   5146: 
1.792     raeburn  5147: sub auto_instcode_defaults {
                   5148:     my ($domain,$returnhash,$code_order) = @_;
                   5149:     my @homeservers;
1.841     albertel 5150: 
                   5151:     my %servers = &get_servers($domain,'library');
                   5152:     foreach my $tryserver (keys(%servers)) {
                   5153: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5154: 	    push(@homeservers,$tryserver);
                   5155: 	}
1.792     raeburn  5156:     }
1.841     albertel 5157: 
1.792     raeburn  5158:     my $response;
1.841     albertel 5159:     foreach my $server (@homeservers) {
1.792     raeburn  5160:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5161:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5162: 	
                   5163: 	foreach my $pair (split(/\&/,$response)) {
                   5164: 	    my ($name,$value)=split(/\=/,$pair);
                   5165: 	    if ($name eq 'code_order') {
                   5166: 		@{$code_order} = split(/\&/,&unescape($value));
                   5167: 	    } else {
                   5168: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5169: 	    }
                   5170: 	}
                   5171: 	return 'ok';
1.792     raeburn  5172:     }
1.841     albertel 5173: 
                   5174:     return $response;
1.792     raeburn  5175: } 
                   5176: 
1.777     albertel 5177: sub auto_validate_class_sec {
1.918     raeburn  5178:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5179:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5180:     my $ownerlist;
                   5181:     if (ref($owners) eq 'ARRAY') {
                   5182:         $ownerlist = join(',',@{$owners});
                   5183:     } else {
                   5184:         $ownerlist = $owners;
                   5185:     }
1.773     raeburn  5186:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5187:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5188:     return $response;
                   5189: }
                   5190: 
1.679     raeburn  5191: # ------------------------------------------------------- Course Group routines
                   5192: 
                   5193: sub get_coursegroups {
1.809     raeburn  5194:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5195:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5196: }
                   5197: 
1.679     raeburn  5198: sub modify_coursegroup {
                   5199:     my ($cdom,$cnum,$groupsettings) = @_;
                   5200:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5201: }
                   5202: 
1.809     raeburn  5203: sub toggle_coursegroup_status {
                   5204:     my ($cdom,$cnum,$group,$action) = @_;
                   5205:     my ($from_namespace,$to_namespace);
                   5206:     if ($action eq 'delete') {
                   5207:         $from_namespace = 'coursegroups';
                   5208:         $to_namespace = 'deleted_groups';
                   5209:     } else {
                   5210:         $from_namespace = 'deleted_groups';
                   5211:         $to_namespace = 'coursegroups';
                   5212:     }
                   5213:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5214:     if (my $tmp = &error(%curr_group)) {
                   5215:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5216:         return ('read error',$tmp);
                   5217:     } else {
                   5218:         my %savedsettings = %curr_group; 
1.809     raeburn  5219:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5220:         my $deloutcome;
                   5221:         if ($result eq 'ok') {
1.809     raeburn  5222:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5223:         } else {
                   5224:             return ('write error',$result);
                   5225:         }
                   5226:         if ($deloutcome eq 'ok') {
                   5227:             return 'ok';
                   5228:         } else {
                   5229:             return ('delete error',$deloutcome);
                   5230:         }
                   5231:     }
                   5232: }
                   5233: 
1.679     raeburn  5234: sub modify_group_roles {
                   5235:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5236:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5237:     my $role = 'gr/'.&escape($userprivs);
                   5238:     my ($uname,$udom) = split(/:/,$user);
                   5239:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5240:     if ($result eq 'ok') {
                   5241:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5242:     }
1.679     raeburn  5243:     return $result;
                   5244: }
                   5245: 
                   5246: sub modify_coursegroup_membership {
                   5247:     my ($cdom,$cnum,$membership) = @_;
                   5248:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5249:     return $result;
                   5250: }
                   5251: 
1.682     raeburn  5252: sub get_active_groups {
                   5253:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5254:     my $now = time;
                   5255:     my %groups = ();
                   5256:     foreach my $key (keys(%env)) {
1.811     albertel 5257:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5258:             my ($start,$end) = split(/\./,$env{$key});
                   5259:             if (($end!=0) && ($end<$now)) { next; }
                   5260:             if (($start!=0) && ($start>$now)) { next; }
                   5261:             if ($1 eq $cdom && $2 eq $cnum) {
                   5262:                 $groups{$3} = $env{$key} ;
                   5263:             }
                   5264:         }
                   5265:     }
                   5266:     return %groups;
                   5267: }
                   5268: 
1.683     raeburn  5269: sub get_group_membership {
                   5270:     my ($cdom,$cnum,$group) = @_;
                   5271:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5272: }
                   5273: 
                   5274: sub get_users_groups {
                   5275:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5276:     my @usersgroups;
1.683     raeburn  5277:     my $cachetime=1800;
                   5278: 
                   5279:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5280:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5281:     if (defined($cached)) {
1.734     albertel 5282:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5283:     } else {  
                   5284:         $grouplist = '';
1.816     raeburn  5285:         my $courseurl = &courseid_to_courseurl($courseid);
                   5286:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5287:         my $access_end = $env{'course.'.$courseid.
                   5288:                               '.default_enrollment_end_date'};
                   5289:         my $now = time;
                   5290:         foreach my $key (keys(%roleshash)) {
                   5291:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5292:                 my $group = $1;
                   5293:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5294:                     my $start = $2;
                   5295:                     my $end = $1;
                   5296:                     if ($start == -1) { next; } # deleted from group
                   5297:                     if (($start!=0) && ($start>$now)) { next; }
                   5298:                     if (($end!=0) && ($end<$now)) {
                   5299:                         if ($access_end && $access_end < $now) {
                   5300:                             if ($access_end - $end < 86400) {
                   5301:                                 push(@usersgroups,$group);
1.733     raeburn  5302:                             }
                   5303:                         }
1.817     raeburn  5304:                         next;
1.733     raeburn  5305:                     }
1.817     raeburn  5306:                     push(@usersgroups,$group);
1.683     raeburn  5307:                 }
                   5308:             }
                   5309:         }
1.817     raeburn  5310:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5311:         $grouplist = join(':',@usersgroups);
                   5312:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5313:     }
1.733     raeburn  5314:     return @usersgroups;
1.683     raeburn  5315: }
                   5316: 
                   5317: sub devalidate_getgroups_cache {
                   5318:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5319:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5320: 
1.683     raeburn  5321:     my $hashid="$udom:$uname:$courseid";
                   5322:     &devalidate_cache_new('getgroups',$hashid);
                   5323: }
                   5324: 
1.12      www      5325: # ------------------------------------------------------------------ Plain Text
                   5326: 
                   5327: sub plaintext {
1.742     raeburn  5328:     my ($short,$type,$cid) = @_;
1.758     albertel 5329:     if ($short =~ /^cr/) {
                   5330: 	return (split('/',$short))[-1];
                   5331:     }
1.742     raeburn  5332:     if (!defined($cid)) {
                   5333:         $cid = $env{'request.course.id'};
                   5334:     }
                   5335:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5336:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5337:                                           '.plaintext'});
                   5338:     }
                   5339:     my %rolenames = (
                   5340:                       Course => 'std',
                   5341:                       Group => 'alt1',
                   5342:                     );
                   5343:     if (defined($type) && 
                   5344:          defined($rolenames{$type}) && 
                   5345:          defined($prp{$short}{$rolenames{$type}})) {
                   5346:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5347:     } else {
                   5348:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5349:     }
1.12      www      5350: }
                   5351: 
                   5352: # ----------------------------------------------------------------- Assign Role
                   5353: 
                   5354: sub assignrole {
1.947     raeburn  5355:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
1.21      www      5356:     my $mrole;
                   5357:     if ($role =~ /^cr\//) {
1.393     www      5358:         my $cwosec=$url;
1.811     albertel 5359:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5360: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5361:            &logthis('Refused custom assignrole: '.
                   5362:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5363: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5364:            return 'refused'; 
                   5365:         }
1.21      www      5366:         $mrole='cr';
1.678     raeburn  5367:     } elsif ($role =~ /^gr\//) {
                   5368:         my $cwogrp=$url;
1.811     albertel 5369:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5370:         unless (&allowed('mdg',$cwogrp)) {
                   5371:             &logthis('Refused group assignrole: '.
                   5372:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5373:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5374:             return 'refused';
                   5375:         }
                   5376:         $mrole='gr';
1.21      www      5377:     } else {
1.82      www      5378:         my $cwosec=$url;
1.811     albertel 5379:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5380:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5381:             my $refused;
                   5382:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5383:                 if (!(&allowed('c'.$role,$url))) {
                   5384:                     $refused = 1;
                   5385:                 }
                   5386:             } else {
                   5387:                 $refused = 1;
                   5388:             }
1.947     raeburn  5389:             if ($refused) {
                   5390:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5391:                     $refused = '';
                   5392:                 } else {
                   5393:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5394:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5395: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5396:                     return 'refused';
                   5397:                 }
1.932     raeburn  5398:             }
1.104     www      5399:         }
1.21      www      5400:         $mrole=$role;
                   5401:     }
1.620     albertel 5402:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5403:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5404:     if ($end) { $command.='_'.$end; }
1.21      www      5405:     if ($start) {
                   5406: 	if ($end) { 
1.81      www      5407:            $command.='_'.$start; 
1.21      www      5408:         } else {
1.81      www      5409:            $command.='_0_'.$start;
1.21      www      5410:         }
                   5411:     }
1.739     raeburn  5412:     my $origstart = $start;
                   5413:     my $origend = $end;
1.357     www      5414: # actually delete
                   5415:     if ($deleteflag) {
1.373     www      5416: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5417: # modify command to delete the role
1.620     albertel 5418:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5419:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5420: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5421: # set start and finish to negative values for userrolelog
                   5422:            $start=-1;
                   5423:            $end=-1;
                   5424:         }
                   5425:     }
                   5426: # send command
1.349     www      5427:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5428: # log new user role if status is ok
1.349     www      5429:     if ($answer eq 'ok') {
1.663     raeburn  5430: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5431: # for course roles, perform group memberships changes triggered by role change.
                   5432:         unless ($role =~ /^gr/) {
                   5433:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5434:                                              $origstart);
                   5435:         }
1.349     www      5436:     }
                   5437:     return $answer;
1.169     harris41 5438: }
                   5439: 
                   5440: # -------------------------------------------------- Modify user authentication
1.197     www      5441: # Overrides without validation
                   5442: 
1.169     harris41 5443: sub modifyuserauth {
                   5444:     my ($udom,$uname,$umode,$upass)=@_;
                   5445:     my $uhome=&homeserver($uname,$udom);
1.197     www      5446:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5447:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5448:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5449:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5450:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5451: 		     &escape($upass),$uhome);
1.620     albertel 5452:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5453:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5454:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5455:     &log($udom,,$uname,$uhome,
1.620     albertel 5456:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5457:                                      $env{'user.name'}.', '.$umode.
1.197     www      5458:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5459:     unless ($reply eq 'ok') {
1.197     www      5460:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5461: 	return 'error: '.$reply;
                   5462:     }   
1.170     harris41 5463:     return 'ok';
1.80      www      5464: }
                   5465: 
1.81      www      5466: # --------------------------------------------------------------- Modify a user
1.80      www      5467: 
1.81      www      5468: sub modifyuser {
1.206     matthew  5469:     my ($udom,    $uname, $uid,
                   5470:         $umode,   $upass, $first,
                   5471:         $middle,  $last,  $gene,
1.387     www      5472:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5473:     $udom= &LONCAPA::clean_domain($udom);
                   5474:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5475:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5476:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5477: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5478:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5479:                                      ' desiredhome not specified'). 
1.620     albertel 5480:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5481:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5482:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5483: # ----------------------------------------------------------------- Create User
1.406     albertel 5484:     if (($uhome eq 'no_host') && 
                   5485: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5486:         my $unhome='';
1.844     albertel 5487:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5488:             $unhome = $desiredhome;
1.620     albertel 5489: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5490: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5491:         } else { # load balancing routine for determining $unhome
1.81      www      5492:             my $loadm=10000000;
1.841     albertel 5493: 	    my %servers = &get_servers($udom,'library');
                   5494: 	    foreach my $tryserver (keys(%servers)) {
                   5495: 		my $answer=reply('load',$tryserver);
                   5496: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5497: 		    $loadm=$answer;
                   5498: 		    $unhome=$tryserver;
                   5499: 		}
1.80      www      5500: 	    }
                   5501:         }
                   5502:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5503: 	    return 'error: unable to find a home server for '.$uname.
                   5504:                    ' in domain '.$udom;
1.80      www      5505:         }
                   5506:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5507:                          &escape($upass),$unhome);
                   5508: 	unless ($reply eq 'ok') {
                   5509:             return 'error: '.$reply;
                   5510:         }   
1.230     stredwic 5511:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5512:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5513: 	    return 'error: unable verify users home machine.';
1.80      www      5514:         }
1.209     matthew  5515:     }   # End of creation of new user
1.80      www      5516: # ---------------------------------------------------------------------- Add ID
                   5517:     if ($uid) {
                   5518:        $uid=~tr/A-Z/a-z/;
                   5519:        my %uidhash=&idrget($udom,$uname);
1.196     www      5520:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5521:          && (!$forceid)) {
1.80      www      5522: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5523: 	      return 'error: user id "'.$uid.'" does not match '.
                   5524:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5525:           }
                   5526:        } else {
                   5527: 	  &idput($udom,($uname => $uid));
                   5528:        }
                   5529:     }
                   5530: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5531:     my @tmp=&get('environment',
1.899     raeburn  5532: 		   ['firstname','middlename','lastname','generation','id',
                   5533:                     'permanentemail'],
1.134     albertel 5534: 		   $udom,$uname);
1.313     matthew  5535:     my %names;
                   5536:     if ($tmp[0] =~ m/^error:.*/) { 
                   5537:         %names=(); 
                   5538:     } else {
                   5539:         %names = @tmp;
                   5540:     }
1.388     www      5541: #
                   5542: # Make sure to not trash student environment if instructor does not bother
                   5543: # to supply name and email information
                   5544: #
                   5545:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5546:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5547:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5548:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5549:     if ($email) {
                   5550:        $email=~s/[^\w\@\.\-\,]//gs;
                   5551:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5552: 			   $names{'critnotification'} = $email;
                   5553: 			   $names{'permanentemail'} = $email; }
                   5554:     }
1.899     raeburn  5555:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5556:     my $reply = &put('environment', \%names, $udom,$uname);
                   5557:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5558:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5559:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5560:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5561:              $umode.', '.$first.', '.$middle.', '.
                   5562: 	     $last.', '.$gene.' by '.
1.620     albertel 5563:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5564:     return 'ok';
1.80      www      5565: }
                   5566: 
1.81      www      5567: # -------------------------------------------------------------- Modify student
1.80      www      5568: 
1.81      www      5569: sub modifystudent {
                   5570:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5571:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5572:     if (!$cid) {
1.620     albertel 5573: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5574: 	    return 'not_in_class';
                   5575: 	}
1.80      www      5576:     }
                   5577: # --------------------------------------------------------------- Make the user
1.81      www      5578:     my $reply=&modifyuser
1.209     matthew  5579: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5580:          $desiredhome,$email);
1.80      www      5581:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5582:     # This will cause &modify_student_enrollment to get the uid from the
                   5583:     # students environment
                   5584:     $uid = undef if (!$forceid);
1.455     albertel 5585:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5586: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5587:     return $reply;
                   5588: }
                   5589: 
                   5590: sub modify_student_enrollment {
1.947     raeburn  5591:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
1.455     albertel 5592:     my ($cdom,$cnum,$chome);
                   5593:     if (!$cid) {
1.620     albertel 5594: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5595: 	    return 'not_in_class';
                   5596: 	}
1.620     albertel 5597: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5598: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5599:     } else {
                   5600: 	($cdom,$cnum)=split(/_/,$cid);
                   5601:     }
1.620     albertel 5602:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5603:     if (!$chome) {
1.457     raeburn  5604: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5605:     }
1.455     albertel 5606:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5607:     # Make sure the user exists
1.81      www      5608:     my $uhome=&homeserver($uname,$udom);
                   5609:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5610: 	return 'error: no such user';
                   5611:     }
1.297     matthew  5612:     # Get student data if we were not given enough information
                   5613:     if (!defined($first)  || $first  eq '' || 
                   5614:         !defined($last)   || $last   eq '' || 
                   5615:         !defined($uid)    || $uid    eq '' || 
                   5616:         !defined($middle) || $middle eq '' || 
                   5617:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5618:         # They did not supply us with enough data to enroll the student, so
                   5619:         # we need to pick up more information.
1.297     matthew  5620:         my %tmp = &get('environment',
1.294     matthew  5621:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5622:                        ,$udom,$uname);
                   5623: 
1.800     albertel 5624:         #foreach my $key (keys(%tmp)) {
                   5625:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5626:         #}
1.294     matthew  5627:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5628:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5629:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5630:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5631:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5632:     }
1.556     albertel 5633:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5634:     my $reply=cput('classlist',
                   5635: 		   {"$uname:$udom" => 
1.515     raeburn  5636: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5637: 		   $cdom,$cnum);
1.81      www      5638:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5639: 	return 'error: '.$reply;
1.652     albertel 5640:     } else {
                   5641: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5642:     }
1.297     matthew  5643:     # Add student role to user
1.83      www      5644:     my $uurl='/'.$cid;
1.81      www      5645:     $uurl=~s/\_/\//g;
                   5646:     if ($usec) {
                   5647: 	$uurl.='/'.$usec;
                   5648:     }
1.947     raeburn  5649:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
1.21      www      5650: }
                   5651: 
1.556     albertel 5652: sub format_name {
                   5653:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5654:     my $name;
                   5655:     if ($first ne 'lastname') {
                   5656: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5657:     } else {
                   5658: 	if ($lastname=~/\S/) {
                   5659: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5660: 	    $name=~s/\s+,/,/;
                   5661: 	} else {
                   5662: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5663: 	}
                   5664:     }
                   5665:     $name=~s/^\s+//;
                   5666:     $name=~s/\s+$//;
                   5667:     $name=~s/\s+/ /g;
                   5668:     return $name;
                   5669: }
                   5670: 
1.84      www      5671: # ------------------------------------------------- Write to course preferences
                   5672: 
                   5673: sub writecoursepref {
                   5674:     my ($courseid,%prefs)=@_;
                   5675:     $courseid=~s/^\///;
                   5676:     $courseid=~s/\_/\//g;
                   5677:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5678:     my $chome=homeserver($cnum,$cdomain);
                   5679:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5680: 	return 'error: no such course';
                   5681:     }
                   5682:     my $cstring='';
1.800     albertel 5683:     foreach my $pref (keys(%prefs)) {
                   5684: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5685:     }
1.84      www      5686:     $cstring=~s/\&$//;
                   5687:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5688: }
                   5689: 
                   5690: # ---------------------------------------------------------- Make/modify course
                   5691: 
                   5692: sub createcourse {
1.741     raeburn  5693:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5694:         $course_owner,$crstype)=@_;
1.84      www      5695:     $url=&declutter($url);
                   5696:     my $cid='';
1.264     matthew  5697:     unless (&allowed('ccc',$udom)) {
1.84      www      5698:         return 'refused';
                   5699:     }
                   5700: # ------------------------------------------------------------------- Create ID
1.674     www      5701:    my $uname=int(1+rand(9)).
                   5702:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5703:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5704:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5705: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5706:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5707:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5708:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5709:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5710:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5711:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5712:            return 'error: unable to generate unique course-ID';
                   5713:        } 
                   5714:    }
1.264     matthew  5715: # ------------------------------------------------ Check supplied server name
1.620     albertel 5716:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5717:     if (! &is_library($course_server)) {
1.264     matthew  5718:         return 'error:bad server name '.$course_server;
                   5719:     }
1.84      www      5720: # ------------------------------------------------------------- Make the course
                   5721:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5722:                       $course_server);
1.84      www      5723:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5724:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5725:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5726: 	return 'error: no such course';
                   5727:     }
1.271     www      5728: # ----------------------------------------------------------------- Course made
1.516     raeburn  5729: # log existence
1.918     raeburn  5730:     my $newcourse = {
                   5731:                     $udom.'_'.$uname => {
1.921     raeburn  5732:                                      description => $description,
                   5733:                                      inst_code   => $inst_code,
                   5734:                                      owner       => $course_owner,
                   5735:                                      type        => $crstype,
1.918     raeburn  5736:                                                 },
                   5737:                     };
1.921     raeburn  5738:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5739: # set toplevel url
1.271     www      5740:     my $topurl=$url;
                   5741:     unless ($nonstandard) {
                   5742: # ------------------------------------------ For standard courses, make top url
                   5743:         my $mapurl=&clutter($url);
1.278     www      5744:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5745:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5746: <map>
                   5747: <resource id="1" type="start"></resource>
                   5748: <resource id="2" src="$mapurl"></resource>
                   5749: <resource id="3" type="finish"></resource>
                   5750: <link index="1" from="1" to="2"></link>
                   5751: <link index="2" from="2" to="3"></link>
                   5752: </map>
                   5753: ENDINITMAP
                   5754:         $topurl=&declutter(
1.638     albertel 5755:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5756:                           );
                   5757:     }
                   5758: # ----------------------------------------------------------- Write preferences
1.84      www      5759:     &writecoursepref($udom.'_'.$uname,
                   5760:                      ('description' => $description,
1.271     www      5761:                       'url'         => $topurl));
1.84      www      5762:     return '/'.$udom.'/'.$uname;
                   5763: }
                   5764: 
1.813     albertel 5765: sub is_course {
                   5766:     my ($cdom,$cnum) = @_;
                   5767:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5768: 				undef,'.');
1.813     albertel 5769:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5770:         return 1;
                   5771:     }
                   5772:     return 0;
                   5773: }
                   5774: 
1.21      www      5775: # ---------------------------------------------------------- Assign Custom Role
                   5776: 
                   5777: sub assigncustomrole {
1.357     www      5778:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5779:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5780:                        $end,$start,$deleteflag);
1.21      www      5781: }
                   5782: 
                   5783: # ----------------------------------------------------------------- Revoke Role
                   5784: 
                   5785: sub revokerole {
1.357     www      5786:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5787:     my $now=time;
1.357     www      5788:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5789: }
                   5790: 
                   5791: # ---------------------------------------------------------- Revoke Custom Role
                   5792: 
                   5793: sub revokecustomrole {
1.357     www      5794:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5795:     my $now=time;
1.357     www      5796:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5797:            $deleteflag);
1.17      www      5798: }
                   5799: 
1.533     banghart 5800: # ------------------------------------------------------------ Disk usage
1.535     albertel 5801: sub diskusage {
1.533     banghart 5802:     my ($udom,$uname,$directoryRoot)=@_;
                   5803:     $directoryRoot =~ s/\/$//;
1.535     albertel 5804:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5805:     return $listing;
1.512     banghart 5806: }
                   5807: 
1.566     banghart 5808: sub is_locked {
                   5809:     my ($file_name, $domain, $user) = @_;
                   5810:     my @check;
                   5811:     my $is_locked;
                   5812:     push @check, $file_name;
1.613     albertel 5813:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5814: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5815:     my ($tmp)=keys(%locked);
                   5816:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5817:     
1.566     banghart 5818:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5819:         $is_locked = 'false';
                   5820:         foreach my $entry (@{$locked{$file_name}}) {
                   5821:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5822:                $is_locked = 'true';
                   5823:                last;
1.745     raeburn  5824:            }
                   5825:        }
1.566     banghart 5826:     } else {
                   5827:         $is_locked = 'false';
                   5828:     }
                   5829: }
                   5830: 
1.759     albertel 5831: sub declutter_portfile {
                   5832:     my ($file) = @_;
1.833     albertel 5833:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5834:     return $file;
                   5835: }
                   5836: 
1.559     banghart 5837: # ------------------------------------------------------------- Mark as Read Only
                   5838: 
                   5839: sub mark_as_readonly {
                   5840:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5841:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5842:     my ($tmp)=keys(%current_permissions);
                   5843:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5844:     foreach my $file (@{$files}) {
1.759     albertel 5845: 	$file = &declutter_portfile($file);
1.561     banghart 5846:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5847:     }
1.613     albertel 5848:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5849:     return;
                   5850: }
                   5851: 
1.572     banghart 5852: # ------------------------------------------------------------Save Selected Files
                   5853: 
                   5854: sub save_selected_files {
                   5855:     my ($user, $path, @files) = @_;
                   5856:     my $filename = $user."savedfiles";
1.573     banghart 5857:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5858:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5859:     foreach my $file (@files) {
1.620     albertel 5860:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5861:     }
                   5862:     foreach my $file (@other_files) {
1.574     banghart 5863:         print (OUT $file."\n");
1.572     banghart 5864:     }
1.574     banghart 5865:     close (OUT);
1.572     banghart 5866:     return 'ok';
                   5867: }
                   5868: 
1.574     banghart 5869: sub clear_selected_files {
                   5870:     my ($user) = @_;
                   5871:     my $filename = $user."savedfiles";
                   5872:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5873:     print (OUT undef);
                   5874:     close (OUT);
                   5875:     return ("ok");    
                   5876: }
                   5877: 
1.572     banghart 5878: sub files_in_path {
                   5879:     my ($user, $path) = @_;
                   5880:     my $filename = $user."savedfiles";
                   5881:     my %return_files;
1.574     banghart 5882:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5883:     while (my $line_in = <IN>) {
1.574     banghart 5884:         chomp ($line_in);
                   5885:         my @paths_and_file = split (m!/!, $line_in);
                   5886:         my $file_part = pop (@paths_and_file);
                   5887:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5888:         $path_part.='/';
                   5889:         my $path_and_file = $path_part.$file_part;
                   5890:         if ($path_part eq $path) {
                   5891:             $return_files{$file_part}= 'selected';
                   5892:         }
                   5893:     }
1.574     banghart 5894:     close (IN);
                   5895:     return (\%return_files);
1.572     banghart 5896: }
                   5897: 
                   5898: # called in portfolio select mode, to show files selected NOT in current directory
                   5899: sub files_not_in_path {
                   5900:     my ($user, $path) = @_;
                   5901:     my $filename = $user."savedfiles";
                   5902:     my @return_files;
                   5903:     my $path_part;
1.800     albertel 5904:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5905:     while (my $line = <IN>) {
1.572     banghart 5906:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5907:         my @paths_and_file = split(m|/|, $line);
                   5908:         my $file_part = pop(@paths_and_file);
                   5909:         chomp($file_part);
                   5910:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5911:         $path_part .= '/';
                   5912:         my $path_and_file = $path_part.$file_part;
                   5913:         if ($path_part ne $path) {
1.800     albertel 5914:             push(@return_files, ($path_and_file));
1.572     banghart 5915:         }
                   5916:     }
1.800     albertel 5917:     close(OUT);
1.574     banghart 5918:     return (@return_files);
1.572     banghart 5919: }
                   5920: 
1.745     raeburn  5921: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5922: 
1.745     raeburn  5923: sub get_portfile_permissions {
                   5924:     my ($domain,$user) = @_;
1.613     albertel 5925:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5926:     my ($tmp)=keys(%current_permissions);
                   5927:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5928:     return \%current_permissions;
                   5929: }
                   5930: 
                   5931: #---------------------------------------------Get portfolio file access controls
                   5932: 
1.749     raeburn  5933: sub get_access_controls {
1.745     raeburn  5934:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5935:     my %access;
                   5936:     my $real_file = $file;
                   5937:     $file =~ s/\.meta$//;
1.745     raeburn  5938:     if (defined($file)) {
1.749     raeburn  5939:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5940:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5941:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5942:             }
                   5943:         }
1.745     raeburn  5944:     } else {
1.749     raeburn  5945:         foreach my $key (keys(%{$current_permissions})) {
                   5946:             if ($key =~ /\0accesscontrol$/) {
                   5947:                 if (defined($group)) {
                   5948:                     if ($key !~ m-^\Q$group\E/-) {
                   5949:                         next;
                   5950:                     }
                   5951:                 }
                   5952:                 my ($fullpath) = split(/\0/,$key);
                   5953:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5954:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5955:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5956:                     }
                   5957:                 }
                   5958:             }
                   5959:         }
                   5960:     }
                   5961:     return %access;
                   5962: }
                   5963: 
                   5964: sub modify_access_controls {
                   5965:     my ($file_name,$changes,$domain,$user)=@_;
                   5966:     my ($outcome,$deloutcome);
                   5967:     my %store_permissions;
                   5968:     my %new_values;
                   5969:     my %new_control;
                   5970:     my %translation;
                   5971:     my @deletions = ();
                   5972:     my $now = time;
                   5973:     if (exists($$changes{'activate'})) {
                   5974:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5975:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5976:             my $numnew = scalar(@newitems);
                   5977:             for (my $i=0; $i<$numnew; $i++) {
                   5978:                 my $newkey = $newitems[$i];
                   5979:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5980:                 if ($newkey =~ /^\d+:/) { 
                   5981:                     $newkey =~ s/^(\d+)/$newid/;
                   5982:                     $translation{$1} = $newid;
                   5983:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5984:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5985:                     $translation{$1} = $newid;
                   5986:                 }
1.749     raeburn  5987:                 $new_values{$file_name."\0".$newkey} = 
                   5988:                                           $$changes{'activate'}{$newitems[$i]};
                   5989:                 $new_control{$newkey} = $now;
                   5990:             }
                   5991:         }
                   5992:     }
                   5993:     my %todelete;
                   5994:     my %changed_items;
                   5995:     foreach my $action ('delete','update') {
                   5996:         if (exists($$changes{$action})) {
                   5997:             if (ref($$changes{$action}) eq 'HASH') {
                   5998:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5999:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6000:                     if ($action eq 'delete') { 
                   6001:                         $todelete{$itemnum} = 1;
                   6002:                     } else {
                   6003:                         $changed_items{$itemnum} = $key;
                   6004:                     }
                   6005:                 }
1.745     raeburn  6006:             }
                   6007:         }
1.749     raeburn  6008:     }
                   6009:     # get lock on access controls for file.
                   6010:     my $lockhash = {
                   6011:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6012:                                                        ':'.$env{'user.domain'},
                   6013:                    }; 
                   6014:     my $tries = 0;
                   6015:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6016:    
                   6017:     while (($gotlock ne 'ok') && $tries <3) {
                   6018:         $tries ++;
                   6019:         sleep 1;
                   6020:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6021:     }
                   6022:     if ($gotlock eq 'ok') {
                   6023:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6024:         my ($tmp)=keys(%curr_permissions);
                   6025:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6026:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6027:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6028:             if (ref($curr_controls) eq 'HASH') {
                   6029:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6030:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6031:                     if (defined($todelete{$itemnum})) {
                   6032:                         push(@deletions,$file_name."\0".$control_item);
                   6033:                     } else {
                   6034:                         if (defined($changed_items{$itemnum})) {
                   6035:                             $new_control{$changed_items{$itemnum}} = $now;
                   6036:                             push(@deletions,$file_name."\0".$control_item);
                   6037:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6038:                         } else {
                   6039:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6040:                         }
                   6041:                     }
1.745     raeburn  6042:                 }
                   6043:             }
                   6044:         }
1.749     raeburn  6045:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6046:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6047:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6048:         #  remove lock
                   6049:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6050:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6051:         my ($file,$group);
                   6052:         if (&is_course($domain,$user)) {
                   6053:             ($group,$file) = split(/\//,$file_name,2);
                   6054:         } else {
                   6055:             $file = $file_name;
                   6056:         }
                   6057:         my $sqlresult =
                   6058:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6059:                                     $group);
1.749     raeburn  6060:     } else {
                   6061:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6062:     }
1.749     raeburn  6063:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6064: }
                   6065: 
1.827     raeburn  6066: sub make_public_indefinitely {
                   6067:     my ($requrl) = @_;
                   6068:     my $now = time;
                   6069:     my $action = 'activate';
                   6070:     my $aclnum = 0;
                   6071:     if (&is_portfolio_url($requrl)) {
                   6072:         my (undef,$udom,$unum,$file_name,$group) =
                   6073:             &parse_portfolio_url($requrl);
                   6074:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6075:         my %access_controls = &get_access_controls($current_perms,
                   6076:                                                    $group,$file_name);
                   6077:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6078:             my ($num,$scope,$end,$start) = 
                   6079:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6080:             if ($scope eq 'public') {
                   6081:                 if ($start <= $now && $end == 0) {
                   6082:                     $action = 'none';
                   6083:                 } else {
                   6084:                     $action = 'update';
                   6085:                     $aclnum = $num;
                   6086:                 }
                   6087:                 last;
                   6088:             }
                   6089:         }
                   6090:         if ($action eq 'none') {
                   6091:              return 'ok';
                   6092:         } else {
                   6093:             my %changes;
                   6094:             my $newend = 0;
                   6095:             my $newstart = $now;
                   6096:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6097:             $changes{$action}{$newkey} = {
                   6098:                 type => 'public',
                   6099:                 time => {
                   6100:                     start => $newstart,
                   6101:                     end   => $newend,
                   6102:                 },
                   6103:             };
                   6104:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6105:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6106:             return $outcome;
                   6107:         }
                   6108:     } else {
                   6109:         return 'invalid';
                   6110:     }
                   6111: }
                   6112: 
1.745     raeburn  6113: #------------------------------------------------------Get Marked as Read Only
                   6114: 
                   6115: sub get_marked_as_readonly {
                   6116:     my ($domain,$user,$what,$group) = @_;
                   6117:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6118:     my @readonly_files;
1.629     banghart 6119:     my $cmp1=$what;
                   6120:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6121:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6122:         if (defined($group)) {
                   6123:             if ($file_name !~ m-^\Q$group\E/-) {
                   6124:                 next;
                   6125:             }
                   6126:         }
1.561     banghart 6127:         if (ref($value) eq "ARRAY"){
                   6128:             foreach my $stored_what (@{$value}) {
1.629     banghart 6129:                 my $cmp2=$stored_what;
1.759     albertel 6130:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6131:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6132:                 }
1.629     banghart 6133:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6134:                     push(@readonly_files, $file_name);
1.745     raeburn  6135:                     last;
1.563     banghart 6136:                 } elsif (!defined($what)) {
                   6137:                     push(@readonly_files, $file_name);
1.745     raeburn  6138:                     last;
1.561     banghart 6139:                 }
                   6140:             }
1.745     raeburn  6141:         }
1.561     banghart 6142:     }
                   6143:     return @readonly_files;
                   6144: }
1.577     banghart 6145: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6146: 
1.577     banghart 6147: sub get_marked_as_readonly_hash {
1.745     raeburn  6148:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6149:     my %readonly_files;
1.745     raeburn  6150:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6151:         if (defined($group)) {
                   6152:             if ($file_name !~ m-^\Q$group\E/-) {
                   6153:                 next;
                   6154:             }
                   6155:         }
1.577     banghart 6156:         if (ref($value) eq "ARRAY"){
                   6157:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6158:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6159:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6160:                         if ($lock_descriptor eq 'graded') {
                   6161:                             $readonly_files{$file_name} = 'graded';
                   6162:                         } elsif ($lock_descriptor eq 'handback') {
                   6163:                             $readonly_files{$file_name} = 'handback';
                   6164:                         } else {
                   6165:                             if (!exists($readonly_files{$file_name})) {
                   6166:                                 $readonly_files{$file_name} = 'locked';
                   6167:                             }
                   6168:                         }
1.745     raeburn  6169:                     }
1.750     banghart 6170:                 } 
1.577     banghart 6171:             }
                   6172:         } 
                   6173:     }
                   6174:     return %readonly_files;
                   6175: }
1.559     banghart 6176: # ------------------------------------------------------------ Unmark as Read Only
                   6177: 
                   6178: sub unmark_as_readonly {
1.629     banghart 6179:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6180:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6181:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6182:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6183:     my $symb_crs = $what;
                   6184:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6185:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6186:     my ($tmp)=keys(%current_permissions);
                   6187:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6188:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6189:     foreach my $file (@readonly_files) {
1.759     albertel 6190: 	my $clean_file = &declutter_portfile($file);
                   6191: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6192: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6193:         my @new_locks;
                   6194:         my @del_keys;
                   6195:         if (ref($current_locks) eq "ARRAY"){
                   6196:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6197:                 my $compare=$locker;
1.749     raeburn  6198:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6199:                     $compare=join('',@{$locker});
1.746     raeburn  6200:                     if ($compare ne $symb_crs) {
                   6201:                         push(@new_locks, $locker);
                   6202:                     }
1.563     banghart 6203:                 }
                   6204:             }
1.650     albertel 6205:             if (scalar(@new_locks) > 0) {
1.563     banghart 6206:                 $current_permissions{$file} = \@new_locks;
                   6207:             } else {
                   6208:                 push(@del_keys, $file);
1.613     albertel 6209:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6210:                 delete($current_permissions{$file});
1.563     banghart 6211:             }
                   6212:         }
1.561     banghart 6213:     }
1.613     albertel 6214:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6215:     return;
                   6216: }
1.512     banghart 6217: 
1.17      www      6218: # ------------------------------------------------------------ Directory lister
                   6219: 
                   6220: sub dirlist {
1.253     stredwic 6221:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6222: 
1.18      www      6223:     $uri=~s/^\///;
                   6224:     $uri=~s/\/$//;
1.253     stredwic 6225:     my ($udom, $uname);
                   6226:     (undef,$udom,$uname)=split(/\//,$uri);
                   6227:     if(defined($userdomain)) {
                   6228:         $udom = $userdomain;
                   6229:     }
                   6230:     if(defined($username)) {
                   6231:         $uname = $username;
                   6232:     }
                   6233: 
                   6234:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6235:     if(defined($alternateDirectoryRoot)) {
                   6236:         $dirRoot = $alternateDirectoryRoot;
                   6237:         $dirRoot =~ s/\/$//;
1.751     banghart 6238:     }
1.253     stredwic 6239: 
                   6240:     if($udom) {
                   6241:         if($uname) {
1.800     albertel 6242:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6243: 				 &homeserver($uname,$udom));
1.605     matthew  6244:             my @listing_results;
                   6245:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6246:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6247: 				  &homeserver($uname,$udom));
1.605     matthew  6248:                 @listing_results = split(/:/,$listing);
                   6249:             } else {
                   6250:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6251:             }
                   6252:             return @listing_results;
1.253     stredwic 6253:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6254:             my %allusers;
1.841     albertel 6255: 	    my %servers = &get_servers($udom,'library');
                   6256: 	    foreach my $tryserver (keys(%servers)) {
                   6257: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6258: 				     $udom, $tryserver);
                   6259: 		my @listing_results;
                   6260: 		if ($listing eq 'unknown_cmd') {
                   6261: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6262: 				      $udom, $tryserver);
                   6263: 		    @listing_results = split(/:/,$listing);
                   6264: 		} else {
                   6265: 		    @listing_results =
                   6266: 			map { &unescape($_); } split(/:/,$listing);
                   6267: 		}
                   6268: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6269: 		    $listing_results[0] ne 'empty'       &&
                   6270: 		    $listing_results[0] ne 'con_lost') {
                   6271: 		    foreach my $line (@listing_results) {
                   6272: 			my ($entry) = split(/&/,$line,2);
                   6273: 			$allusers{$entry} = 1;
                   6274: 		    }
                   6275: 		}
1.253     stredwic 6276:             }
                   6277:             my $alluserstr='';
1.800     albertel 6278:             foreach my $user (sort(keys(%allusers))) {
                   6279:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6280:             }
                   6281:             $alluserstr=~s/:$//;
                   6282:             return split(/:/,$alluserstr);
                   6283:         } else {
1.800     albertel 6284:             return ('missing user name');
1.253     stredwic 6285:         }
                   6286:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6287:         my @all_domains = sort(&all_domains());
                   6288:          foreach my $domain (@all_domains) {
                   6289:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6290:          }
                   6291:          return @all_domains;
                   6292:      } else {
1.800     albertel 6293:         return ('missing domain');
1.275     stredwic 6294:     }
                   6295: }
                   6296: 
                   6297: # --------------------------------------------- GetFileTimestamp
                   6298: # This function utilizes dirlist and returns the date stamp for
                   6299: # when it was last modified.  It will also return an error of -1
                   6300: # if an error occurs
                   6301: 
1.410     matthew  6302: ##
                   6303: ## FIXME: This subroutine assumes its caller knows something about the
                   6304: ## directory structure of the home server for the student ($root).
                   6305: ## Not a good assumption to make.  Since this is for looking up files
                   6306: ## in user directories, the full path should be constructed by lond, not
                   6307: ## whatever machine we request data from.
                   6308: ##
1.275     stredwic 6309: sub GetFileTimestamp {
                   6310:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6311:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6312:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6313:     my $subdir=$studentName.'__';
                   6314:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6315:     my $proname="$studentDomain/$subdir/$studentName";
                   6316:     $proname .= '/'.$filename;
1.375     matthew  6317:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6318:                                               $studentName, $root);
1.275     stredwic 6319:     my @stats = split('&', $fileStat);
                   6320:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6321:         # @stats contains first the filename, then the stat output
                   6322:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6323:     } else {
                   6324:         return -1;
1.253     stredwic 6325:     }
1.26      www      6326: }
                   6327: 
1.712     albertel 6328: sub stat_file {
                   6329:     my ($uri) = @_;
1.787     albertel 6330:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6331: 
1.712     albertel 6332:     my ($udom,$uname,$file,$dir);
                   6333:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6334: 	($udom,$uname,$file) =
1.811     albertel 6335: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6336: 	$file = 'userfiles/'.$file;
1.740     www      6337: 	$dir = &propath($udom,$uname);
1.712     albertel 6338:     }
                   6339:     if ($uri =~ m-^/res/-) {
                   6340: 	($udom,$uname) = 
1.807     albertel 6341: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6342: 	$file = $uri;
                   6343:     }
                   6344: 
                   6345:     if (!$udom || !$uname || !$file) {
                   6346: 	# unable to handle the uri
                   6347: 	return ();
                   6348:     }
                   6349: 
                   6350:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6351:     my @stats = split('&', $result);
1.721     banghart 6352:     
1.712     albertel 6353:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6354: 	shift(@stats); #filename is first
                   6355: 	return @stats;
                   6356:     }
                   6357:     return ();
                   6358: }
                   6359: 
1.26      www      6360: # -------------------------------------------------------- Value of a Condition
                   6361: 
1.713     albertel 6362: # gets the value of a specific preevaluated condition
                   6363: #    stored in the string  $env{user.state.<cid>}
                   6364: # or looks up a condition reference in the bighash and if if hasn't
                   6365: # already been evaluated recurses into docondval to get the value of
                   6366: # the condition, then memoizing it to 
                   6367: #   $env{user.state.<cid>.<condition>}
1.40      www      6368: sub directcondval {
                   6369:     my $number=shift;
1.620     albertel 6370:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6371: 	&Apache::lonuserstate::evalstate();
                   6372:     }
1.713     albertel 6373:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6374: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6375:     } elsif ($number =~ /^_/) {
                   6376: 	my $sub_condition;
                   6377: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6378: 		&GDBM_READER(),0640)) {
                   6379: 	    $sub_condition=$bighash{'conditions'.$number};
                   6380: 	    untie(%bighash);
                   6381: 	}
                   6382: 	my $value = &docondval($sub_condition);
1.949     raeburn  6383: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6384: 	return $value;
                   6385:     }
1.620     albertel 6386:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6387:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6388:     } else {
                   6389:        return 2;
                   6390:     }
                   6391: }
                   6392: 
1.713     albertel 6393: # get the collection of conditions for this resource
1.26      www      6394: sub condval {
                   6395:     my $condidx=shift;
1.54      www      6396:     my $allpathcond='';
1.713     albertel 6397:     foreach my $cond (split(/\|/,$condidx)) {
                   6398: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6399: 	    $allpathcond.=
                   6400: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6401: 	}
1.191     harris41 6402:     }
1.54      www      6403:     $allpathcond=~s/\|$//;
1.713     albertel 6404:     return &docondval($allpathcond);
                   6405: }
                   6406: 
                   6407: #evaluates an expression of conditions
                   6408: sub docondval {
                   6409:     my ($allpathcond) = @_;
                   6410:     my $result=0;
                   6411:     if ($env{'request.course.id'}
                   6412: 	&& defined($allpathcond)) {
                   6413: 	my $operand='|';
                   6414: 	my @stack;
                   6415: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6416: 	    if ($chunk eq '(') {
                   6417: 		push @stack,($operand,$result);
                   6418: 	    } elsif ($chunk eq ')') {
                   6419: 		my $before=pop @stack;
                   6420: 		if (pop @stack eq '&') {
                   6421: 		    $result=$result>$before?$before:$result;
                   6422: 		} else {
                   6423: 		    $result=$result>$before?$result:$before;
                   6424: 		}
                   6425: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6426: 		$operand=$chunk;
                   6427: 	    } else {
                   6428: 		my $new=directcondval($chunk);
                   6429: 		if ($operand eq '&') {
                   6430: 		    $result=$result>$new?$new:$result;
                   6431: 		} else {
                   6432: 		    $result=$result>$new?$result:$new;
                   6433: 		}
                   6434: 	    }
                   6435: 	}
1.26      www      6436:     }
                   6437:     return $result;
1.421     albertel 6438: }
                   6439: 
                   6440: # ---------------------------------------------------- Devalidate courseresdata
                   6441: 
                   6442: sub devalidatecourseresdata {
                   6443:     my ($coursenum,$coursedomain)=@_;
                   6444:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6445:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6446: }
                   6447: 
1.763     www      6448: 
1.200     www      6449: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6450: #
                   6451: #  Parameters:
                   6452: #      $coursenum    - Number of the course.
                   6453: #      $coursedomain - Domain at which the course was created.
                   6454: #  Returns:
                   6455: #     A hash of the course parameters along (I think) with timestamps
                   6456: #     and version info.
1.877     foxr     6457: 
1.624     albertel 6458: sub get_courseresdata {
                   6459:     my ($coursenum,$coursedomain)=@_;
1.200     www      6460:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6461:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6462:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6463:     my %dumpreply;
1.417     albertel 6464:     unless (defined($cached)) {
1.624     albertel 6465: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6466: 	$result=\%dumpreply;
1.251     albertel 6467: 	my ($tmp) = keys(%dumpreply);
                   6468: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6469: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6470: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6471: 	    return $tmp;
1.416     albertel 6472: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6473: 	    $result=undef;
1.599     albertel 6474: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6475: 	}
                   6476:     }
1.624     albertel 6477:     return $result;
                   6478: }
                   6479: 
1.633     albertel 6480: sub devalidateuserresdata {
                   6481:     my ($uname,$udom)=@_;
                   6482:     my $hashid="$udom:$uname";
                   6483:     &devalidate_cache_new('userres',$hashid);
                   6484: }
                   6485: 
1.624     albertel 6486: sub get_userresdata {
                   6487:     my ($uname,$udom)=@_;
                   6488:     #most student don\'t have any data set, check if there is some data
                   6489:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6490: 
                   6491:     my $hashid="$udom:$uname";
                   6492:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6493:     if (!defined($cached)) {
                   6494: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6495: 	$result=\%resourcedata;
                   6496: 	&do_cache_new('userres',$hashid,$result,600);
                   6497:     }
                   6498:     my ($tmp)=keys(%$result);
                   6499:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6500: 	return $result;
                   6501:     }
                   6502:     #error 2 occurs when the .db doesn't exist
                   6503:     if ($tmp!~/error: 2 /) {
1.672     albertel 6504: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6505: 		 " Trying to get resource data for ".
                   6506: 		 $uname." at ".$udom.": ".
                   6507: 		 $tmp."</font>");
                   6508:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6509: 	#&EXT_cache_set($udom,$uname);
                   6510: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6511: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6512:     }
                   6513:     return $tmp;
                   6514: }
1.879     foxr     6515: #----------------------------------------------- resdata - return resource data
                   6516: #  Purpose:
                   6517: #    Return resource data for either users or for a course.
                   6518: #  Parameters:
                   6519: #     $name      - Course/user name.
                   6520: #     $domain    - Name of the domain the user/course is registered on.
                   6521: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6522: #     @which     - Array of names of resources desired.
                   6523: #  Returns:
                   6524: #     The value of the first reasource in @which that is found in the
                   6525: #     resource hash.
                   6526: #  Exceptional Conditions:
                   6527: #     If the $type passed in is not valid (not the string 'course' or 
                   6528: #     'user', an undefined  reference is returned.
                   6529: #     If none of the resources are found, an undef is returned
1.624     albertel 6530: sub resdata {
                   6531:     my ($name,$domain,$type,@which)=@_;
                   6532:     my $result;
                   6533:     if ($type eq 'course') {
                   6534: 	$result=&get_courseresdata($name,$domain);
                   6535:     } elsif ($type eq 'user') {
                   6536: 	$result=&get_userresdata($name,$domain);
                   6537:     }
                   6538:     if (!ref($result)) { return $result; }    
1.251     albertel 6539:     foreach my $item (@which) {
1.927     albertel 6540: 	if (defined($result->{$item->[0]})) {
                   6541: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6542: 	}
1.250     albertel 6543:     }
1.291     albertel 6544:     return undef;
1.200     www      6545: }
                   6546: 
1.379     matthew  6547: #
                   6548: # EXT resource caching routines
                   6549: #
                   6550: 
                   6551: sub clear_EXT_cache_status {
1.383     albertel 6552:     &delenv('cache.EXT.');
1.379     matthew  6553: }
                   6554: 
                   6555: sub EXT_cache_status {
                   6556:     my ($target_domain,$target_user) = @_;
1.383     albertel 6557:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6558:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6559:         # We know already the user has no data
                   6560:         return 1;
                   6561:     } else {
                   6562:         return 0;
                   6563:     }
                   6564: }
                   6565: 
                   6566: sub EXT_cache_set {
                   6567:     my ($target_domain,$target_user) = @_;
1.383     albertel 6568:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6569:     #&appenv({$cachename => time});
1.379     matthew  6570: }
                   6571: 
1.28      www      6572: # --------------------------------------------------------- Value of a Variable
1.58      www      6573: sub EXT {
1.715     albertel 6574: 
1.395     albertel 6575:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6576:     unless ($varname) { return ''; }
1.218     albertel 6577:     #get real user name/domain, courseid and symb
                   6578:     my $courseid;
1.359     albertel 6579:     my $publicuser;
1.427     www      6580:     if ($symbparm) {
                   6581: 	$symbparm=&get_symb_from_alias($symbparm);
                   6582:     }
1.218     albertel 6583:     if (!($uname && $udom)) {
1.790     albertel 6584:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6585:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6586:     } else {
1.620     albertel 6587: 	$courseid=$env{'request.course.id'};
1.218     albertel 6588:     }
1.48      www      6589:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6590:     my $rest;
1.320     albertel 6591:     if (defined($therest[0])) {
1.48      www      6592:        $rest=join('.',@therest);
                   6593:     } else {
                   6594:        $rest='';
                   6595:     }
1.320     albertel 6596: 
1.57      www      6597:     my $qualifierrest=$qualifier;
                   6598:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6599:     my $spacequalifierrest=$space;
                   6600:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6601:     if ($realm eq 'user') {
1.48      www      6602: # --------------------------------------------------------------- user.resource
                   6603: 	if ($space eq 'resource') {
1.651     albertel 6604: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6605: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6606: 		 &&
1.744     albertel 6607: 		 ($symbparm eq &symbread()) ) {	
                   6608: 		# if we are in the middle of processing the resource the
                   6609: 		# get the value we are planning on committing
                   6610:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6611:                     return $Apache::lonhomework::results{$qualifierrest};
                   6612:                 } else {
                   6613:                     return $Apache::lonhomework::history{$qualifierrest};
                   6614:                 }
1.335     albertel 6615: 	    } else {
1.359     albertel 6616: 		my %restored;
1.620     albertel 6617: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6618: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6619: 		} else {
                   6620: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6621: 		}
1.335     albertel 6622: 		return $restored{$qualifierrest};
                   6623: 	    }
1.48      www      6624: # ----------------------------------------------------------------- user.access
                   6625:         } elsif ($space eq 'access') {
1.218     albertel 6626: 	    # FIXME - not supporting calls for a specific user
1.48      www      6627:             return &allowed($qualifier,$rest);
                   6628: # ------------------------------------------ user.preferences, user.environment
                   6629:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6630: 	    if (($uname eq $env{'user.name'}) &&
                   6631: 		($udom eq $env{'user.domain'})) {
                   6632: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6633: 	    } else {
1.359     albertel 6634: 		my %returnhash;
                   6635: 		if (!$publicuser) {
                   6636: 		    %returnhash=&userenvironment($udom,$uname,
                   6637: 						 $qualifierrest);
                   6638: 		}
1.218     albertel 6639: 		return $returnhash{$qualifierrest};
                   6640: 	    }
1.48      www      6641: # ----------------------------------------------------------------- user.course
                   6642:         } elsif ($space eq 'course') {
1.218     albertel 6643: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6644:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6645: # ------------------------------------------------------------------- user.role
                   6646:         } elsif ($space eq 'role') {
1.218     albertel 6647: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6648:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6649:             if ($qualifier eq 'value') {
                   6650: 		return $role;
                   6651:             } elsif ($qualifier eq 'extent') {
                   6652:                 return $where;
                   6653:             }
                   6654: # ----------------------------------------------------------------- user.domain
                   6655:         } elsif ($space eq 'domain') {
1.218     albertel 6656:             return $udom;
1.48      www      6657: # ------------------------------------------------------------------- user.name
                   6658:         } elsif ($space eq 'name') {
1.218     albertel 6659:             return $uname;
1.48      www      6660: # ---------------------------------------------------- Any other user namespace
1.29      www      6661:         } else {
1.359     albertel 6662: 	    my %reply;
                   6663: 	    if (!$publicuser) {
                   6664: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6665: 	    }
                   6666: 	    return $reply{$qualifierrest};
1.48      www      6667:         }
1.236     www      6668:     } elsif ($realm eq 'query') {
                   6669: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6670:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6671: 						[$spacequalifierrest]);
1.620     albertel 6672: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6673:    } elsif ($realm eq 'request') {
1.48      www      6674: # ------------------------------------------------------------- request.browser
                   6675:         if ($space eq 'browser') {
1.430     www      6676: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6677: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6678: 		    return 1;
                   6679: 		} else {
                   6680: 		    return 0;
                   6681: 		}
                   6682: 	    } else {
1.620     albertel 6683: 		return $env{'browser.'.$qualifier};
1.430     www      6684: 	    }
1.57      www      6685: # ------------------------------------------------------------ request.filename
                   6686:         } else {
1.620     albertel 6687:             return $env{'request.'.$spacequalifierrest};
1.29      www      6688:         }
1.28      www      6689:     } elsif ($realm eq 'course') {
1.48      www      6690: # ---------------------------------------------------------- course.description
1.620     albertel 6691:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6692:     } elsif ($realm eq 'resource') {
1.165     www      6693: 
1.620     albertel 6694: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6695: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6696: 	}
1.693     albertel 6697: 
                   6698: 	if ($space eq 'title') {
                   6699: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6700: 	    return &gettitle($symbparm);
                   6701: 	}
                   6702: 	
                   6703: 	if ($space eq 'map') {
                   6704: 	    my ($map) = &decode_symb($symbparm);
                   6705: 	    return &symbread($map);
                   6706: 	}
1.905     albertel 6707: 	if ($space eq 'filename') {
                   6708: 	    if ($symbparm) {
                   6709: 		return &clutter((&decode_symb($symbparm))[2]);
                   6710: 	    }
                   6711: 	    return &hreflocation('',$env{'request.filename'});
                   6712: 	}
1.693     albertel 6713: 
                   6714: 	my ($section, $group, @groups);
1.593     albertel 6715: 	my ($courselevelm,$courselevel);
1.539     albertel 6716: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6717: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6718: 
1.218     albertel 6719: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6720: 
1.60      www      6721: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6722: 	    my $symbp=$symbparm;
1.735     albertel 6723: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6724: 
                   6725: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6726: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6727: 
1.620     albertel 6728: 	    if (($env{'user.name'} eq $uname) &&
                   6729: 		($env{'user.domain'} eq $udom)) {
                   6730: 		$section=$env{'request.course.sec'};
1.733     raeburn  6731:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6732:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6733: 	    } else {
1.539     albertel 6734: 		if (! defined($usection)) {
1.551     albertel 6735: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6736: 		} else {
                   6737: 		    $section = $usection;
                   6738: 		}
1.733     raeburn  6739:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6740: 	    }
                   6741: 
                   6742: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6743: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6744: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6745: 
1.593     albertel 6746: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6747: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6748: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6749: 
1.60      www      6750: # ----------------------------------------------------------- first, check user
1.624     albertel 6751: 
                   6752: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6753: 				       ([$courselevelr,'resource'],
                   6754: 					[$courselevelm,'map'     ],
                   6755: 					[$courselevel, 'course'  ]));
1.931     albertel 6756: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6757: 
1.594     albertel 6758: # ------------------------------------------------ second, check some of course
1.684     raeburn  6759:             my $coursereply;
1.691     raeburn  6760:             if (@groups > 0) {
                   6761:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6762:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6763:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6764:             }
1.96      www      6765: 
1.684     raeburn  6766: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6767: 				  $env{'course.'.$courseid.'.domain'},
                   6768: 				  'course',
                   6769: 				  ([$seclevelr,   'resource'],
                   6770: 				   [$seclevelm,   'map'     ],
                   6771: 				   [$seclevel,    'course'  ],
                   6772: 				   [$courselevelr,'resource']));
                   6773: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6774: 
1.60      www      6775: # ------------------------------------------------------ third, check map parms
1.218     albertel 6776: 	    my %parmhash=();
                   6777: 	    my $thisparm='';
                   6778: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6779: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6780: 		    &GDBM_READER(),0640)) {
1.218     albertel 6781: 		$thisparm=$parmhash{$symbparm};
                   6782: 		untie(%parmhash);
                   6783: 	    }
1.927     albertel 6784: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6785: 	}
1.594     albertel 6786: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6787: 
1.218     albertel 6788: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6789: 	my $filename;
                   6790: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6791: 	if ($symbparm) {
1.409     www      6792: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6793: 	} else {
1.620     albertel 6794: 	    $filename=$env{'request.filename'};
1.282     albertel 6795: 	}
                   6796: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6797: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6798: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6799: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6800: 
1.927     albertel 6801: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6802: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6803: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6804: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6805: 				     $env{'course.'.$courseid.'.domain'},
                   6806: 				     'course',
1.927     albertel 6807: 				     ([$courselevelm,'map'   ],
                   6808: 				      [$courselevel, 'course']));
                   6809: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6810: 	}
1.145     www      6811: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6812: 	unless ($space eq '0') {
1.336     albertel 6813: 	    my @parts=split(/_/,$space);
                   6814: 	    my $id=pop(@parts);
                   6815: 	    my $part=join('_',@parts);
                   6816: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6817: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6818: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6819: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6820: 	}
1.395     albertel 6821: 	if ($recurse) { return undef; }
                   6822: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6823: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6824: # ---------------------------------------------------- Any other user namespace
                   6825:     } elsif ($realm eq 'environment') {
                   6826: # ----------------------------------------------------------------- environment
1.620     albertel 6827: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6828: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6829: 	} else {
1.770     albertel 6830: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6831: 		return '';
                   6832: 	    }
1.219     albertel 6833: 	    my %returnhash=&userenvironment($udom,$uname,
                   6834: 					    $spacequalifierrest);
                   6835: 	    return $returnhash{$spacequalifierrest};
                   6836: 	}
1.28      www      6837:     } elsif ($realm eq 'system') {
1.48      www      6838: # ----------------------------------------------------------------- system.time
                   6839: 	if ($space eq 'time') {
                   6840: 	    return time;
                   6841:         }
1.696     albertel 6842:     } elsif ($realm eq 'server') {
                   6843: # ----------------------------------------------------------------- system.time
                   6844: 	if ($space eq 'name') {
                   6845: 	    return $ENV{'SERVER_NAME'};
                   6846:         }
1.28      www      6847:     }
1.48      www      6848:     return '';
1.61      www      6849: }
                   6850: 
1.927     albertel 6851: sub get_reply {
                   6852:     my ($reply_value) = @_;
1.940     raeburn  6853:     if (ref($reply_value) eq 'ARRAY') {
                   6854:         if (wantarray) {
                   6855: 	    return @$reply_value;
                   6856:         }
                   6857:         return $reply_value->[0];
                   6858:     } else {
                   6859:         return $reply_value;
1.927     albertel 6860:     }
                   6861: }
                   6862: 
1.691     raeburn  6863: sub check_group_parms {
                   6864:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6865:     my @groupitems = ();
                   6866:     my $resultitem;
1.927     albertel 6867:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6868:     foreach my $group (@{$groups}) {
                   6869:         foreach my $level (@levels) {
1.927     albertel 6870:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6871:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6872:         }
                   6873:     }
                   6874:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6875:                             $env{'course.'.$courseid.'.domain'},
                   6876:                                      'course',@groupitems);
                   6877:     return $coursereply;
                   6878: }
                   6879: 
                   6880: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6881:     my ($courseid,@groups) = @_;
                   6882:     @groups = sort(@groups);
1.691     raeburn  6883:     return @groups;
                   6884: }
                   6885: 
1.395     albertel 6886: sub packages_tab_default {
                   6887:     my ($uri,$varname)=@_;
                   6888:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6889: 
                   6890:     my (@extension,@specifics,$do_default);
                   6891:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6892: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6893: 	if ($pack_type eq 'default') {
                   6894: 	    $do_default=1;
                   6895: 	} elsif ($pack_type eq 'extension') {
                   6896: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6897: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6898: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6899: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6900: 	}
                   6901:     }
                   6902:     # first look for a package that matches the requested part id
                   6903:     foreach my $package (@specifics) {
                   6904: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6905: 	next if ($pack_part ne $part);
                   6906: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6907: 	    return $packagetab{"$pack_type&$name&default"};
                   6908: 	}
                   6909:     }
                   6910:     # look for any possible matching non extension_ package
                   6911:     foreach my $package (@specifics) {
                   6912: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6913: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6914: 	    return $packagetab{"$pack_type&$name&default"};
                   6915: 	}
1.585     albertel 6916: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6917: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6918: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6919: 	}
                   6920:     }
1.738     albertel 6921:     # look for any posible extension_ match
                   6922:     foreach my $package (@extension) {
                   6923: 	my ($package,$pack_type)=@{$package};
                   6924: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6925: 	    return $packagetab{"$pack_type&$name&default"};
                   6926: 	}
                   6927: 	if (defined($packagetab{$package."&$name&default"})) {
                   6928: 	    return $packagetab{$package."&$name&default"};
                   6929: 	}
                   6930:     }
                   6931:     # look for a global default setting
                   6932:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6933: 	return $packagetab{"default&$name&default"};
                   6934:     }
1.395     albertel 6935:     return undef;
                   6936: }
                   6937: 
1.334     albertel 6938: sub add_prefix_and_part {
                   6939:     my ($prefix,$part)=@_;
                   6940:     my $keyroot;
                   6941:     if (defined($prefix) && $prefix !~ /^__/) {
                   6942: 	# prefix that has a part already
                   6943: 	$keyroot=$prefix;
                   6944:     } elsif (defined($prefix)) {
                   6945: 	# prefix that is missing a part
                   6946: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6947:     } else {
                   6948: 	# no prefix at all
                   6949: 	if (defined($part)) { $keyroot='_'.$part; }
                   6950:     }
                   6951:     return $keyroot;
                   6952: }
                   6953: 
1.71      www      6954: # ---------------------------------------------------------------- Get metadata
                   6955: 
1.599     albertel 6956: my %metaentry;
1.71      www      6957: sub metadata {
1.176     www      6958:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6959:     $uri=&declutter($uri);
1.288     albertel 6960:     # if it is a non metadata possible uri return quickly
1.529     albertel 6961:     if (($uri eq '') || 
                   6962: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6963: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6964:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6965: 	return undef;
                   6966:     }
                   6967:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6968: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6969: 	return undef;
1.288     albertel 6970:     }
1.73      www      6971:     my $filename=$uri;
                   6972:     $uri=~s/\.meta$//;
1.172     www      6973: #
                   6974: # Is the metadata already cached?
1.177     www      6975: # Look at timestamp of caching
1.172     www      6976: # Everything is cached by the main uri, libraries are never directly cached
                   6977: #
1.428     albertel 6978:     if (!defined($liburi)) {
1.599     albertel 6979: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6980: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6981:     }
                   6982:     {
1.172     www      6983: #
                   6984: # Is this a recursive call for a library?
                   6985: #
1.599     albertel 6986: #	if (! exists($metacache{$uri})) {
                   6987: #	    $metacache{$uri}={};
                   6988: #	}
1.924     albertel 6989: 	my $cachetime = 60*60;
1.171     www      6990:         if ($liburi) {
                   6991: 	    $liburi=&declutter($liburi);
                   6992:             $filename=$liburi;
1.401     bowersj2 6993:         } else {
1.599     albertel 6994: 	    &devalidate_cache_new('meta',$uri);
                   6995: 	    undef(%metaentry);
1.401     bowersj2 6996: 	}
1.140     www      6997:         my %metathesekeys=();
1.73      www      6998:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6999: 	my $metastring;
1.924     albertel 7000: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7001: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7002: 	    $metastring = 
1.929     albertel 7003: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7004: 					  ('grade_target' => 'meta'));
                   7005: 	    $cachetime = 1; # only want this cached in the child not long term
                   7006: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7007: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7008: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7009: 	    $metastring=&getfile($file);
1.489     albertel 7010: 	}
1.208     albertel 7011:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7012:         my $token;
1.140     www      7013:         undef %metathesekeys;
1.71      www      7014:         while ($token=$parser->get_token) {
1.339     albertel 7015: 	    if ($token->[0] eq 'S') {
                   7016: 		if (defined($token->[2]->{'package'})) {
1.172     www      7017: #
                   7018: # This is a package - get package info
                   7019: #
1.339     albertel 7020: 		    my $package=$token->[2]->{'package'};
                   7021: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7022: 		    if (defined($token->[2]->{'id'})) { 
                   7023: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7024: 		    }
1.599     albertel 7025: 		    if ($metaentry{':packages'}) {
                   7026: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7027: 		    } else {
1.599     albertel 7028: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7029: 		    }
1.736     albertel 7030: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7031: 			my $part=$keyroot;
                   7032: 			$part=~s/^\_//;
1.736     albertel 7033: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7034: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7035: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7036: 			    # ignore package.tab specified default values
                   7037:                             # here &package_tab_default() will fetch those
                   7038: 			    if ($subp eq 'default') { next; }
1.736     albertel 7039: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7040: 			    my $unikey;
                   7041: 			    if ($pack =~ /_0$/) {
                   7042: 				$unikey='parameter_0_'.$name;
                   7043: 				$part=0;
                   7044: 			    } else {
                   7045: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7046: 			    }
1.339     albertel 7047: 			    if ($subp eq 'display') {
                   7048: 				$value.=' [Part: '.$part.']';
                   7049: 			    }
1.599     albertel 7050: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7051: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7052: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7053: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7054: 			    }
1.599     albertel 7055: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7056: 				$metaentry{':'.$unikey}=
                   7057: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7058: 			    }
1.339     albertel 7059: 			}
                   7060: 		    }
                   7061: 		} else {
1.172     www      7062: #
                   7063: # This is not a package - some other kind of start tag
1.339     albertel 7064: #
                   7065: 		    my $entry=$token->[1];
                   7066: 		    my $unikey;
                   7067: 		    if ($entry eq 'import') {
                   7068: 			$unikey='';
                   7069: 		    } else {
                   7070: 			$unikey=$entry;
                   7071: 		    }
                   7072: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7073: 
                   7074: 		    if (defined($token->[2]->{'id'})) { 
                   7075: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7076: 		    }
1.175     www      7077: 
1.339     albertel 7078: 		    if ($entry eq 'import') {
1.175     www      7079: #
                   7080: # Importing a library here
1.339     albertel 7081: #
                   7082: 			if ($depthcount<20) {
                   7083: 			    my $location=$parser->get_text('/import');
                   7084: 			    my $dir=$filename;
                   7085: 			    $dir=~s|[^/]*$||;
                   7086: 			    $location=&filelocation($dir,$location);
1.736     albertel 7087: 			    my $metadata = 
                   7088: 				&metadata($uri,'keys', $location,$unikey,
                   7089: 					  $depthcount+1);
                   7090: 			    foreach my $meta (split(',',$metadata)) {
                   7091: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7092: 				$metathesekeys{$meta}=1;
1.339     albertel 7093: 			    }
                   7094: 			}
                   7095: 		    } else { 
                   7096: 			
                   7097: 			if (defined($token->[2]->{'name'})) { 
                   7098: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7099: 			}
                   7100: 			$metathesekeys{$unikey}=1;
1.736     albertel 7101: 			foreach my $param (@{$token->[3]}) {
                   7102: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7103: 				$token->[2]->{$param};
1.339     albertel 7104: 			}
                   7105: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7106: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7107: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7108: 		 # only ws inside the tag, and not in default, so use default
                   7109: 		 # as value
1.599     albertel 7110: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7111: 			} elsif ( $internaltext =~ /\S/ ) {
                   7112: 		  # something interesting inside the tag
                   7113: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7114: 			} else {
1.908     albertel 7115: 		  # no interesting values, don't set a default
1.339     albertel 7116: 			}
1.172     www      7117: # end of not-a-package not-a-library import
1.339     albertel 7118: 		    }
1.172     www      7119: # end of not-a-package start tag
1.339     albertel 7120: 		}
1.172     www      7121: # the next is the end of "start tag"
1.339     albertel 7122: 	    }
                   7123: 	}
1.483     albertel 7124: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7125: 	$extension = lc($extension);
                   7126: 	if ($extension eq 'htm') { $extension='html'; }
                   7127: 
1.737     albertel 7128: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7129: 	    #no specific packages #how's our extension
                   7130: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7131: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7132: 					 \%metathesekeys);
                   7133: 	}
1.883     albertel 7134: 
                   7135: 	if (!exists($metaentry{':packages'})
                   7136: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7137: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7138: 		#no specific packages well let's get default then
                   7139: 		if ($key!~/^default&/) { next; }
1.488     albertel 7140: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7141: 					     \%metathesekeys);
                   7142: 	    }
                   7143: 	}
1.338     www      7144: # are there custom rights to evaluate
1.599     albertel 7145: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7146: 
1.338     www      7147:     #
                   7148:     # Importing a rights file here
1.339     albertel 7149:     #
                   7150: 	    unless ($depthcount) {
1.599     albertel 7151: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7152: 		my $dir=$filename;
                   7153: 		$dir=~s|[^/]*$||;
                   7154: 		$location=&filelocation($dir,$location);
1.736     albertel 7155: 		my $rights_metadata =
                   7156: 		    &metadata($uri,'keys',$location,'_rights',
                   7157: 			      $depthcount+1);
                   7158: 		foreach my $rights (split(',',$rights_metadata)) {
                   7159: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7160: 		    $metathesekeys{$rights}=1;
1.339     albertel 7161: 		}
                   7162: 	    }
                   7163: 	}
1.737     albertel 7164: 	# uniqifiy package listing
                   7165: 	my %seen;
                   7166: 	my @uniq_packages =
                   7167: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7168: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7169: 
                   7170: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7171: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7172: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7173: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7174: # this is the end of "was not already recently cached
1.71      www      7175:     }
1.599     albertel 7176:     return $metaentry{':'.$what};
1.261     albertel 7177: }
                   7178: 
1.488     albertel 7179: sub metadata_create_package_def {
1.483     albertel 7180:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7181:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7182:     if ($subp eq 'default') { next; }
                   7183:     
1.599     albertel 7184:     if (defined($metaentry{':packages'})) {
                   7185: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7186:     } else {
1.599     albertel 7187: 	$metaentry{':packages'}=$package;
1.483     albertel 7188:     }
                   7189:     my $value=$packagetab{$key};
                   7190:     my $unikey;
                   7191:     $unikey='parameter_0_'.$name;
1.599     albertel 7192:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7193:     $$metathesekeys{$unikey}=1;
1.599     albertel 7194:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7195: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7196:     }
1.599     albertel 7197:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7198: 	$metaentry{':'.$unikey}=
                   7199: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7200:     }
                   7201: }
                   7202: 
1.261     albertel 7203: sub metadata_generate_part0 {
                   7204:     my ($metadata,$metacache,$uri) = @_;
                   7205:     my %allnames;
1.737     albertel 7206:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7207: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7208: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7209: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7210: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7211: 	    $allnames{$name}=$part;
                   7212: 	  }
                   7213: 	}
                   7214:     }
                   7215:     foreach my $name (keys(%allnames)) {
                   7216:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7217:       my $key=":parameter_0_$name";
1.261     albertel 7218:       $$metacache{"$key.part"}='0';
                   7219:       $$metacache{"$key.name"}=$name;
1.428     albertel 7220:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7221: 					   $allnames{$name}.'_'.$name.
                   7222: 					   '.type'};
1.428     albertel 7223:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7224: 			     '.display'};
1.644     www      7225:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7226:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7227:       $$metacache{"$key.display"}=$olddis;
                   7228:     }
1.71      www      7229: }
                   7230: 
1.764     albertel 7231: # ------------------------------------------------------ Devalidate title cache
                   7232: 
                   7233: sub devalidate_title_cache {
                   7234:     my ($url)=@_;
                   7235:     if (!$env{'request.course.id'}) { return; }
                   7236:     my $symb=&symbread($url);
                   7237:     if (!$symb) { return; }
                   7238:     my $key=$env{'request.course.id'}."\0".$symb;
                   7239:     &devalidate_cache_new('title',$key);
                   7240: }
                   7241: 
1.301     www      7242: # ------------------------------------------------- Get the title of a resource
                   7243: 
                   7244: sub gettitle {
                   7245:     my $urlsymb=shift;
                   7246:     my $symb=&symbread($urlsymb);
1.534     albertel 7247:     if ($symb) {
1.620     albertel 7248: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7249: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7250: 	if (defined($cached)) { 
                   7251: 	    return $result;
                   7252: 	}
1.534     albertel 7253: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7254: 	my $title='';
1.907     albertel 7255: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7256: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7257: 	} else {
                   7258: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7259: 		    &GDBM_READER(),0640)) {
                   7260: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7261: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7262: 		untie(%bighash);
                   7263: 	    }
1.534     albertel 7264: 	}
                   7265: 	$title=~s/\&colon\;/\:/gs;
                   7266: 	if ($title) {
1.599     albertel 7267: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7268: 	}
                   7269: 	$urlsymb=$url;
                   7270:     }
                   7271:     my $title=&metadata($urlsymb,'title');
                   7272:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7273:     return $title;
1.301     www      7274: }
1.613     albertel 7275: 
1.614     albertel 7276: sub get_slot {
                   7277:     my ($which,$cnum,$cdom)=@_;
                   7278:     if (!$cnum || !$cdom) {
1.790     albertel 7279: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7280: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7281: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7282:     }
1.703     albertel 7283:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7284:     my %slotinfo;
                   7285:     if (exists($remembered{$key})) {
                   7286: 	$slotinfo{$which} = $remembered{$key};
                   7287:     } else {
                   7288: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7289: 	&Apache::lonhomework::showhash(%slotinfo);
                   7290: 	my ($tmp)=keys(%slotinfo);
                   7291: 	if ($tmp=~/^error:/) { return (); }
                   7292: 	$remembered{$key} = $slotinfo{$which};
                   7293:     }
1.616     albertel 7294:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7295: 	return %{$slotinfo{$which}};
                   7296:     }
                   7297:     return $slotinfo{$which};
1.614     albertel 7298: }
1.31      www      7299: # ------------------------------------------------- Update symbolic store links
                   7300: 
                   7301: sub symblist {
                   7302:     my ($mapname,%newhash)=@_;
1.438     www      7303:     $mapname=&deversion(&declutter($mapname));
1.31      www      7304:     my %hash;
1.620     albertel 7305:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7306:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7307:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7308: 	    foreach my $url (keys %newhash) {
                   7309: 		next if ($url eq 'last_known'
                   7310: 			 && $env{'form.no_update_last_known'});
                   7311: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7312: 						    $newhash{$url}->[1],
                   7313: 						    $newhash{$url}->[0]);
1.191     harris41 7314:             }
1.31      www      7315:             if (untie(%hash)) {
                   7316: 		return 'ok';
                   7317:             }
                   7318:         }
                   7319:     }
                   7320:     return 'error';
1.212     www      7321: }
                   7322: 
                   7323: # --------------------------------------------------------------- Verify a symb
                   7324: 
                   7325: sub symbverify {
1.510     www      7326:     my ($symb,$thisurl)=@_;
                   7327:     my $thisfn=$thisurl;
1.439     www      7328:     $thisfn=&declutter($thisfn);
1.215     www      7329: # direct jump to resource in page or to a sequence - will construct own symbs
                   7330:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7331: # check URL part
1.409     www      7332:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7333: 
1.431     www      7334:     unless ($url eq $thisfn) { return 0; }
1.213     www      7335: 
1.216     www      7336:     $symb=&symbclean($symb);
1.510     www      7337:     $thisurl=&deversion($thisurl);
1.439     www      7338:     $thisfn=&deversion($thisfn);
1.213     www      7339: 
                   7340:     my %bighash;
                   7341:     my $okay=0;
1.431     www      7342: 
1.620     albertel 7343:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7344:                             &GDBM_READER(),0640)) {
1.510     www      7345:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7346:         unless ($ids) { 
1.510     www      7347:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7348:         }
                   7349:         if ($ids) {
                   7350: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7351: 	    foreach my $id (split(/\,/,$ids)) {
                   7352: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7353:                if (
                   7354:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7355:    eq $symb) { 
1.620     albertel 7356: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7357: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7358: 		       $okay=1; 
                   7359: 		   }
                   7360: 	       }
1.216     www      7361: 	   }
                   7362:         }
1.213     www      7363: 	untie(%bighash);
                   7364:     }
                   7365:     return $okay;
1.31      www      7366: }
                   7367: 
1.210     www      7368: # --------------------------------------------------------------- Clean-up symb
                   7369: 
                   7370: sub symbclean {
                   7371:     my $symb=shift;
1.568     albertel 7372:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7373: # remove version from map
                   7374:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7375: 
1.210     www      7376: # remove version from URL
                   7377:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7378: 
1.507     www      7379: # remove wrapper
                   7380: 
1.510     www      7381:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7382:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7383:     return $symb;
1.409     www      7384: }
                   7385: 
                   7386: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7387: 
                   7388: sub encode_symb {
                   7389:     my ($map,$resid,$url)=@_;
                   7390:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7391: }
1.409     www      7392: 
                   7393: sub decode_symb {
1.568     albertel 7394:     my $symb=shift;
                   7395:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7396:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7397:     return (&fixversion($map),$resid,&fixversion($url));
                   7398: }
                   7399: 
                   7400: sub fixversion {
                   7401:     my $fn=shift;
1.609     banghart 7402:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7403:     my %bighash;
                   7404:     my $uri=&clutter($fn);
1.620     albertel 7405:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7406: # is this cached?
1.599     albertel 7407:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7408:     if (defined($cached)) { return $result; }
                   7409: # unfortunately not cached, or expired
1.620     albertel 7410:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7411: 	    &GDBM_READER(),0640)) {
                   7412:  	if ($bighash{'version_'.$uri}) {
                   7413:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7414:  	    unless (($version eq 'mostrecent') || 
                   7415: 		    ($version==&getversion($uri))) {
1.440     www      7416:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7417:  	    }
                   7418:  	}
                   7419:  	untie %bighash;
1.413     www      7420:     }
1.599     albertel 7421:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7422: }
                   7423: 
                   7424: sub deversion {
                   7425:     my $url=shift;
                   7426:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7427:     return $url;
1.210     www      7428: }
                   7429: 
1.31      www      7430: # ------------------------------------------------------ Return symb list entry
                   7431: 
                   7432: sub symbread {
1.249     www      7433:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7434:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7435:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7436: # no filename provided? try from environment
1.44      www      7437:     unless ($thisfn) {
1.620     albertel 7438:         if ($env{'request.symb'}) {
                   7439: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7440: 	}
1.620     albertel 7441: 	$thisfn=$env{'request.filename'};
1.44      www      7442:     }
1.569     albertel 7443:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7444: # is that filename actually a symb? Verify, clean, and return
                   7445:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7446: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7447: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7448: 	}
1.242     www      7449:     }
1.44      www      7450:     $thisfn=declutter($thisfn);
1.31      www      7451:     my %hash;
1.37      www      7452:     my %bighash;
                   7453:     my $syval='';
1.620     albertel 7454:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7455:         my $targetfn = $thisfn;
1.609     banghart 7456:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7457:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7458:         }
1.687     albertel 7459: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7460: 	    $targetfn=$1;
                   7461: 	}
1.620     albertel 7462:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7463:                       &GDBM_READER(),0640)) {
1.481     raeburn  7464: 	    $syval=$hash{$targetfn};
1.37      www      7465:             untie(%hash);
                   7466:         }
                   7467: # ---------------------------------------------------------- There was an entry
                   7468:         if ($syval) {
1.601     albertel 7469: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7470: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7471: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7472: 		    #return $env{$cache_str}='';
1.601     albertel 7473: 		#}    
                   7474: 		#$syval.=$1;
                   7475: 	    #}
1.37      www      7476:         } else {
                   7477: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7478:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7479:                             &GDBM_READER(),0640)) {
1.37      www      7480: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7481:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7482:               unless ($ids) { 
                   7483:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7484:               }
                   7485:               unless ($ids) {
                   7486: # alias?
                   7487: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7488:               }
1.37      www      7489:               if ($ids) {
                   7490: # ------------------------------------------------------------------- Has ID(s)
                   7491:                  my @possibilities=split(/\,/,$ids);
1.39      www      7492:                  if ($#possibilities==0) {
                   7493: # ----------------------------------------------- There is only one possibility
1.37      www      7494: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7495: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7496: 						    $resid,$thisfn);
1.249     www      7497:                  } elsif (!$donotrecurse) {
1.39      www      7498: # ------------------------------------------ There is more than one possibility
                   7499:                      my $realpossible=0;
1.800     albertel 7500:                      foreach my $id (@possibilities) {
                   7501: 			 my $file=$bighash{'src_'.$id};
1.39      www      7502:                          if (&allowed('bre',$file)) {
1.800     albertel 7503:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7504:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7505: 				$realpossible++;
1.626     albertel 7506:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7507: 						    $resid,$thisfn);
1.39      www      7508:                             }
                   7509: 			 }
1.191     harris41 7510:                      }
1.39      www      7511: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7512:                  } else {
                   7513:                      $syval='';
1.37      www      7514:                  }
                   7515: 	      }
                   7516:               untie(%bighash)
1.481     raeburn  7517:            }
1.31      www      7518:         }
1.62      www      7519:         if ($syval) {
1.620     albertel 7520: 	    return $env{$cache_str}=$syval;
1.62      www      7521:         }
1.31      www      7522:     }
1.949     raeburn  7523:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7524:     return $env{$cache_str}='';
1.31      www      7525: }
                   7526: 
                   7527: # ---------------------------------------------------------- Return random seed
                   7528: 
1.32      www      7529: sub numval {
                   7530:     my $txt=shift;
                   7531:     $txt=~tr/A-J/0-9/;
                   7532:     $txt=~tr/a-j/0-9/;
                   7533:     $txt=~tr/K-T/0-9/;
                   7534:     $txt=~tr/k-t/0-9/;
                   7535:     $txt=~tr/U-Z/0-5/;
                   7536:     $txt=~tr/u-z/0-5/;
                   7537:     $txt=~s/\D//g;
1.564     albertel 7538:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7539:     return int($txt);
1.368     albertel 7540: }
                   7541: 
1.484     albertel 7542: sub numval2 {
                   7543:     my $txt=shift;
                   7544:     $txt=~tr/A-J/0-9/;
                   7545:     $txt=~tr/a-j/0-9/;
                   7546:     $txt=~tr/K-T/0-9/;
                   7547:     $txt=~tr/k-t/0-9/;
                   7548:     $txt=~tr/U-Z/0-5/;
                   7549:     $txt=~tr/u-z/0-5/;
                   7550:     $txt=~s/\D//g;
                   7551:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7552:     my $total;
                   7553:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7554:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7555:     return int($total);
                   7556: }
                   7557: 
1.575     albertel 7558: sub numval3 {
                   7559:     use integer;
                   7560:     my $txt=shift;
                   7561:     $txt=~tr/A-J/0-9/;
                   7562:     $txt=~tr/a-j/0-9/;
                   7563:     $txt=~tr/K-T/0-9/;
                   7564:     $txt=~tr/k-t/0-9/;
                   7565:     $txt=~tr/U-Z/0-5/;
                   7566:     $txt=~tr/u-z/0-5/;
                   7567:     $txt=~s/\D//g;
                   7568:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7569:     my $total;
                   7570:     foreach my $val (@txts) { $total+=$val; }
                   7571:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7572:     return $total;
                   7573: }
                   7574: 
1.675     albertel 7575: sub digest {
                   7576:     my ($data)=@_;
                   7577:     my $digest=&Digest::MD5::md5($data);
                   7578:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7579:     my ($e,$f);
                   7580:     {
                   7581:         use integer;
                   7582:         $e=($a+$b);
                   7583:         $f=($c+$d);
                   7584:         if ($_64bit) {
                   7585:             $e=(($e<<32)>>32);
                   7586:             $f=(($f<<32)>>32);
                   7587:         }
                   7588:     }
                   7589:     if (wantarray) {
                   7590: 	return ($e,$f);
                   7591:     } else {
                   7592: 	my $g;
                   7593: 	{
                   7594: 	    use integer;
                   7595: 	    $g=($e+$f);
                   7596: 	    if ($_64bit) {
                   7597: 		$g=(($g<<32)>>32);
                   7598: 	    }
                   7599: 	}
                   7600: 	return $g;
                   7601:     }
                   7602: }
                   7603: 
1.368     albertel 7604: sub latest_rnd_algorithm_id {
1.675     albertel 7605:     return '64bit5';
1.366     albertel 7606: }
1.32      www      7607: 
1.503     albertel 7608: sub get_rand_alg {
                   7609:     my ($courseid)=@_;
1.790     albertel 7610:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7611:     if ($courseid) {
1.620     albertel 7612: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7613:     }
                   7614:     return &latest_rnd_algorithm_id();
                   7615: }
                   7616: 
1.562     albertel 7617: sub validCODE {
                   7618:     my ($CODE)=@_;
                   7619:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7620:     return 0;
                   7621: }
                   7622: 
1.491     albertel 7623: sub getCODE {
1.620     albertel 7624:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7625:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7626: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7627: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7628: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7629:     }
                   7630:     return undef;
                   7631: }
                   7632: 
1.31      www      7633: sub rndseed {
1.155     albertel 7634:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7635:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7636:     if (!defined($symb)) {
1.366     albertel 7637: 	unless ($symb=$wsymb) { return time; }
                   7638:     }
                   7639:     if (!$courseid) { $courseid=$wcourseid; }
                   7640:     if (!$domain) { $domain=$wdomain; }
                   7641:     if (!$username) { $username=$wusername }
1.503     albertel 7642:     my $which=&get_rand_alg();
1.803     albertel 7643: 
1.491     albertel 7644:     if (defined(&getCODE())) {
1.675     albertel 7645: 	if ($which eq '64bit5') {
                   7646: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7647: 	} elsif ($which eq '64bit4') {
1.575     albertel 7648: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7649: 	} else {
                   7650: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7651: 	}
1.675     albertel 7652:     } elsif ($which eq '64bit5') {
                   7653: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7654:     } elsif ($which eq '64bit4') {
                   7655: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7656:     } elsif ($which eq '64bit3') {
                   7657: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7658:     } elsif ($which eq '64bit2') {
                   7659: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7660:     } elsif ($which eq '64bit') {
                   7661: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7662:     }
                   7663:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7664: }
                   7665: 
                   7666: sub rndseed_32bit {
                   7667:     my ($symb,$courseid,$domain,$username)=@_;
                   7668:     {
                   7669: 	use integer;
                   7670: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7671: 	my $symbseed=numval($symb) << 22;
                   7672: 	my $namechck=unpack("%32C*",$username) << 17;
                   7673: 	my $nameseed=numval($username) << 12;
                   7674: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7675: 	my $courseseed=unpack("%32C*",$courseid);
                   7676: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7677: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7678: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7679: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7680: 	return $num;
                   7681:     }
                   7682: }
                   7683: 
                   7684: sub rndseed_64bit {
                   7685:     my ($symb,$courseid,$domain,$username)=@_;
                   7686:     {
                   7687: 	use integer;
                   7688: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7689: 	my $symbseed=numval($symb) << 10;
                   7690: 	my $namechck=unpack("%32S*",$username);
                   7691: 	
                   7692: 	my $nameseed=numval($username) << 21;
                   7693: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7694: 	my $courseseed=unpack("%32S*",$courseid);
                   7695: 	
                   7696: 	my $num1=$symbchck+$symbseed+$namechck;
                   7697: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7698: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7699: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7700: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7701: 	return "$num1,$num2";
1.155     albertel 7702:     }
1.366     albertel 7703: }
                   7704: 
1.443     albertel 7705: sub rndseed_64bit2 {
                   7706:     my ($symb,$courseid,$domain,$username)=@_;
                   7707:     {
                   7708: 	use integer;
                   7709: 	# strings need to be an even # of cahracters long, it it is odd the
                   7710:         # last characters gets thrown away
                   7711: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7712: 	my $symbseed=numval($symb) << 10;
                   7713: 	my $namechck=unpack("%32S*",$username.' ');
                   7714: 	
                   7715: 	my $nameseed=numval($username) << 21;
1.501     albertel 7716: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7717: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7718: 	
                   7719: 	my $num1=$symbchck+$symbseed+$namechck;
                   7720: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7721: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7722: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7723: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7724: 	return "$num1,$num2";
                   7725:     }
                   7726: }
                   7727: 
                   7728: sub rndseed_64bit3 {
                   7729:     my ($symb,$courseid,$domain,$username)=@_;
                   7730:     {
                   7731: 	use integer;
                   7732: 	# strings need to be an even # of cahracters long, it it is odd the
                   7733:         # last characters gets thrown away
                   7734: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7735: 	my $symbseed=numval2($symb) << 10;
                   7736: 	my $namechck=unpack("%32S*",$username.' ');
                   7737: 	
                   7738: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7739: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7740: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7741: 	
                   7742: 	my $num1=$symbchck+$symbseed+$namechck;
                   7743: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7744: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7745: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7746: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7747: 	
1.503     albertel 7748: 	return "$num1:$num2";
1.443     albertel 7749:     }
                   7750: }
                   7751: 
1.575     albertel 7752: sub rndseed_64bit4 {
                   7753:     my ($symb,$courseid,$domain,$username)=@_;
                   7754:     {
                   7755: 	use integer;
                   7756: 	# strings need to be an even # of cahracters long, it it is odd the
                   7757:         # last characters gets thrown away
                   7758: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7759: 	my $symbseed=numval3($symb) << 10;
                   7760: 	my $namechck=unpack("%32S*",$username.' ');
                   7761: 	
                   7762: 	my $nameseed=numval3($username) << 21;
                   7763: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7764: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7765: 	
                   7766: 	my $num1=$symbchck+$symbseed+$namechck;
                   7767: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7768: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7769: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7770: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7771: 	
                   7772: 	return "$num1:$num2";
                   7773:     }
                   7774: }
                   7775: 
1.675     albertel 7776: sub rndseed_64bit5 {
                   7777:     my ($symb,$courseid,$domain,$username)=@_;
                   7778:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7779:     return "$num1:$num2";
                   7780: }
                   7781: 
1.366     albertel 7782: sub rndseed_CODE_64bit {
                   7783:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7784:     {
1.366     albertel 7785: 	use integer;
1.443     albertel 7786: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7787: 	my $symbseed=numval2($symb);
1.491     albertel 7788: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7789: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7790: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7791: 	my $num1=$symbseed+$CODEchck;
                   7792: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7793: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7794: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7795: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7796: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7797: 	return "$num1:$num2";
1.366     albertel 7798:     }
                   7799: }
                   7800: 
1.575     albertel 7801: sub rndseed_CODE_64bit4 {
                   7802:     my ($symb,$courseid,$domain,$username)=@_;
                   7803:     {
                   7804: 	use integer;
                   7805: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7806: 	my $symbseed=numval3($symb);
                   7807: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7808: 	my $CODEseed=numval3(&getCODE());
                   7809: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7810: 	my $num1=$symbseed+$CODEchck;
                   7811: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7812: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7813: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7814: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7815: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7816: 	return "$num1:$num2";
                   7817:     }
                   7818: }
                   7819: 
1.675     albertel 7820: sub rndseed_CODE_64bit5 {
                   7821:     my ($symb,$courseid,$domain,$username)=@_;
                   7822:     my $code = &getCODE();
                   7823:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7824:     return "$num1:$num2";
                   7825: }
                   7826: 
1.366     albertel 7827: sub setup_random_from_rndseed {
                   7828:     my ($rndseed)=@_;
1.503     albertel 7829:     if ($rndseed =~/([,:])/) {
                   7830: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7831: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7832:     } else {
                   7833: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7834:     }
1.36      albertel 7835: }
                   7836: 
1.474     albertel 7837: sub latest_receipt_algorithm_id {
1.835     albertel 7838:     return 'receipt3';
1.474     albertel 7839: }
                   7840: 
1.480     www      7841: sub recunique {
                   7842:     my $fucourseid=shift;
                   7843:     my $unique;
1.835     albertel 7844:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7845: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7846: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7847:     } else {
                   7848: 	$unique=$perlvar{'lonReceipt'};
                   7849:     }
                   7850:     return unpack("%32C*",$unique);
                   7851: }
                   7852: 
                   7853: sub recprefix {
                   7854:     my $fucourseid=shift;
                   7855:     my $prefix;
1.835     albertel 7856:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7857: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7858: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7859:     } else {
                   7860: 	$prefix=$perlvar{'lonHostID'};
                   7861:     }
                   7862:     return unpack("%32C*",$prefix);
                   7863: }
                   7864: 
1.76      www      7865: sub ireceipt {
1.474     albertel 7866:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7867: 
                   7868:     my $return =&recprefix($fucourseid).'-';
                   7869: 
                   7870:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7871: 	$env{'request.state'} eq 'construct') {
                   7872: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7873: 	return $return;
                   7874:     }
                   7875: 
1.76      www      7876:     my $cuname=unpack("%32C*",$funame);
                   7877:     my $cudom=unpack("%32C*",$fudom);
                   7878:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7879:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7880:     my $cunique=&recunique($fucourseid);
1.474     albertel 7881:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7882:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7883: 
1.790     albertel 7884: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7885: 			       
                   7886: 	$return.= ($cunique%$cuname+
                   7887: 		   $cunique%$cudom+
                   7888: 		   $cusymb%$cuname+
                   7889: 		   $cusymb%$cudom+
                   7890: 		   $cucourseid%$cuname+
                   7891: 		   $cucourseid%$cudom+
                   7892: 		   $cpart%$cuname+
                   7893: 		   $cpart%$cudom);
                   7894:     } else {
                   7895: 	$return.= ($cunique%$cuname+
                   7896: 		   $cunique%$cudom+
                   7897: 		   $cusymb%$cuname+
                   7898: 		   $cusymb%$cudom+
                   7899: 		   $cucourseid%$cuname+
                   7900: 		   $cucourseid%$cudom);
                   7901:     }
                   7902:     return $return;
1.76      www      7903: }
                   7904: 
                   7905: sub receipt {
1.474     albertel 7906:     my ($part)=@_;
1.790     albertel 7907:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7908:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7909: }
1.260     ng       7910: 
1.790     albertel 7911: sub whichuser {
                   7912:     my ($passedsymb)=@_;
                   7913:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7914:     if (defined($env{'form.grade_symb'})) {
                   7915: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7916: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7917: 	if (!$allowed &&
                   7918: 	    exists($env{'request.course.sec'}) &&
                   7919: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7920: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7921: 			      '/'.$env{'request.course.sec'});
                   7922: 	}
                   7923: 	if ($allowed) {
                   7924: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7925: 	    $courseid=$tmp_courseid;
                   7926: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7927: 	    ($name)=&get_env_multiple('form.grade_username');
                   7928: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7929: 	}
                   7930:     }
                   7931:     if (!$passedsymb) {
                   7932: 	$symb=&symbread();
                   7933:     } else {
                   7934: 	$symb=$passedsymb;
                   7935:     }
                   7936:     $courseid=$env{'request.course.id'};
                   7937:     $domain=$env{'user.domain'};
                   7938:     $name=$env{'user.name'};
                   7939:     if ($name eq 'public' && $domain eq 'public') {
                   7940: 	if (!defined($env{'form.username'})) {
                   7941: 	    $env{'form.username'}.=time.rand(10000000);
                   7942: 	}
                   7943: 	$name.=$env{'form.username'};
                   7944:     }
                   7945:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7946: 
                   7947: }
                   7948: 
1.36      albertel 7949: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7950: # returns either the contents of the file or 
                   7951: # -1 if the file doesn't exist
1.481     raeburn  7952: #
                   7953: # if the target is a file that was uploaded via DOCS, 
                   7954: # a check will be made to see if a current copy exists on the local server,
                   7955: # if it does this will be served, otherwise a copy will be retrieved from
                   7956: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7957: # the local server.   
1.472     albertel 7958: 
1.36      albertel 7959: sub getfile {
1.538     albertel 7960:     my ($file) = @_;
1.609     banghart 7961:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7962:     &repcopy($file);
                   7963:     return &readfile($file);
                   7964: }
                   7965: 
                   7966: sub repcopy_userfile {
                   7967:     my ($file)=@_;
1.609     banghart 7968:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7969:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7970:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7971: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7972:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7973:     if (-e "$file") {
1.828     www      7974: # we already have a local copy, check it out
1.538     albertel 7975: 	my @fileinfo = stat($file);
1.828     www      7976: 	my $rtncode;
                   7977: 	my $info;
1.538     albertel 7978: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7979: 	if ($lwpresp ne 'ok') {
1.828     www      7980: # there is no such file anymore, even though we had a local copy
1.482     albertel 7981: 	    if ($rtncode eq '404') {
1.538     albertel 7982: 		unlink($file);
1.482     albertel 7983: 	    }
                   7984: 	    return -1;
                   7985: 	}
                   7986: 	if ($info < $fileinfo[9]) {
1.828     www      7987: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7988: 	    return 'ok';
1.828     www      7989: 	} else {
                   7990: # the file is outdated, get rid of it
                   7991: 	    unlink($file);
1.482     albertel 7992: 	}
1.828     www      7993:     }
                   7994: # one way or the other, at this point, we don't have the file
                   7995: # construct the correct path for the file
                   7996:     my @parts = ($cdom,$cnum); 
                   7997:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7998: 	push @parts, split(/\//,$1);
                   7999:     }
                   8000:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8001:     foreach my $part (@parts) {
                   8002: 	$path .= '/'.$part;
                   8003: 	if (!-e $path) {
                   8004: 	    mkdir($path,0770);
1.482     albertel 8005: 	}
                   8006:     }
1.828     www      8007: # now the path exists for sure
                   8008: # get a user agent
                   8009:     my $ua=new LWP::UserAgent;
                   8010:     my $transferfile=$file.'.in.transfer';
                   8011: # FIXME: this should flock
                   8012:     if (-e $transferfile) { return 'ok'; }
                   8013:     my $request;
                   8014:     $uri=~s/^\///;
1.838     albertel 8015:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      8016:     my $response=$ua->request($request,$transferfile);
                   8017: # did it work?
                   8018:     if ($response->is_error()) {
                   8019: 	unlink($transferfile);
                   8020: 	&logthis("Userfile repcopy failed for $uri");
                   8021: 	return -1;
                   8022:     }
                   8023: # worked, rename the transfer file
                   8024:     rename($transferfile,$file);
1.607     raeburn  8025:     return 'ok';
1.481     raeburn  8026: }
                   8027: 
1.517     albertel 8028: sub tokenwrapper {
                   8029:     my $uri=shift;
1.552     albertel 8030:     $uri=~s|^http\://([^/]+)||;
                   8031:     $uri=~s|^/||;
1.620     albertel 8032:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8033:     my $token=$1;
1.552     albertel 8034:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8035:     if ($udom && $uname && $file) {
                   8036: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8037:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8038:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8039:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8040:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8041:     } else {
                   8042:         return '/adm/notfound.html';
                   8043:     }
                   8044: }
                   8045: 
1.828     www      8046: # call with reqtype HEAD: get last modification time
                   8047: # call with reqtype GET: get the file contents
                   8048: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8049: #
1.481     raeburn  8050: sub getuploaded {
                   8051:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8052:     $uri=~s/^\///;
1.838     albertel 8053:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8054:     my $ua=new LWP::UserAgent;
                   8055:     my $request=new HTTP::Request($reqtype,$uri);
                   8056:     my $response=$ua->request($request);
                   8057:     $$rtncode = $response->code;
1.482     albertel 8058:     if (! $response->is_success()) {
                   8059: 	return 'failed';
                   8060:     }      
                   8061:     if ($reqtype eq 'HEAD') {
1.486     www      8062: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8063:     } elsif ($reqtype eq 'GET') {
                   8064: 	$$info = $response->content;
1.472     albertel 8065:     }
1.482     albertel 8066:     return 'ok';
1.36      albertel 8067: }
                   8068: 
1.481     raeburn  8069: sub readfile {
                   8070:     my $file = shift;
                   8071:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8072:     my $fh;
                   8073:     open($fh,"<$file");
                   8074:     my $a='';
1.800     albertel 8075:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8076:     return $a;
                   8077: }
                   8078: 
1.36      albertel 8079: sub filelocation {
1.590     banghart 8080:     my ($dir,$file) = @_;
                   8081:     my $location;
                   8082:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8083: 
                   8084:     if ($file =~ m-^/adm/-) {
                   8085: 	$file=~s-^/adm/wrapper/-/-;
                   8086: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8087:     }
1.882     albertel 8088: 
1.590     banghart 8089:     if ($file=~m:^/~:) { # is a contruction space reference
                   8090:         $location = $file;
                   8091:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8092:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8093: 	# is a correct contruction space reference
                   8094:         $location = $file;
1.609     banghart 8095:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8096:         my ($udom,$uname,$filename)=
1.811     albertel 8097:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8098:         my $home=&homeserver($uname,$udom);
                   8099:         my $is_me=0;
                   8100:         my @ids=&current_machine_ids();
                   8101:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8102:         if ($is_me) {
1.740     www      8103:   	    $location=&propath($udom,$uname).
1.590     banghart 8104:   	      '/userfiles/'.$filename;
                   8105:         } else {
                   8106:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8107:   	      $udom.'/'.$uname.'/'.$filename;
                   8108:         }
1.882     albertel 8109:     } elsif ($file =~ m-^/adm/-) {
                   8110: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8111:     } else {
                   8112:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8113:         $file=~s:^/res/:/:;
                   8114:         if ( !( $file =~ m:^/:) ) {
                   8115:             $location = $dir. '/'.$file;
                   8116:         } else {
                   8117:             $location = '/home/httpd/html/res'.$file;
                   8118:         }
1.59      albertel 8119:     }
1.590     banghart 8120:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8121:     while ($location=~m{/\.\./}) {
                   8122: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8123: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8124: 	} else {
                   8125: 	    $location=~ s{/\.\./}{/}g;
                   8126: 	}
                   8127:     } #remove dir/..
1.590     banghart 8128:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8129:     return $location;
1.46      www      8130: }
1.36      albertel 8131: 
1.46      www      8132: sub hreflocation {
                   8133:     my ($dir,$file)=@_;
1.460     albertel 8134:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8135: 	$file=filelocation($dir,$file);
1.700     albertel 8136:     } elsif ($file=~m-^/adm/-) {
                   8137: 	$file=~s-^/adm/wrapper/-/-;
                   8138: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8139:     }
                   8140:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8141: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8142:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8143: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8144:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8145: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8146: 	    -/uploaded/$1/$2/-x;
1.46      www      8147:     }
1.913     albertel 8148:     if ($file=~ m{^/userfiles/}) {
                   8149: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8150:     }
1.462     albertel 8151:     return $file;
1.465     albertel 8152: }
                   8153: 
                   8154: sub current_machine_domains {
1.853     albertel 8155:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8156: }
                   8157: 
                   8158: sub machine_domains {
                   8159:     my ($hostname) = @_;
1.465     albertel 8160:     my @domains;
1.838     albertel 8161:     my %hostname = &all_hostnames();
1.465     albertel 8162:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8163: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8164: 	if ($hostname eq $name) {
1.844     albertel 8165: 	    push(@domains,&host_domain($id));
1.465     albertel 8166: 	}
                   8167:     }
                   8168:     return @domains;
                   8169: }
                   8170: 
                   8171: sub current_machine_ids {
1.853     albertel 8172:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8173: }
                   8174: 
                   8175: sub machine_ids {
                   8176:     my ($hostname) = @_;
                   8177:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8178:     my @ids;
1.888     albertel 8179:     my %name_to_host = &all_names();
1.889     albertel 8180:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8181: 	return @{ $name_to_host{$hostname} };
                   8182:     }
                   8183:     return;
1.31      www      8184: }
                   8185: 
1.824     raeburn  8186: sub additional_machine_domains {
                   8187:     my @domains;
                   8188:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8189:     while( my $line = <$fh>) {
                   8190:         $line =~ s/\s//g;
                   8191:         push(@domains,$line);
                   8192:     }
                   8193:     return @domains;
                   8194: }
                   8195: 
                   8196: sub default_login_domain {
                   8197:     my $domain = $perlvar{'lonDefDomain'};
                   8198:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8199:     foreach my $posdom (&current_machine_domains(),
                   8200:                         &additional_machine_domains()) {
                   8201:         if (lc($posdom) eq lc($testdomain)) {
                   8202:             $domain=$posdom;
                   8203:             last;
                   8204:         }
                   8205:     }
                   8206:     return $domain;
                   8207: }
                   8208: 
1.31      www      8209: # ------------------------------------------------------------- Declutters URLs
                   8210: 
                   8211: sub declutter {
                   8212:     my $thisfn=shift;
1.569     albertel 8213:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8214:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8215:     $thisfn=~s/^\///;
1.697     albertel 8216:     $thisfn=~s|^adm/wrapper/||;
                   8217:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8218:     $thisfn=~s/^res\///;
1.235     www      8219:     $thisfn=~s/\?.+$//;
1.268     www      8220:     return $thisfn;
                   8221: }
                   8222: 
                   8223: # ------------------------------------------------------------- Clutter up URLs
                   8224: 
                   8225: sub clutter {
                   8226:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8227:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8228: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8229:        $thisfn='/res'.$thisfn; 
                   8230:     }
1.694     albertel 8231:     if ($thisfn !~m|/adm|) {
1.695     albertel 8232: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8233: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8234: 	} else {
                   8235: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8236: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8237: 	    if ($embstyle eq 'ssi'
                   8238: 		|| ($embstyle eq 'hdn')
                   8239: 		|| ($embstyle eq 'rat')
                   8240: 		|| ($embstyle eq 'prv')
                   8241: 		|| ($embstyle eq 'ign')) {
                   8242: 		#do nothing with these
                   8243: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8244: 		|| ($embstyle eq 'emb')
                   8245: 		|| ($embstyle eq 'wrp')) {
                   8246: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8247: 	    } elsif ($embstyle eq 'unk'
                   8248: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8249: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8250: 	    } else {
1.718     www      8251: #		&logthis("Got a blank emb style");
1.695     albertel 8252: 	    }
1.694     albertel 8253: 	}
                   8254:     }
1.31      www      8255:     return $thisfn;
1.12      www      8256: }
                   8257: 
1.787     albertel 8258: sub clutter_with_no_wrapper {
                   8259:     my $uri = &clutter(shift);
                   8260:     if ($uri =~ m-^/adm/-) {
                   8261: 	$uri =~ s-^/adm/wrapper/-/-;
                   8262: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8263:     }
                   8264:     return $uri;
                   8265: }
                   8266: 
1.557     albertel 8267: sub freeze_escape {
                   8268:     my ($value)=@_;
                   8269:     if (ref($value)) {
                   8270: 	$value=&nfreeze($value);
                   8271: 	return '__FROZEN__'.&escape($value);
                   8272:     }
                   8273:     return &escape($value);
                   8274: }
                   8275: 
1.11      www      8276: 
1.557     albertel 8277: sub thaw_unescape {
                   8278:     my ($value)=@_;
                   8279:     if ($value =~ /^__FROZEN__/) {
                   8280: 	substr($value,0,10,undef);
                   8281: 	$value=&unescape($value);
                   8282: 	return &thaw($value);
                   8283:     }
                   8284:     return &unescape($value);
                   8285: }
                   8286: 
1.436     albertel 8287: sub correct_line_ends {
                   8288:     my ($result)=@_;
                   8289:     $$result =~s/\r\n/\n/mg;
                   8290:     $$result =~s/\r/\n/mg;
1.415     albertel 8291: }
1.1       albertel 8292: # ================================================================ Main Program
                   8293: 
1.184     www      8294: sub goodbye {
1.204     albertel 8295:    &logthis("Starting Shut down");
1.443     albertel 8296: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8297:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8298: #converted
1.599     albertel 8299: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8300:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8301: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8302: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8303: #1.1 only
1.870     albertel 8304: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8305: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8306: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8307: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8308:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8309:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8310:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8311:    &flushcourselogs();
                   8312:    &logthis("Shutting down");
                   8313: }
                   8314: 
1.852     albertel 8315: sub get_dns {
1.869     albertel 8316:     my ($url,$func,$ignore_cache) = @_;
                   8317:     if (!$ignore_cache) {
                   8318: 	my ($content,$cached)=
                   8319: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8320: 	if ($cached) {
                   8321: 	    &$func($content);
                   8322: 	    return;
                   8323: 	}
                   8324:     }
                   8325: 
                   8326:     my %alldns;
1.852     albertel 8327:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8328:     foreach my $dns (<$config>) {
                   8329: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8330: 	$alldns{$1} = 1;
                   8331:     }
                   8332:     while (%alldns) {
                   8333: 	my ($dns) = keys(%alldns);
                   8334: 	delete($alldns{$dns});
1.852     albertel 8335: 	my $ua=new LWP::UserAgent;
                   8336: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8337: 	my $response=$ua->request($request);
                   8338: 	next if ($response->is_error());
                   8339: 	my @content = split("\n",$response->content);
1.869     albertel 8340: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8341: 	&$func(\@content);
1.869     albertel 8342: 	return;
1.852     albertel 8343:     }
                   8344:     close($config);
1.871     albertel 8345:     my $which = (split('/',$url))[3];
                   8346:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8347:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8348:     my @content = <$config>;
                   8349:     &$func(\@content);
                   8350:     return;
1.852     albertel 8351: }
1.327     albertel 8352: # ------------------------------------------------------------ Read domain file
                   8353: {
1.852     albertel 8354:     my $loaded;
1.846     albertel 8355:     my %domain;
                   8356: 
1.852     albertel 8357:     sub parse_domain_tab {
                   8358: 	my ($lines) = @_;
                   8359: 	foreach my $line (@$lines) {
                   8360: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8361: 
1.846     albertel 8362: 	    chomp($line);
1.852     albertel 8363: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8364: 	    my %this_domain;
                   8365: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8366: 			       'lang_def', 'city', 'longi', 'lati',
                   8367: 			       'primary') {
                   8368: 		$this_domain{$field} = shift(@elements);
                   8369: 	    }
                   8370: 	    $domain{$name} = \%this_domain;
1.852     albertel 8371: 	}
                   8372:     }
1.864     albertel 8373: 
                   8374:     sub reset_domain_info {
                   8375: 	undef($loaded);
                   8376: 	undef(%domain);
                   8377:     }
                   8378: 
1.852     albertel 8379:     sub load_domain_tab {
1.869     albertel 8380: 	my ($ignore_cache) = @_;
                   8381: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8382: 	my $fh;
                   8383: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8384: 	    my @lines = <$fh>;
                   8385: 	    &parse_domain_tab(\@lines);
1.448     albertel 8386: 	}
1.852     albertel 8387: 	close($fh);
                   8388: 	$loaded = 1;
1.327     albertel 8389:     }
1.846     albertel 8390: 
                   8391:     sub domain {
1.852     albertel 8392: 	&load_domain_tab() if (!$loaded);
                   8393: 
1.846     albertel 8394: 	my ($name,$what) = @_;
                   8395: 	return if ( !exists($domain{$name}) );
                   8396: 
                   8397: 	if (!$what) {
                   8398: 	    return $domain{$name}{'description'};
                   8399: 	}
                   8400: 	return $domain{$name}{$what};
                   8401:     }
1.327     albertel 8402: }
                   8403: 
                   8404: 
1.1       albertel 8405: # ------------------------------------------------------------- Read hosts file
                   8406: {
1.838     albertel 8407:     my %hostname;
1.844     albertel 8408:     my %hostdom;
1.845     albertel 8409:     my %libserv;
1.852     albertel 8410:     my $loaded;
1.888     albertel 8411:     my %name_to_host;
1.852     albertel 8412: 
                   8413:     sub parse_hosts_tab {
                   8414: 	my ($file) = @_;
                   8415: 	foreach my $configline (@$file) {
                   8416: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8417: 	    next if ($configline =~ /^\^/);
                   8418: 	    chomp($configline);
                   8419: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8420: 	    $name=~s/\s//g;
                   8421: 	    if ($id && $domain && $role && $name) {
                   8422: 		$hostname{$id}=$name;
1.888     albertel 8423: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8424: 		$hostdom{$id}=$domain;
                   8425: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8426: 	    }
                   8427: 	}
                   8428:     }
1.864     albertel 8429:     
                   8430:     sub reset_hosts_info {
1.897     albertel 8431: 	&purge_remembered();
1.864     albertel 8432: 	&reset_domain_info();
                   8433: 	&reset_hosts_ip_info();
1.892     albertel 8434: 	undef(%name_to_host);
1.864     albertel 8435: 	undef(%hostname);
                   8436: 	undef(%hostdom);
                   8437: 	undef(%libserv);
                   8438: 	undef($loaded);
                   8439:     }
1.1       albertel 8440: 
1.852     albertel 8441:     sub load_hosts_tab {
1.869     albertel 8442: 	my ($ignore_cache) = @_;
                   8443: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8444: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8445: 	my @config = <$config>;
                   8446: 	&parse_hosts_tab(\@config);
                   8447: 	close($config);
                   8448: 	$loaded=1;
1.1       albertel 8449:     }
1.852     albertel 8450: 
1.838     albertel 8451:     sub hostname {
1.852     albertel 8452: 	&load_hosts_tab() if (!$loaded);
                   8453: 
1.838     albertel 8454: 	my ($lonid) = @_;
                   8455: 	return $hostname{$lonid};
                   8456:     }
1.845     albertel 8457: 
1.838     albertel 8458:     sub all_hostnames {
1.852     albertel 8459: 	&load_hosts_tab() if (!$loaded);
                   8460: 
1.838     albertel 8461: 	return %hostname;
                   8462:     }
1.845     albertel 8463: 
1.888     albertel 8464:     sub all_names {
                   8465: 	&load_hosts_tab() if (!$loaded);
                   8466: 
                   8467: 	return %name_to_host;
                   8468:     }
                   8469: 
1.845     albertel 8470:     sub is_library {
1.852     albertel 8471: 	&load_hosts_tab() if (!$loaded);
                   8472: 
1.845     albertel 8473: 	return exists($libserv{$_[0]});
                   8474:     }
                   8475: 
                   8476:     sub all_library {
1.852     albertel 8477: 	&load_hosts_tab() if (!$loaded);
                   8478: 
1.845     albertel 8479: 	return %libserv;
                   8480:     }
                   8481: 
1.841     albertel 8482:     sub get_servers {
1.852     albertel 8483: 	&load_hosts_tab() if (!$loaded);
                   8484: 
1.841     albertel 8485: 	my ($domain,$type) = @_;
                   8486: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8487: 	                                          : %hostname;
                   8488: 	my %result;
1.842     albertel 8489: 	if (ref($domain) eq 'ARRAY') {
                   8490: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8491: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8492: 		    $result{$host} = $hostname;
                   8493: 		}
                   8494: 	    }
                   8495: 	} else {
                   8496: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8497: 		if ($hostdom{$host} eq $domain) {
                   8498: 		    $result{$host} = $hostname;
                   8499: 		}
1.841     albertel 8500: 	    }
                   8501: 	}
                   8502: 	return %result;
                   8503:     }
1.845     albertel 8504: 
1.844     albertel 8505:     sub host_domain {
1.852     albertel 8506: 	&load_hosts_tab() if (!$loaded);
                   8507: 
1.844     albertel 8508: 	my ($lonid) = @_;
                   8509: 	return $hostdom{$lonid};
                   8510:     }
                   8511: 
1.841     albertel 8512:     sub all_domains {
1.852     albertel 8513: 	&load_hosts_tab() if (!$loaded);
                   8514: 
1.841     albertel 8515: 	my %seen;
                   8516: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8517: 	return @uniq;
                   8518:     }
1.1       albertel 8519: }
                   8520: 
1.847     albertel 8521: { 
                   8522:     my %iphost;
1.856     albertel 8523:     my %name_to_ip;
                   8524:     my %lonid_to_ip;
1.869     albertel 8525: 
1.847     albertel 8526:     sub get_hosts_from_ip {
                   8527: 	my ($ip) = @_;
                   8528: 	my %iphosts = &get_iphost();
                   8529: 	if (ref($iphosts{$ip})) {
                   8530: 	    return @{$iphosts{$ip}};
                   8531: 	}
                   8532: 	return;
1.839     albertel 8533:     }
1.864     albertel 8534:     
                   8535:     sub reset_hosts_ip_info {
                   8536: 	undef(%iphost);
                   8537: 	undef(%name_to_ip);
                   8538: 	undef(%lonid_to_ip);
                   8539:     }
1.856     albertel 8540: 
                   8541:     sub get_host_ip {
                   8542: 	my ($lonid) = @_;
                   8543: 	if (exists($lonid_to_ip{$lonid})) {
                   8544: 	    return $lonid_to_ip{$lonid};
                   8545: 	}
                   8546: 	my $name=&hostname($lonid);
                   8547:    	my $ip = gethostbyname($name);
                   8548: 	return if (!$ip || length($ip) ne 4);
                   8549: 	$ip=inet_ntoa($ip);
                   8550: 	$name_to_ip{$name}   = $ip;
                   8551: 	$lonid_to_ip{$lonid} = $ip;
                   8552: 	return $ip;
                   8553:     }
1.847     albertel 8554:     
                   8555:     sub get_iphost {
1.869     albertel 8556: 	my ($ignore_cache) = @_;
1.894     albertel 8557: 
1.869     albertel 8558: 	if (!$ignore_cache) {
                   8559: 	    if (%iphost) {
                   8560: 		return %iphost;
                   8561: 	    }
                   8562: 	    my ($ip_info,$cached)=
                   8563: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8564: 	    if ($cached) {
                   8565: 		%iphost      = %{$ip_info->[0]};
                   8566: 		%name_to_ip  = %{$ip_info->[1]};
                   8567: 		%lonid_to_ip = %{$ip_info->[2]};
                   8568: 		return %iphost;
                   8569: 	    }
                   8570: 	}
1.894     albertel 8571: 
                   8572: 	# get yesterday's info for fallback
                   8573: 	my %old_name_to_ip;
                   8574: 	my ($ip_info,$cached)=
                   8575: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8576: 	if ($cached) {
                   8577: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8578: 	}
                   8579: 
1.888     albertel 8580: 	my %name_to_host = &all_names();
                   8581: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8582: 	    my $ip;
                   8583: 	    if (!exists($name_to_ip{$name})) {
                   8584: 		$ip = gethostbyname($name);
                   8585: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8586: 		    if (defined($old_name_to_ip{$name})) {
                   8587: 			$ip = $old_name_to_ip{$name};
                   8588: 			&logthis("Can't find $name defaulting to old $ip");
                   8589: 		    } else {
                   8590: 			&logthis("Name $name no IP found");
                   8591: 			next;
                   8592: 		    }
                   8593: 		} else {
                   8594: 		    $ip=inet_ntoa($ip);
1.847     albertel 8595: 		}
                   8596: 		$name_to_ip{$name} = $ip;
                   8597: 	    } else {
                   8598: 		$ip = $name_to_ip{$name};
1.653     albertel 8599: 	    }
1.888     albertel 8600: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8601: 		$lonid_to_ip{$id} = $ip;
                   8602: 	    }
                   8603: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8604: 	}
1.869     albertel 8605: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8606: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8607: 				      48*60*60);
1.869     albertel 8608: 
1.847     albertel 8609: 	return %iphost;
1.598     albertel 8610:     }
                   8611: }
                   8612: 
1.862     albertel 8613: BEGIN {
                   8614: 
                   8615: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8616:     unless ($readit) {
                   8617: {
                   8618:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8619:     %perlvar = (%perlvar,%{$configvars});
                   8620: }
                   8621: 
                   8622: 
1.1       albertel 8623: # ------------------------------------------------------ Read spare server file
                   8624: {
1.448     albertel 8625:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8626: 
                   8627:     while (my $configline=<$config>) {
                   8628:        chomp($configline);
1.284     matthew  8629:        if ($configline) {
1.784     albertel 8630: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8631: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8632: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8633:        }
                   8634:     }
1.448     albertel 8635:     close($config);
1.1       albertel 8636: }
1.11      www      8637: # ------------------------------------------------------------ Read permissions
                   8638: {
1.448     albertel 8639:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8640: 
                   8641:     while (my $configline=<$config>) {
1.448     albertel 8642: 	chomp($configline);
                   8643: 	if ($configline) {
                   8644: 	    my ($role,$perm)=split(/ /,$configline);
                   8645: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8646: 	}
1.11      www      8647:     }
1.448     albertel 8648:     close($config);
1.11      www      8649: }
                   8650: 
                   8651: # -------------------------------------------- Read plain texts for permissions
                   8652: {
1.448     albertel 8653:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8654: 
                   8655:     while (my $configline=<$config>) {
1.448     albertel 8656: 	chomp($configline);
                   8657: 	if ($configline) {
1.742     raeburn  8658: 	    my ($short,@plain)=split(/:/,$configline);
                   8659:             %{$prp{$short}} = ();
                   8660: 	    if (@plain > 0) {
                   8661:                 $prp{$short}{'std'} = $plain[0];
                   8662:                 for (my $i=1; $i<@plain; $i++) {
                   8663:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8664:                 }
                   8665:             }
1.448     albertel 8666: 	}
1.135     www      8667:     }
1.448     albertel 8668:     close($config);
1.135     www      8669: }
                   8670: 
                   8671: # ---------------------------------------------------------- Read package table
                   8672: {
1.448     albertel 8673:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8674: 
                   8675:     while (my $configline=<$config>) {
1.483     albertel 8676: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8677: 	chomp($configline);
                   8678: 	my ($short,$plain)=split(/:/,$configline);
                   8679: 	my ($pack,$name)=split(/\&/,$short);
                   8680: 	if ($plain ne '') {
                   8681: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8682: 	    $packagetab{$short}=$plain; 
                   8683: 	}
1.11      www      8684:     }
1.448     albertel 8685:     close($config);
1.329     matthew  8686: }
                   8687: 
                   8688: # ------------- set up temporary directory
                   8689: {
                   8690:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8691: 
1.11      www      8692: }
                   8693: 
1.794     albertel 8694: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8695: 				'compress_threshold'=> 20_000,
                   8696:  			        });
1.185     www      8697: 
1.281     www      8698: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8699: $dumpcount=0;
1.22      www      8700: 
1.163     harris41 8701: &logtouch();
1.672     albertel 8702: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8703: $readit=1;
1.564     albertel 8704:     {
                   8705: 	use integer;
                   8706: 	my $test=(2**32)+1;
1.568     albertel 8707: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8708: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8709:     }
1.195     www      8710: }
1.1       albertel 8711: }
1.179     www      8712: 
1.1       albertel 8713: 1;
1.191     harris41 8714: __END__
                   8715: 
1.243     albertel 8716: =pod
                   8717: 
1.191     harris41 8718: =head1 NAME
                   8719: 
1.243     albertel 8720: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8721: 
                   8722: =head1 SYNOPSIS
                   8723: 
1.243     albertel 8724: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8725: 
                   8726:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8727: 
1.243     albertel 8728: Common parameters:
                   8729: 
                   8730: =over 4
                   8731: 
                   8732: =item *
                   8733: 
                   8734: $uname : an internal username (if $cname expecting a course Id specifically)
                   8735: 
                   8736: =item *
                   8737: 
                   8738: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8739: 
                   8740: =item *
                   8741: 
                   8742: $symb : a resource instance identifier
                   8743: 
                   8744: =item *
                   8745: 
                   8746: $namespace : the name of a .db file that contains the data needed or
                   8747: being set.
                   8748: 
                   8749: =back
                   8750: 
1.394     bowersj2 8751: =head1 OVERVIEW
1.191     harris41 8752: 
1.394     bowersj2 8753: lonnet provides subroutines which interact with the
                   8754: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8755: about classes, users, and resources.
1.243     albertel 8756: 
                   8757: For many of these objects you can also use this to store data about
                   8758: them or modify them in various ways.
1.191     harris41 8759: 
1.394     bowersj2 8760: =head2 Symbs
1.191     harris41 8761: 
1.394     bowersj2 8762: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8763: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8764: map, the resource number of the resource in the map, and the URL of
                   8765: the resource itself. The latter is somewhat redundant, but might help
                   8766: if maps change.
                   8767: 
                   8768: An example is
                   8769: 
                   8770:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8771: 
                   8772: The respective map entry is
                   8773: 
                   8774:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8775:   title="Problem 2">
                   8776:  </resource>
                   8777: 
                   8778: Symbs are used by the random number generator, as well as to store and
                   8779: restore data specific to a certain instance of for example a problem.
                   8780: 
                   8781: =head2 Storing And Retrieving Data
                   8782: 
                   8783: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8784: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8785: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8786: is is the non-critical message twin of cstore. These functions are for
                   8787: handlers to store a perl hash to a user's permanent data space in an
                   8788: easy manner, and to retrieve it again on another call. It is expected
                   8789: that a handler would use this once at the beginning to retrieve data,
                   8790: and then again once at the end to send only the new data back.
                   8791: 
                   8792: The data is stored in the user's data directory on the user's
                   8793: homeserver under the ID of the course.
                   8794: 
                   8795: The hash that is returned by restore will have all of the previous
                   8796: value for all of the elements of the hash.
                   8797: 
                   8798: Example:
                   8799: 
                   8800:  #creating a hash
                   8801:  my %hash;
                   8802:  $hash{'foo'}='bar';
                   8803: 
                   8804:  #storing it
                   8805:  &Apache::lonnet::cstore(\%hash);
                   8806: 
                   8807:  #changing a value
                   8808:  $hash{'foo'}='notbar';
                   8809: 
                   8810:  #adding a new value
                   8811:  $hash{'bar'}='foo';
                   8812:  &Apache::lonnet::cstore(\%hash);
                   8813: 
                   8814:  #retrieving the hash
                   8815:  my %history=&Apache::lonnet::restore();
                   8816: 
                   8817:  #print the hash
                   8818:  foreach my $key (sort(keys(%history))) {
                   8819:    print("\%history{$key} = $history{$key}");
                   8820:  }
                   8821: 
                   8822: Will print out:
1.191     harris41 8823: 
1.394     bowersj2 8824:  %history{1:foo} = bar
                   8825:  %history{1:keys} = foo:timestamp
                   8826:  %history{1:timestamp} = 990455579
                   8827:  %history{2:bar} = foo
                   8828:  %history{2:foo} = notbar
                   8829:  %history{2:keys} = foo:bar:timestamp
                   8830:  %history{2:timestamp} = 990455580
                   8831:  %history{bar} = foo
                   8832:  %history{foo} = notbar
                   8833:  %history{timestamp} = 990455580
                   8834:  %history{version} = 2
                   8835: 
                   8836: Note that the special hash entries C<keys>, C<version> and
                   8837: C<timestamp> were added to the hash. C<version> will be equal to the
                   8838: total number of versions of the data that have been stored. The
                   8839: C<timestamp> attribute will be the UNIX time the hash was
                   8840: stored. C<keys> is available in every historical section to list which
                   8841: keys were added or changed at a specific historical revision of a
                   8842: hash.
                   8843: 
                   8844: B<Warning>: do not store the hash that restore returns directly. This
                   8845: will cause a mess since it will restore the historical keys as if the
                   8846: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8847: 
1.394     bowersj2 8848: Calling convention:
1.191     harris41 8849: 
1.394     bowersj2 8850:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8851:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8852: 
1.394     bowersj2 8853: For more detailed information, see lonnet specific documentation.
1.191     harris41 8854: 
1.394     bowersj2 8855: =head1 RETURN MESSAGES
1.191     harris41 8856: 
1.394     bowersj2 8857: =over 4
1.191     harris41 8858: 
1.394     bowersj2 8859: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8860: 
1.394     bowersj2 8861: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8862: when the connection is brought back up
1.191     harris41 8863: 
1.394     bowersj2 8864: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8865: for later delivery
1.191     harris41 8866: 
1.394     bowersj2 8867: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8868: 
1.394     bowersj2 8869: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8870: that was requested
1.191     harris41 8871: 
1.243     albertel 8872: =back
1.191     harris41 8873: 
1.243     albertel 8874: =head1 PUBLIC SUBROUTINES
1.191     harris41 8875: 
1.243     albertel 8876: =head2 Session Environment Functions
1.191     harris41 8877: 
1.243     albertel 8878: =over 4
1.191     harris41 8879: 
1.394     bowersj2 8880: =item * 
                   8881: X<appenv()>
1.949     raeburn  8882: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8883: the user envirnoment file, and will be restored for each access this
1.620     albertel 8884: user makes during this session, also modifies the %env for the current
1.949     raeburn  8885: process. Optional rolesarrayref - if defined contains a reference to an array
                   8886: of roles which are exempt from the restriction on modifying user.role entries 
                   8887: in the user's environment.db and in %env.    
1.191     harris41 8888: 
                   8889: =item *
1.394     bowersj2 8890: X<delenv()>
                   8891: B<delenv($regexp)>: removes all items from the session
                   8892: environment file that matches the regular expression in $regexp. The
1.620     albertel 8893: values are also delted from the current processes %env.
1.191     harris41 8894: 
1.795     albertel 8895: =item * get_env_multiple($name) 
                   8896: 
                   8897: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8898: values may be defined and end up as an array ref.
                   8899: 
                   8900: returns an array of values
                   8901: 
1.243     albertel 8902: =back
                   8903: 
                   8904: =head2 User Information
1.191     harris41 8905: 
1.243     albertel 8906: =over 4
1.191     harris41 8907: 
                   8908: =item *
1.394     bowersj2 8909: X<queryauthenticate()>
                   8910: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8911: authentication scheme
                   8912: 
                   8913: =item *
1.394     bowersj2 8914: X<authenticate()>
                   8915: B<authenticate($uname,$upass,$udom)>: try to
                   8916: authenticate user from domain's lib servers (first use the current
                   8917: one). C<$upass> should be the users password.
1.191     harris41 8918: 
                   8919: =item *
1.394     bowersj2 8920: X<homeserver()>
                   8921: B<homeserver($uname,$udom)>: find the server which has
                   8922: the user's directory and files (there must be only one), this caches
                   8923: the answer, and also caches if there is a borken connection.
1.191     harris41 8924: 
                   8925: =item *
1.394     bowersj2 8926: X<idget()>
                   8927: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8928: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8929: username, and only 1 username per ID in a specific domain) (returns
                   8930: hash: id=>name,id=>name)
1.191     harris41 8931: 
                   8932: =item *
1.394     bowersj2 8933: X<idrget()>
                   8934: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8935: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8936: 
                   8937: =item *
1.394     bowersj2 8938: X<idput()>
                   8939: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8940: 
                   8941: =item *
1.394     bowersj2 8942: X<rolesinit()>
                   8943: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8944: 
                   8945: =item *
1.551     albertel 8946: X<getsection()>
                   8947: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8948: course $cname, return section name/number or '' for "not in course"
                   8949: and '-1' for "no section"
                   8950: 
                   8951: =item *
1.394     bowersj2 8952: X<userenvironment()>
                   8953: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8954: passed in @what from the requested user's environment, returns a hash
                   8955: 
1.858     raeburn  8956: =item * 
                   8957: X<userlog_query()>
1.859     albertel 8958: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8959: activity.log file. %filters defines filters applied when parsing the
                   8960: log file. These can be start or end timestamps, or the type of action
                   8961: - log to look for Login or Logout events, check for Checkin or
                   8962: Checkout, role for role selection. The response is in the form
                   8963: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8964: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8965: 
1.243     albertel 8966: =back
                   8967: 
                   8968: =head2 User Roles
                   8969: 
                   8970: =over 4
                   8971: 
                   8972: =item *
                   8973: 
1.810     raeburn  8974: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8975:  F: full access
                   8976:  U,I,K: authentication modes (cxx only)
                   8977:  '': forbidden
                   8978:  1: user needs to choose course
                   8979:  2: browse allowed
1.766     albertel 8980:  A: passphrase authentication needed
1.243     albertel 8981: 
                   8982: =item *
                   8983: 
                   8984: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8985: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8986: and course level
                   8987: 
                   8988: =item *
                   8989: 
                   8990: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8991: explanation of a user role term
                   8992: 
1.832     raeburn  8993: =item *
                   8994: 
1.935     raeburn  8995: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8996: All arguments are optional. Returns a hash of a roles, either for
                   8997: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8998: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8999: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9000: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9001: For each key, value is set to colon-separated start and end times for
                   9002: the role.  If no username and domain are specified, will default to
1.934     raeburn  9003: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9004: of role statuses (active, future or previous), roles 
                   9005: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9006: to restrict the list of roles reported. If no array ref is 
                   9007: provided for types, will default to return only active roles.
1.834     albertel 9008: 
1.243     albertel 9009: =back
                   9010: 
                   9011: =head2 User Modification
                   9012: 
                   9013: =over 4
                   9014: 
                   9015: =item *
                   9016: 
                   9017: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   9018: user for the level given by URL.  Optional start and end dates (leave empty
                   9019: string or zero for "no date")
1.191     harris41 9020: 
                   9021: =item *
                   9022: 
1.243     albertel 9023: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9024: change a users, password, possible return values are: ok,
                   9025: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9026: refused
1.191     harris41 9027: 
                   9028: =item *
                   9029: 
1.243     albertel 9030: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9031: 
                   9032: =item *
                   9033: 
1.243     albertel 9034: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9035: modify user
1.191     harris41 9036: 
                   9037: =item *
                   9038: 
1.286     matthew  9039: modifystudent
                   9040: 
                   9041: modify a students enrollment and identification information.
                   9042: The course id is resolved based on the current users environment.  
                   9043: This means the envoking user must be a course coordinator or otherwise
                   9044: associated with a course.
                   9045: 
1.297     matthew  9046: This call is essentially a wrapper for lonnet::modifyuser and
                   9047: lonnet::modify_student_enrollment
1.286     matthew  9048: 
                   9049: Inputs: 
                   9050: 
                   9051: =over 4
                   9052: 
                   9053: =item B<$udom> Students loncapa domain
                   9054: 
                   9055: =item B<$uname> Students loncapa login name
                   9056: 
                   9057: =item B<$uid> Students id/student number
                   9058: 
                   9059: =item B<$umode> Students authentication mode
                   9060: 
                   9061: =item B<$upass> Students password
                   9062: 
                   9063: =item B<$first> Students first name
                   9064: 
                   9065: =item B<$middle> Students middle name
                   9066: 
                   9067: =item B<$last> Students last name
                   9068: 
                   9069: =item B<$gene> Students generation
                   9070: 
                   9071: =item B<$usec> Students section in course
                   9072: 
                   9073: =item B<$end> Unix time of the roles expiration
                   9074: 
                   9075: =item B<$start> Unix time of the roles start date
                   9076: 
                   9077: =item B<$forceid> If defined, allow $uid to be changed
                   9078: 
                   9079: =item B<$desiredhome> server to use as home server for student
                   9080: 
                   9081: =back
1.297     matthew  9082: 
                   9083: =item *
                   9084: 
                   9085: modify_student_enrollment
                   9086: 
                   9087: Change a students enrollment status in a class.  The environment variable
                   9088: 'role.request.course' must be defined for this function to proceed.
                   9089: 
                   9090: Inputs:
                   9091: 
                   9092: =over 4
                   9093: 
                   9094: =item $udom, students domain
                   9095: 
                   9096: =item $uname, students name
                   9097: 
                   9098: =item $uid, students user id
                   9099: 
                   9100: =item $first, students first name
                   9101: 
                   9102: =item $middle
                   9103: 
                   9104: =item $last
                   9105: 
                   9106: =item $gene
                   9107: 
                   9108: =item $usec
                   9109: 
                   9110: =item $end
                   9111: 
                   9112: =item $start
                   9113: 
                   9114: =back
                   9115: 
1.191     harris41 9116: 
                   9117: =item *
                   9118: 
1.243     albertel 9119: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9120: custom role; give a custom role to a user for the level given by URL.  Specify
                   9121: name and domain of role author, and role name
1.191     harris41 9122: 
                   9123: =item *
                   9124: 
1.243     albertel 9125: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9126: 
                   9127: =item *
                   9128: 
1.243     albertel 9129: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9130: 
                   9131: =back
                   9132: 
                   9133: =head2 Course Infomation
                   9134: 
                   9135: =over 4
1.191     harris41 9136: 
                   9137: =item *
                   9138: 
1.631     albertel 9139: coursedescription($courseid) : returns a hash of information about the
                   9140: specified course id, including all environment settings for the
                   9141: course, the description of the course will be in the hash under the
                   9142: key 'description'
1.191     harris41 9143: 
                   9144: =item *
                   9145: 
1.624     albertel 9146: resdata($name,$domain,$type,@which) : request for current parameter
                   9147: setting for a specific $type, where $type is either 'course' or 'user',
                   9148: @what should be a list of parameters to ask about. This routine caches
                   9149: answers for 5 minutes.
1.243     albertel 9150: 
1.877     foxr     9151: =item *
                   9152: 
                   9153: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9154: data base, returning a hash that is keyed by the resource name and has
                   9155: values that are the resource value.  I believe that the timestamps and
                   9156: versions are also returned.
                   9157: 
                   9158: 
1.243     albertel 9159: =back
                   9160: 
                   9161: =head2 Course Modification
                   9162: 
                   9163: =over 4
1.191     harris41 9164: 
                   9165: =item *
                   9166: 
1.243     albertel 9167: writecoursepref($courseid,%prefs) : write preferences (environment
                   9168: database) for a course
1.191     harris41 9169: 
                   9170: =item *
                   9171: 
1.243     albertel 9172: createcourse($udom,$description,$url) : make/modify course
                   9173: 
                   9174: =back
                   9175: 
                   9176: =head2 Resource Subroutines
                   9177: 
                   9178: =over 4
1.191     harris41 9179: 
                   9180: =item *
                   9181: 
1.243     albertel 9182: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9183: 
                   9184: =item *
                   9185: 
1.243     albertel 9186: repcopy($filename) : subscribes to the requested file, and attempts to
                   9187: replicate from the owning library server, Might return
1.607     raeburn  9188: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9189: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9190: resource. Expects the local filesystem pathname
                   9191: (/home/httpd/html/res/....)
                   9192: 
                   9193: =back
                   9194: 
                   9195: =head2 Resource Information
                   9196: 
                   9197: =over 4
1.191     harris41 9198: 
                   9199: =item *
                   9200: 
1.243     albertel 9201: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9202: a vairety of different possible values, $varname should be a request
                   9203: string, and the other parameters can be used to specify who and what
                   9204: one is asking about.
                   9205: 
                   9206: Possible values for $varname are environment.lastname (or other item
                   9207: from the envirnment hash), user.name (or someother aspect about the
                   9208: user), resource.0.maxtries (or some other part and parameter of a
                   9209: resource)
1.204     albertel 9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: directcondval($number) : get current value of a condition; reads from a state
                   9214: string
1.204     albertel 9215: 
                   9216: =item *
                   9217: 
1.243     albertel 9218: condval($condidx) : value of condition index based on state
1.204     albertel 9219: 
                   9220: =item *
                   9221: 
1.243     albertel 9222: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9223: resource's metadata, $what should be either a specific key, or either
                   9224: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9225: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9226: 
                   9227: this function automatically caches all requests
1.191     harris41 9228: 
                   9229: =item *
                   9230: 
1.243     albertel 9231: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9232: network of library servers; returns file handle of where SQL and regex results
                   9233: will be stored for query
1.191     harris41 9234: 
                   9235: =item *
                   9236: 
1.243     albertel 9237: symbread($filename) : return symbolic list entry (filename argument optional);
                   9238: returns the data handle
1.191     harris41 9239: 
                   9240: =item *
                   9241: 
1.243     albertel 9242: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9243: a possible symb for the URL in $thisfn, and if is an encryypted
                   9244: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9245: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9246: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9247: 
1.191     harris41 9248: 
                   9249: =item *
                   9250: 
1.243     albertel 9251: symbclean($symb) : removes versions numbers from a symb, returns the
                   9252: cleaned symb
1.191     harris41 9253: 
                   9254: =item *
                   9255: 
1.243     albertel 9256: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9257: course map, user must be in a course for it to work.
1.191     harris41 9258: 
                   9259: =item *
                   9260: 
1.243     albertel 9261: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9262: 
                   9263: =item *
                   9264: 
1.243     albertel 9265: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9266: a random seed, all arguments are optional, if they aren't sent it uses the
                   9267: environment to derive them. Note: if symb isn't sent and it can't get one
                   9268: from &symbread it will use the current time as its return value
1.191     harris41 9269: 
                   9270: =item *
                   9271: 
1.243     albertel 9272: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9273: unfakeable, receipt
1.191     harris41 9274: 
                   9275: =item *
                   9276: 
1.620     albertel 9277: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9278: 
                   9279: =item *
                   9280: 
1.243     albertel 9281: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9282: 
                   9283: =item *
                   9284: 
1.243     albertel 9285: 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 9286: 
                   9287: =item *
                   9288: 
1.243     albertel 9289: 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 9290: 
                   9291: =item *
                   9292: 
1.243     albertel 9293: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9294: 
                   9295: =item *
                   9296: 
1.243     albertel 9297: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9298: forcing spreadsheet to reevaluate the resource scores next time.
                   9299: 
                   9300: =back
                   9301: 
                   9302: =head2 Storing/Retreiving Data
                   9303: 
                   9304: =over 4
1.191     harris41 9305: 
                   9306: =item *
                   9307: 
1.243     albertel 9308: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9309: for this url; hashref needs to be given and should be a \%hashname; the
                   9310: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9311: be derived from the env
1.191     harris41 9312: 
                   9313: =item *
                   9314: 
1.243     albertel 9315: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9316: uses critical subroutine
1.191     harris41 9317: 
                   9318: =item *
                   9319: 
1.243     albertel 9320: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9321: all args are optional
1.191     harris41 9322: 
                   9323: =item *
                   9324: 
1.717     albertel 9325: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9326: dumps the complete (or key matching regexp) namespace into a hash
                   9327: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9328: normally &store()ed into
                   9329: 
                   9330: $range should be either an integer '100' (give me the first 100
                   9331:                                            matching records)
                   9332:               or be  two integers sperated by a - with no spaces
                   9333:                  '30-50' (give me the 30th through the 50th matching
                   9334:                           records)
                   9335: 
                   9336: 
                   9337: =item *
                   9338: 
                   9339: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9340: replaces a &store() version of data with a replacement set of data
                   9341: for a particular resource in a namespace passed in the $storehash hash 
                   9342: reference
                   9343: 
                   9344: =item *
                   9345: 
1.243     albertel 9346: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9347: works very similar to store/cstore, but all data is stored in a
                   9348: temporary location and can be reset using tmpreset, $storehash should
                   9349: be a hash reference, returns nothing on success
1.191     harris41 9350: 
                   9351: =item *
                   9352: 
1.243     albertel 9353: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9354: similar to restore, but all data is stored in a temporary location and
                   9355: can be reset using tmpreset. Returns a hash of values on success,
                   9356: error string otherwise.
1.191     harris41 9357: 
                   9358: =item *
                   9359: 
1.243     albertel 9360: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9361: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9362: 
                   9363: =item *
                   9364: 
1.243     albertel 9365: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9366: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9367: 
                   9368: =item *
                   9369: 
1.243     albertel 9370: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9371: namesp ($udom and $uname are optional)
1.191     harris41 9372: 
                   9373: =item *
                   9374: 
1.702     albertel 9375: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9376: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9377: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9378: 
1.702     albertel 9379: $range should be either an integer '100' (give me the first 100
                   9380:                                            matching records)
                   9381:               or be  two integers sperated by a - with no spaces
                   9382:                  '30-50' (give me the 30th through the 50th matching
                   9383:                           records)
1.449     matthew  9384: =item *
                   9385: 
                   9386: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9387: $store can be a scalar, an array reference, or if the amount to be 
                   9388: incremented is > 1, a hash reference.
                   9389: 
                   9390: ($udom and $uname are optional)
1.191     harris41 9391: 
                   9392: =item *
                   9393: 
1.243     albertel 9394: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9395: ($udom and $uname are optional)
1.191     harris41 9396: 
                   9397: =item *
                   9398: 
1.243     albertel 9399: cput($namespace,$storehash,$udom,$uname) : critical put
                   9400: ($udom and $uname are optional)
1.191     harris41 9401: 
                   9402: =item *
                   9403: 
1.748     albertel 9404: newput($namespace,$storehash,$udom,$uname) :
                   9405: 
                   9406: Attempts to store the items in the $storehash, but only if they don't
                   9407: currently exist, if this succeeds you can be certain that you have 
                   9408: successfully created a new key value pair in the $namespace db.
                   9409: 
                   9410: 
                   9411: Args:
                   9412:  $namespace: name of database to store values to
                   9413:  $storehash: hashref to store to the db
                   9414:  $udom: (optional) domain of user containing the db
                   9415:  $uname: (optional) name of user caontaining the db
                   9416: 
                   9417: Returns:
                   9418:  'ok' -> succeeded in storing all keys of $storehash
                   9419:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9420:                         least <key> already existed in the db (other
                   9421:                         requested keys may also already exist)
                   9422:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9423:  'con_lost' -> unable to contact request server
                   9424:  'refused' -> action was not allowed by remote machine
                   9425: 
                   9426: 
                   9427: =item *
                   9428: 
1.243     albertel 9429: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9430: reference filled in from namesp (encrypts the return communication)
                   9431: ($udom and $uname are optional)
1.191     harris41 9432: 
                   9433: =item *
                   9434: 
1.243     albertel 9435: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9436: critical subroutine
                   9437: 
1.806     raeburn  9438: =item *
                   9439: 
1.860     raeburn  9440: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9441: array reference filled in from namespace found in domain level on either
                   9442: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9443: 
                   9444: =item *
                   9445: 
1.860     raeburn  9446: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9447: domain level either on specified domain server ($uhome) or primary domain 
                   9448: server ($udom and $uhome are optional)
1.806     raeburn  9449: 
1.943     raeburn  9450: =item * 
                   9451: 
                   9452: get_domain_defaults($target_domain) : returns hash with defaults for
                   9453: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9454: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9455: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9456: Values are retrieved from cache (if current), or from domain's configuration.db
                   9457: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9458: or lonTabs/domain.tab. 
                   9459: 
                   9460: %domdefaults = &get_auth_defaults($target_domain);
                   9461: 
1.243     albertel 9462: =back
                   9463: 
                   9464: =head2 Network Status Functions
                   9465: 
                   9466: =over 4
1.191     harris41 9467: 
                   9468: =item *
                   9469: 
                   9470: dirlist($uri) : return directory list based on URI
                   9471: 
                   9472: =item *
                   9473: 
1.243     albertel 9474: spareserver() : find server with least workload from spare.tab
                   9475: 
                   9476: =back
                   9477: 
                   9478: =head2 Apache Request
                   9479: 
                   9480: =over 4
1.191     harris41 9481: 
                   9482: =item *
                   9483: 
1.243     albertel 9484: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9485: localhost, posts hash
                   9486: 
                   9487: =back
                   9488: 
                   9489: =head2 Data to String to Data
                   9490: 
                   9491: =over 4
1.191     harris41 9492: 
                   9493: =item *
                   9494: 
1.243     albertel 9495: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9496: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9497: 
                   9498: =item *
                   9499: 
1.243     albertel 9500: hashref2str($hashref) : convert a hashref into a string complete with
                   9501: escaping and '=' and '&' separators, supports elements that are
                   9502: arrayrefs and hashrefs
1.191     harris41 9503: 
                   9504: =item *
                   9505: 
1.243     albertel 9506: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9507: with escaping and '&' separators, supports elements that are arrayrefs
                   9508: and hashrefs
1.191     harris41 9509: 
                   9510: =item *
                   9511: 
1.243     albertel 9512: str2hash($string) : convert string to hash using unescaping and
                   9513: splitting on '=' and '&', supports elements that are arrayrefs and
                   9514: hashrefs
1.191     harris41 9515: 
                   9516: =item *
                   9517: 
1.243     albertel 9518: str2array($string) : convert string to hash using unescaping and
                   9519: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9520: 
                   9521: =back
                   9522: 
                   9523: =head2 Logging Routines
                   9524: 
                   9525: =over 4
                   9526: 
                   9527: These routines allow one to make log messages in the lonnet.log and
                   9528: lonnet.perm logfiles.
1.191     harris41 9529: 
                   9530: =item *
                   9531: 
1.243     albertel 9532: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9533: 
                   9534: =item *
                   9535: 
1.243     albertel 9536: logthis() : append message to the normal lonnet.log file, it gets
                   9537: preiodically rolled over and deleted.
1.191     harris41 9538: 
                   9539: =item *
                   9540: 
1.243     albertel 9541: logperm() : append a permanent message to lonnet.perm.log, this log
                   9542: file never gets deleted by any automated portion of the system, only
                   9543: messages of critical importance should go in here.
                   9544: 
                   9545: =back
                   9546: 
                   9547: =head2 General File Helper Routines
                   9548: 
                   9549: =over 4
1.191     harris41 9550: 
                   9551: =item *
                   9552: 
1.481     raeburn  9553: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9554: (a) files in /uploaded
                   9555:   (i) If a local copy of the file exists - 
                   9556:       compares modification date of local copy with last-modified date for 
                   9557:       definitive version stored on home server for course. If local copy is 
                   9558:       stale, requests a new version from the home server and stores it. 
                   9559:       If the original has been removed from the home server, then local copy 
                   9560:       is unlinked.
                   9561:   (ii) If local copy does not exist -
                   9562:       requests the file from the home server and stores it. 
                   9563:   
                   9564:   If $caller is 'uploadrep':  
                   9565:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9566:     for request for files originally uploaded via DOCS. 
                   9567:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9568:   
                   9569:   Otherwise:
                   9570:      This indicates a call from the content generation phase of the request.
                   9571:      -  returns the entire contents of the file or -1.
                   9572:      
                   9573: (b) files in /res
                   9574:    - returns the entire contents of a file or -1; 
                   9575:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9576: 
1.712     albertel 9577: 
                   9578: =item *
                   9579: 
                   9580: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9581:                   reference
                   9582: 
                   9583: returns either a stat() list of data about the file or an empty list
                   9584: if the file doesn't exist or couldn't find out about it (connection
                   9585: problems or user unknown)
                   9586: 
1.191     harris41 9587: =item *
                   9588: 
1.243     albertel 9589: filelocation($dir,$file) : returns file system location of a file
                   9590: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9591: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9592: and a file of ../bob will become /a/bob)
1.191     harris41 9593: 
                   9594: =item *
                   9595: 
                   9596: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9597: filelocation except for hrefs
                   9598: 
                   9599: =item *
                   9600: 
                   9601: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9602: 
1.243     albertel 9603: =back
                   9604: 
1.608     albertel 9605: =head2 Usererfile file routines (/uploaded*)
                   9606: 
                   9607: =over 4
                   9608: 
                   9609: =item *
                   9610: 
                   9611: userfileupload(): main rotine for putting a file in a user or course's
                   9612:                   filespace, arguments are,
                   9613: 
1.620     albertel 9614:  formname - required - this is the name of the element in $env where the
1.608     albertel 9615:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9616:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9617:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9618:  coursedoc - if true, store the file in the course of the active role
                   9619:              of the current user
                   9620:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9621:          if undefined, it will be placed in "unknown"
                   9622: 
                   9623:  (This routine calls clean_filename() to remove any dangerous
                   9624:  characters from the filename, and then calls finuserfileupload() to
                   9625:  complete the transaction)
                   9626: 
                   9627:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9628:  and /adm/notfound.html if unsuccessful
                   9629: 
                   9630: =item *
                   9631: 
                   9632: clean_filename(): routine for cleaing a filename up for storage in
                   9633:                  userfile space, argument is:
                   9634: 
                   9635:  filename - proposed filename
                   9636: 
                   9637: returns: the new clean filename
                   9638: 
                   9639: =item *
                   9640: 
                   9641: finishuserfileupload(): routine that creaes and sends the file to
                   9642: userspace, probably shouldn't be called directly
                   9643: 
                   9644:   docuname: username or courseid of destination for the file
                   9645:   docudom: domain of user/course of destination for the file
                   9646:   formname: same as for userfileupload()
                   9647:   fname: filename (inculding subdirectories) for the file
                   9648: 
                   9649:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9650:  and /adm/notfound.html if unsuccessful
                   9651: 
                   9652: =item *
                   9653: 
                   9654: renameuserfile(): renames an existing userfile to a new name
                   9655: 
                   9656:   Args:
                   9657:    docuname: username or courseid of destination for the file
                   9658:    docudom: domain of user/course of destination for the file
                   9659:    old: current file name (including any subdirs under userfiles)
                   9660:    new: desired file name (including any subdirs under userfiles)
                   9661: 
                   9662: =item *
                   9663: 
                   9664: mkdiruserfile(): creates a directory is a userfiles dir
                   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:    dir: dir to create (including any subdirs under userfiles)
                   9670: 
                   9671: =item *
                   9672: 
                   9673: removeuserfile(): removes a file that exists in userfiles
                   9674: 
                   9675:   Args:
                   9676:    docuname: username or courseid of destination for the file
                   9677:    docudom: domain of user/course of destination for the file
                   9678:    fname: filname to delete (including any subdirs under userfiles)
                   9679: 
                   9680: =item *
                   9681: 
                   9682: removeuploadedurl(): convience function for removeuserfile()
                   9683: 
                   9684:   Args:
                   9685:    url:  a full /uploaded/... url to delete
                   9686: 
1.747     albertel 9687: =item * 
                   9688: 
                   9689: get_portfile_permissions():
                   9690:   Args:
                   9691:     domain: domain of user or course contain the portfolio files
                   9692:     user: name of user or num of course contain the portfolio files
                   9693:   Returns:
                   9694:     hashref of a dump of the proper file_permissions.db
                   9695:    
                   9696: 
                   9697: =item * 
                   9698: 
                   9699: get_access_controls():
                   9700: 
                   9701: Args:
                   9702:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9703:   group: (optional) the group you want the files associated with
                   9704:   file: (optional) the file you want access info on
                   9705: 
                   9706: Returns:
1.749     raeburn  9707:     a hash (keys are file names) of hashes containing
                   9708:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9709:         values are XML containing access control settings (see below) 
1.747     albertel 9710: 
                   9711: Internal notes:
                   9712: 
1.749     raeburn  9713:  access controls are stored in file_permissions.db as key=value pairs.
                   9714:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9715:         where scope -> public,guest,course,group,domains or users.
                   9716:               end -> UNIX time for end of access (0 -> no end date)
                   9717:               start -> UNIX time for start of access
                   9718: 
                   9719:     value -> XML description of access control
                   9720:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9721:             <start></start>
                   9722:             <end></end>
                   9723: 
                   9724:             <password></password>  for scope type = guest
                   9725: 
                   9726:             <domain></domain>     for scope type = course or group
                   9727:             <number></number>
                   9728:             <roles id="">
                   9729:              <role></role>
                   9730:              <access></access>
                   9731:              <section></section>
                   9732:              <group></group>
                   9733:             </roles>
                   9734: 
                   9735:             <dom></dom>         for scope type = domains
                   9736: 
                   9737:             <users>             for scope type = users
                   9738:              <user>
                   9739:               <uname></uname>
                   9740:               <udom></udom>
                   9741:              </user>
                   9742:             </users>
                   9743:            </scope> 
                   9744:               
                   9745:  Access data is also aggregated for each file in an additional key=value pair:
                   9746:  key -> path to file/file_name\0accesscontrol 
                   9747:  value -> reference to hash
                   9748:           hash contains key = value pairs
                   9749:           where key = uniqueID:scope_end_start
                   9750:                 value = UNIX time record was last updated
                   9751: 
                   9752:           Used to improve speed of look-ups of access controls for each file.  
                   9753:  
                   9754:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9755: 
                   9756: modify_access_controls():
                   9757: 
                   9758: Modifies access controls for a portfolio file
                   9759: Args
                   9760: 1. file name
                   9761: 2. reference to hash of required changes,
                   9762: 3. domain
                   9763: 4. username
                   9764:   where domain,username are the domain of the portfolio owner 
                   9765:   (either a user or a course) 
                   9766: 
                   9767: Returns:
                   9768: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9769: 2. result of deletions ('ok' or 'error', with error message).
                   9770: 3. reference to hash of any new or updated access controls.
                   9771: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9772:    key = integer (inbound ID)
                   9773:    value = uniqueID  
1.747     albertel 9774: 
1.608     albertel 9775: =back
                   9776: 
1.243     albertel 9777: =head2 HTTP Helper Routines
                   9778: 
                   9779: =over 4
                   9780: 
1.191     harris41 9781: =item *
                   9782: 
                   9783: escape() : unpack non-word characters into CGI-compatible hex codes
                   9784: 
                   9785: =item *
                   9786: 
                   9787: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9788: 
1.243     albertel 9789: =back
                   9790: 
                   9791: =head1 PRIVATE SUBROUTINES
                   9792: 
                   9793: =head2 Underlying communication routines (Shouldn't call)
                   9794: 
                   9795: =over 4
                   9796: 
                   9797: =item *
                   9798: 
                   9799: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9800: 
                   9801: =item *
                   9802: 
                   9803: reply() : uses subreply to send a message to remote machine, logs all failures
                   9804: 
                   9805: =item *
                   9806: 
                   9807: critical() : passes a critical message to another server; if cannot
                   9808: get through then place message in connection buffer directory and
                   9809: returns con_delayed, if incapable of saving message, returns
                   9810: con_failed
                   9811: 
                   9812: =item *
                   9813: 
                   9814: reconlonc() : tries to reconnect lonc client processes.
                   9815: 
                   9816: =back
                   9817: 
                   9818: =head2 Resource Access Logging
                   9819: 
                   9820: =over 4
                   9821: 
                   9822: =item *
                   9823: 
                   9824: flushcourselogs() : flush (save) buffer logs and access logs
                   9825: 
                   9826: =item *
                   9827: 
                   9828: courselog($what) : save message for course in hash
                   9829: 
                   9830: =item *
                   9831: 
                   9832: courseacclog($what) : save message for course using &courselog().  Perform
                   9833: special processing for specific resource types (problems, exams, quizzes, etc).
                   9834: 
1.191     harris41 9835: =item *
                   9836: 
                   9837: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9838: as a PerlChildExitHandler
1.243     albertel 9839: 
                   9840: =back
                   9841: 
                   9842: =head2 Other
                   9843: 
                   9844: =over 4
                   9845: 
                   9846: =item *
                   9847: 
                   9848: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9849: 
                   9850: =back
                   9851: 
                   9852: =cut
1.877     foxr     9853: 

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